python flask - serving static files

后端 未结 2 1438
灰色年华
灰色年华 2021-01-02 01:16

I\'m trying to serve a static file using flask. I don\'t know how to use the url_for function. All my routes generating dynamic content are working fine, I\'ve imported url_

2条回答
  •  Happy的楠姐
    2021-01-02 01:26

    You are getting the correct output for what you are doing. url_for generates the url for the arguments you give it. In your case, you are generating the url for the hi.html file in the static directory. If you want to actually output the file, you would want to

    from flask import render_template, url_for
    
    ...
    
        return render_template(url_for("static", filename="hi.html"))
    

    But at this point, your static directory would need to be under the templates directory (where ever that is configured to live).

    If you are going to be serving static html files like this, then my suggestion would be to serve them outside of the flask application by routing traffic to /static/.* directly from your web server. There are plenty of examples on the web for doing this using nginx or apache.

提交回复
热议问题