2017-05-27 77 views
1

我有一个简单的Flask服务器。会发生什么是用户首先上传音乐文件到我的服务器(mp3),我的服务器处理此文件,创建一个新的结果文件(MusicXML),然后我在浏览器上呈现该文件。Flask文件没有更新Javascript取回

这里是我的瓶路由:

@app.route('/', methods=['GET', 'POST']) 
def index(): 
    if request.method == "GET": 
    return render_template('index.html', request="GET") 
    else: 
    file = request.files['file'] 
    handle_file(file) 
    return render_template('index.html', request="POST") 

@app.route('/mxl') 
def mxl(): 
    return send_from_directory(UPLOAD_FOLDER, 'piece.mxl') 

def handle_file(file): 
    filename = secure_filename(file.filename) 
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) 
    file.save(filepath) 
    pitches = mir.transcribe(filepath) 
    os.remove(filepath) 

所以在这里我们可以看到,首先,在'/'用户访问。然后上传音乐文件(POST方法),并调用handle_file()。这会调用mir.transcribe来处理文件并创建一个“结果”musicXML文件。

使用Music21模块创建MusicXML文件并将其存储在静态文件夹中。因此,在包mir我们:

def transcribe(filename): 
    ... 
    note_stream.write("musicxml", "static/piece.mxl") 

handle_file()回报,我们称之为render_templaterequest='POST'。这里是我的index.html

{%- extends "base.html" %} 

{% import "bootstrap/utils.html" as utils %} 

{% block content %} 
    {% if request == "GET": %} 

    <!-- uploading file form --> 

    {% else: %} 

    <script> 
    // This is the important part, where we call fetch to obtain the 
    // MusicXML file we created on the server. 
    fetch('http://localhost:5000/mxl') 
     .then(function (response) { 
     return response.text(); 
     }) 
     .then(function (mxl) { 
     console.log(mxl); 
     return embed.loadMusicXML(mxl); 
     }) 
     .then(function() { 
     console.log("Score loaded in the embed!"); 
     }) 
     .catch(function (error) { 
     console.log("Unable to load the score!"); 
     }); 
    </script> 

    {% endif %} 
{% endblock %} 

{% block scripts %} 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script> 
    <!--<script src="static/js/record.js"></script>--> 
{% endblock %} 

因此,你可以看到,我们render_template后,fetch被调用。

问题是,有时候,fetch不会返回新创建的MusicXML文件,而是返回它以前的版本。但是,如果我转到我的static文件夹,那里包含的MusicXML文件就是新文件夹!

这是为什么发生?

+0

难道你检查你的响应头(特别是'Cache-Control')? – errata

+0

这实际上是指向我的问题,我认为(不确定)这个问题只在我开启devtools时才存在,因为我已经在devtools打开时禁用了缓存。因此,当我的devtools打开时,头文件中有一个No-Cache,当devtools没有时,我没有。我该怎么做,所以无缓存总是在那里为获取声明? – pk1914

回答

2

如果你愿意,你可以强制对所有请求禁用缓存,是这样的:

@app.after_request 
def add_header(response): 
    response.cache_control.max_age = 300 
    if 'Cache-Control' not in response.headers: 
     response.headers['Cache-Control'] = 'no-store' 
    return response 

,或者你可以为所有的静态文件的默认值在app

app = Flask(__name___) 
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 60 
+0

那我不得不返回一个Response吗?而不是使用'send_from_directory'? – pk1914

+0

我用我的代码替换了该代码,没有任何更改。响应头中的'Cache-Control'仍然是'public,max-age = 43200'。 – pk1914

+0

啊jeez,对不起,我的不好,在一秒内更新的答案! – errata