Javascript获取时Flask文件未更新

2024-09-28 22:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的烧瓶服务器。用户首先将音乐文件上传到我的服务器(mp3),我的服务器处理这个文件,创建一个新的结果文件(MusicXML),然后我在浏览器上呈现该文件。在

这是我的烧瓶路线:

@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,后者处理文件并创建一个“result”musicXML文件。在

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

^{pr2}$

handle_file()返回时,我们用request='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文件就是新的!在

为什么会这样?在


Tags: 文件thegetindexreturnrequesthtmlscript
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:25

如果需要,可以强制禁用所有请求的缓存,例如:

@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中的所有静态文件设置默认值:

^{pr2}$

相关问题 更多 >