Python 如何重定向到烧瓶的上一页?

Python 如何重定向到烧瓶的上一页?,python,html,redirect,flask,Python,Html,Redirect,Flask,我对flask还处于初级阶段,正在尝试创建一个web应用程序。用户将从文件浏览器上传一张照片,图像显示在屏幕上(感谢我找到的答案) 我的问题是,当我在确认页面单击“返回”时,我想重定向到文件上载页面(),但它似乎根本不起作用。url更改,但页面仍处于/uploadconfirmation页面,该页面询问用户是否要继续。我不确定这是否是由于我发现的显示图像的代码造成的 感谢您的帮助 图像: 代码: main.py import os from flask import Flask, flash,

我对flask还处于初级阶段,正在尝试创建一个web应用程序。用户将从文件浏览器上传一张照片,图像显示在屏幕上(感谢我找到的答案)

我的问题是,当我在确认页面单击“返回”时,我想重定向到文件上载页面(),但它似乎根本不起作用。url更改,但页面仍处于/uploadconfirmation页面,该页面询问用户是否要继续。我不确定这是否是由于我发现的显示图像的代码造成的

感谢您的帮助

图像:

代码:

main.py

import os
from flask import Flask, flash, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'C:/Users/yurik/OneDrive/FYPCode/code+images/FullProject/imagesUploaded'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)

app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# specifies max file size = 16MB
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# HOME:
#index method,returns index.html
@app.route('/home')
def index():                             
    return render_template('index.html')

# UPLOAD FILE:  
@app.route('/upload')
def upload_page():
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        # file is uploaded to imagesUploaded folder in FullProject
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('file_confirm', filename=filename))
        else:
            flash('Allowed file types are png, jpg, jpeg, gif')
            return redirect(request.url)

# FILE CONFIRMATION/show file uploaded:
# Returns html page
@app.route('/show/<filename>')
def file_confirm(filename):
    filename = 'http://127.0.0.1:5000/uploadconfirmation/' + filename
    return render_template('uploadconfirmation.html', filename=filename)

# returns image
@app.route('/uploadconfirmation/<filename>')
def show_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

# run flask app and .py file
if __name__ == '__main__':
    app.run()
导入操作系统
从flask导入flask、flash、请求、重定向、url、呈现模板、从目录发送
从werkzeug.utils导入安全文件名
上传文件夹='C:/Users/yurik/OneDrive/FYPCode/code+images/FullProject/imagesupload'
允许的扩展名=set(['png','jpg','jpeg','gif'])
app=烧瓶(名称)
app.secret\u key=“秘钥”
app.config['UPLOAD\u FOLDER']=UPLOAD\u FOLDER
#指定最大文件大小=16MB
app.config['MAX\u CONTENT\u LENGTH']=16*1024*1024
允许的def_文件(文件名):
在文件名和文件名中返回“.”。rsplit(“.”,1)[1]。在允许的扩展名中返回lower()
#主页:
#index方法,返回index.html
@应用程序路径(“/home”)
def index():
返回渲染模板('index.html')
#上载文件:
@app.route(“/upload”)
def上传页面():
返回呈现模板('upload.html')
@app.route('/',methods=['POST'])
def upload_文件():
如果request.method==“POST”:
#检查post请求是否包含文件部分
如果“文件”不在request.files中:
闪存(“无文件部分”)
返回重定向(request.url)
file=request.files['file']
如果file.filename=='':
flash('没有选择要上载的文件')
返回重定向(request.url)
#文件已上载到FullProject中的imagesUploaded文件夹
如果文件和允许的文件(file.filename):
filename=secure\u文件名(file.filename)
保存(os.path.join(app.config['UPLOAD\u FOLDER'],文件名))
返回重定向(url_for('file_confirm',filename=filename))
其他:
flash('允许的文件类型为png、jpg、jpeg、gif')
返回重定向(request.url)
#文件确认/显示上传的文件:
#返回html页面
@app.route(“/show/”)
def文件\u确认(文件名):
filename='1http://127.0.0.1:5000/uploadconfirmation/“+文件名
返回呈现模板('uploadconfirmation.html',filename=filename)
#返回图像
@app.route(“/uploadconfirmation/”)
def show_文件(文件名):
从目录返回发送目录(上传文件夹,文件名)
#运行flask应用程序和.py文件
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run()
upload.html

<!DOCTYPE html>
<html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <head>
        <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
        <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
        <meta charset=utf-8 />

        <title>File Upload </title>
        <link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
    </head>
    <body>
        <div class="maintitle">
            <h1 class="heading">Select a file to upload</h1>    
        </div>
        <div class="uploadbody">
            <p>
                {% with messages = get_flashed_messages() %}
                    {% if messages %}
                        <ul class=flashes>
                          {% for message in messages %}
                              <li>{{ message }}</li>
                          {% endfor %}
                        </ul>
                    {% endif %}
                {% endwith %}
            </p>
            <form method="post" action="/" enctype="multipart/form-data">
                <dl>
                    <p>
                        <input type="file" name="file" autocomplete="off" required>
                    </p>
                </dl>
                <p>
                    <input type="submit" class="submit "value="Submit">
                </p>
            </form>
    </body>
</html>

文件上传
选择要上载的文件

{%with messages=get_flashed_messages()%}
{%if消息%}

{消息%中的消息为%s}
  • {{message}}
  • {%endfor%} {%endif%} {%endwith%}

    uploadconfirmation.html

    <!DOCTYPE html>
    <html>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <head>
            <title>File Confirmation </title>
            <link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
        </head>
        <body>
            <div class="maintitle">
                <h2 class="proceedheading">Do you want to proceed with this image?</h2>    
            </div>
            <div class="uploadbody">
                <p>
                    {% if filename %}
                        <img src="{{filename}}" width="80%" height="80%">
                    {% else %}
                        <h1>no image for whatever reason</h1>
                    {% endif %}
                    <a href="upload" class="upload" value="upload">Go back</a> 
                    <a href="choosebrand" class="upload" value="choosebrand">Yes</a>
            </div>
        </body>
    </html>
    
    
    文件确认
    是否要继续此图像?
    
    {%if文件名%}
    {%else%}
    不管什么原因都没有图像
    {%endif%}
    
    尝试在模板中动态呈现链接:

    <a href="{{ url_for('upload') }}">Go back</a>
    

    如果您想返回,请使用以下代码:

    #base.html(此代码应包含在每个模板中)
    window.onload=function(){localStorage.setItem(“prev_page”,location.href)}
    函数go_back(){window.location.href=localStorage.getItem(“prev_page”)};
    
    下面的代码将允许您使用back按钮。

    您可以使用flask方法的url\u来获取上传页面的url

    <a href="{{ url_for('upload_page') }}">Back</a>
    
    
    
    注意:的url_采用路由方法名称作为参数,即“上载页面”而不是“上载”