4

For my Flask app I use 'windows-1251' encoding. To draw a template I set 'Content-Type' as follows:

from flask.helpers import make_response

def render_tmpl_dummy():
    response = make_response("Some Russian text here")
    response.headers['Content-Type'] = 'text/html; charset=windows-1251'
    return response

And all fine here. But my static js-files also in 'windows-1251'. So, is there any way to set 'Content-Type=application/x-javascript; charset=windows-1251' for all static files? (PS: I do not want to convert them to UTF-8 manually in advance, this method is not suitable for me)

Alex Che
  • 111
  • 1
  • 4

2 Answers2

0

This is how I was able to give all files with a custom extension in the static folder a custom MIME type on the development server:

if __name__ == '__main__':

    CUSTOM_FILE_EXTENSION = '.jsonl'
    CUSTOM_MIME_TYPE = 'application/jsonl+json'

    @flask_app.route(flask_app.static_url_path + '/' + '<path:path>' + CUSTOM_FILE_EXTENSION)
    def jsonl_mime_type(path):
        return flask.send_from_directory(
            directory=flask_app.static_folder,
            path=path + CUSTOM_FILE_EXTENSION,
            mimetype=CUSTOM_MIME_TYPE
        )

In effect, I simply reinvented the Flask static web server, which apparently consists of a single call to add_url_rule() in the Flask constructor:

        self.add_url_rule(
            f"{self.static_url_path}/<path:filename>",
            endpoint="static",
            host=static_host,
            view_func=lambda **kw: self_ref().send_static_file(**kw),
        )

I went to all this trouble so the development server behaved more like production, where Apache has a gentler way to set MIME type.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
-1

Your static files shouldn't be served by the web server other than in development, so converting the file encoding is the correct method.

If your reason for not converting the files first is due to volume, see How to convert a file to utf-8 in Python? to see how to automate it.

Community
  • 1
  • 1
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
  • It makes me uncomfortable to convert files, because I get them from the parent project. In fact, this project - it cut-off-part of parent large project, with a small specific task. That is why I use Flask and its web server for "production". – Alex Che Feb 14 '13 at 15:56
  • This belongs as a comment. It offers a possible solution to an alternative question, and with more certainty than it merits. – Bob Stein Jan 05 '22 at 17:04