search

Home  >  Q&A  >  body text

python - flask redirect redirection problem?

The code is as follows. The picture can be uploaded successfully, but the picture cannot be displayed after the picture is uploaded successfully. Is this the correct way to write redirect?

#!/usr/bin/env python3
# -*- coding:utf-8-*-

import os

from flask import Flask, render_template, request, redirect, url_for
from flask_uploads import UploadSet, configure_uploads, patch_request_class, IMAGES

app = Flask(__name__)

app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + "/upload/img"
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)


@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        file_url = photos.url(filename)
        print("filename = %s, file_url = %s" % (filename, file_url))
        return redirect(url_for('index', file_url=file_url))
    return render_template('index.html', file_url=None)


if __name__ == '__main__':
    app.run(port=8080)
<!doctype html>
<html>
<head>
    <title>Demo-上传文件</title>

</head>
<body>
<h1>文件上传demo</h1>
<form method="post" enctype="multipart/form-data">
    <input type="file" name="photo">
    <input type="submit" value="上传">
</form>
<br>
{% if file_url %}
    <img src="{{ file_url }}" alt="">
    {% else %}
    <p>还没有上传文件</p>
{% endif %}
</body>
</html>

----------Update----------
Modified the index routing and achieved the desired effect:

@app.route('/', methods=['POST', 'GET'])
def index():
    file_url = None
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        file_url = photos.url(filename)
        print("filename = %s, file_url = %s" % (filename, file_url))
    return render_template('index.html', file_url=file_url)

But was the previous thinking wrong?

phpcn_u1582phpcn_u15822743 days ago810

reply all(1)I'll reply

  • 滿天的星座

    滿天的星座2017-05-18 10:50:50

    For image display, you need to define a route for sending static files, and you can use send_from_directory for corresponding processing.

    @app.route('/get_media/<path:filename>', methods=['GET'])
    def get_media(filename):
       return send_from_directory('/media/', filename)

    reply
    0
  • Cancelreply