url_for为静态文件夹创建了错误的路径

时间:2019-10-24 12:17:40

标签: python flask

我们在服务器上运行了Flask应用(xxxx.edu.au:5000)。但是,我们设置了xxxx.edu.au/getseq代理,将请求转发到xxxx.edu.au:5000

不幸的是,现在在浏览器中,我们得到了Loading failed for the <script> with source “https://xxxx.edu.au/static/vehicle.js”

这是flask应用程序的结构:

flask
├── getseq.py
├── static
│   └── vehicle.js
└── templates
    └── example.html

烧瓶应用程序写在这里:

$ cat getseq.py
from flask import Flask, render_template, request
from wtforms import Form, RadioField, TextAreaField
from wtforms.widgets import TextArea

SECRET_KEY = 'development'

app = Flask(__name__)
app.config.from_object(__name__)
...

@app.route("/getseq/<mrna_id>", methods=['post', 'get'])    
def get_sequences(mrna_id):
    ...
    return render_template('example.html', form=form)

@app.route("/getseq/health", methods=['get'])
def health():
    response = app.response_class(
        status=200,
        mimetype='text/html'
    )
    return response

if __name__ == '__main__':
    print("starting...")
    app.run(host='0.0.0.0',port=5000,debug=True)

在这里定义路径vehicle.js

$ cat templates/example.html 
<script type="text/javascript" src="{{url_for('static', filename='vehicle.js')}}"></script>
...

如何更改url_for还是必须更改getseq.py

先谢谢您

1 个答案:

答案 0 :(得分:0)

在不重复您的问题的情况下,很难说出是什么原因导致您的静态资产失败。作为一种解决方法,您可以在服务器上阅读vehicle.js,对其进行base64编码,将其传递到模板上下文中,并使用以下命令呈现脚本标签:

<script type="text/javascript" src="data:text/javascript;base64,{{ base64_encoded_data }}"></script>

编辑 在您的视图处理程序中:

import base64


@app.route("/getseq/<mrna_id>", methods=['post', 'get'])    
def get_sequences(mrna_id):
    with open('static/vehicle.js', 'rb') as f:
        base64_encoded_data = base64.b64encode(f.read())
    return render_template('example.html', form=form, base64_encoded_data=base64_encoded_data)