2017-05-27 81 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