另一種方式來發送靜態文件是使用這樣一個包羅萬象的規則:
@app.route('/<path:path>')
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()
我用這個來嘗試開發時最小化設置。我從http://flask.pocoo.org/snippets/57/
的想法。此外,我用我的單機上燒瓶但在生產服務器和Apache部署發展。我使用:
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('/<path:path>', 'static_file', static_file)
app.run()
這是一個爲靜態文件工作的人, 謝謝。 +1 – 2014-06-09 01:16:47
值得一提的是,static_folder不必位於項目文件夾中。例如static_folder ='/ app/ui'很好。 – ashic 2017-10-18 23:58:09