Static files in Flask - robot.txt, sitemap.xml (mod_wsgi)

前端 未结 10 582
后悔当初
后悔当初 2020-11-29 15:15

Is there any clever solution to store static files in Flask\'s application root directory. robots.txt and sitemap.xml are expected to be found in /, so my idea was to create

10条回答
  •  醉梦人生
    2020-11-29 16:02

    Another way to send static files is to use a catch-all rule like this:

    @app.route('/')
    def catch_all(path):
        if not app.debug:
            flask.abort(404)
        try:
            f = open(path)
        except IOError, e:
            flask.abort(404)
            return
        return f.read()
    

    I use this to try to minimise the set-up when developing. I got the idea from http://flask.pocoo.org/snippets/57/

    Further, I'm developing using flask on my standalone machine but deploying with Apache in production server. I use:

    file_suffix_to_mimetype = {
        '.css': 'text/css',
        '.jpg': 'image/jpeg',
        '.html': 'text/html',
        '.ico': 'image/x-icon',
        '.png': 'image/png',
        '.js': 'application/javascript'
    }
    def static_file(path):
        try:
            f = open(path)
        except IOError, e:
            flask.abort(404)
            return
        root, ext = os.path.splitext(path)
        if ext in file_suffix_to_mimetype:
            return flask.Response(f.read(), mimetype=file_suffix_to_mimetype[ext])
        return f.read()
    
    [...]
    
    if __name__ == '__main__':
        parser = optparse.OptionParser()
        parser.add_option('-d', '--debug', dest='debug', default=False,
                          help='turn on Flask debugging', action='store_true')
    
        options, args = parser.parse_args()
    
        if options.debug:
            app.debug = True
            # set up flask to serve static content
            app.add_url_rule('/', 'static_file', static_file)
        app.run()
    

提交回复
热议问题