How to create response for CSS or javascript file request?

I see we can use html, file, file_streaming and some other to respond appropriately.

I am currently using app.static to serve other file including css, js.

How can i create a response for css, js files without app.static?

For the time being, I am doing this

from sanic import HTTPResponse

async def css(body, headers=None):
    content_type: str = "text/css; charset=utf-8"
    return HTTPResponse(body, headers=headers, content_type=content_type)

async def serve_css(_):
    css_file = await open(f'./static/css/{css_file_name}')
    content = await
    await css_file.close()
    return await css(content)

This is a cut down version of my code. I believe this is not available as builtin.

That seems fine. I might consider using raw though. Might be a little more clean. Just make sure you set the content type properly

Understood, thank you :heart:

I have another question :sweat_smile:, I have been asking a lot of questions from past 5 days or so, sorry for troubling :sweat_smile:

How can i setup http/2.2 currently I guess http/1.1 is running?

No worries. I am happy to answer and help. :sunglasses:

Sanic server does not currently support HTTP/2, and likely never will. It is a flawed protocol (IMO). We are, however, exploring the possibility of adding HTTP/3. Early stages though.

If you would like to have HTTP/2, then your best bet is to enable it at the proxy layer with nginx. There is a pretty thorough guide for proxying from nginx to Sanic. You would just need to adapt it to add HTTP/2.

1 Like