belyalov / tinyweb

Simple and lightweight HTTP async server for micropython
MIT License
239 stars 40 forks source link

Sendfile detect mimetype #35

Open metachris opened 3 years ago

metachris commented 3 years ago

Try to auto-detect mime-type based on filename.

metachris commented 3 years ago

What do you think about this?

Browsers are complaining if we send eg. css files without the correct content type. This auto-detect is particularly useful if serving static files like this:

@app.route('/webfiles-static/<fn>')
async def images(req, resp, fn):
    await resp.send_file('webfiles-static/{}'.format(fn))
belyalov commented 3 years ago

Hey @metachris

Sorry for late reply - got some Christmas related mess last weeks.. ))

I was considering adding this before - the problem was increased footprint, and, as I remember it would work for esp8266, but leaving only feeew of RAM free..

Since it is not widely used I decided not to implement it.

P.S. For the same reason I've omitted adding response status codes like (200 OK, 404 Not Found).

metachris commented 3 years ago

I understand. Didn't know tinyweb code itself already pushes the limit so far :)

keredson commented 2 years ago

the code length memory issue is (thankfully) likely to soon be a thing of the past: https://github.com/micropython/micropython/pull/8191 perhaps we can revisit this then?

eyJhb commented 1 year ago

It would be nice, if this could be a separate function, that could be used for detection the mime type based on a filename. The reason to put as an external function, would be in the case of gzipped files, ie. main.js.gz.

contentType = web.guessContentType(filename)
res.send_file(filename, content_type = contentType)

Something like the above usecase.

Also, would be nice to use filename.rfind(b'.', 1)[-1] instead, as that would decrease how much of the string is searched. Besides this, all the . in front of the MIME_TYPES_PER_EXT could be removed, so that string concatenation is not required.

@keredson luckily it is merged and now a thing of the past AFAIK :)