Skip to main content
 首页 » 编程设计

python之如何使用 Flask 使 POST 方法适用于同一页面上的两种不同形式

2024年10月01日6lhb25

如何使用 flask 使 POST 方法适用于同一页面上的两种不同形式?

这是我的主要 __int__.py 文件中的代码,用于 flask/python

@app.route('/', methods=['GET', 'POST']) 
@app.route('/login/', methods=['GET', 'POST']) 
def login(): 
    error = None 
    if request.method == 'POST': 
        if request.form['email'] != '1' or \ 
                request.form['password'] != '1': 
            flash('Invalid Credentials') 
        else: 
            flash('You were successfully logged in') 
            return redirect(url_for('dashborad')) 
    return render_template('login.html', error=error) 
 
 
@app.route('/', methods=['GET', 'POST']) 
@app.route('/register/', methods=['GET', 'POST']) 
def register(): 
    try: 
        if request.method == 'POST': 
            email = request.form['email1'] 
            name = request.form['name1'] 
            password = request.form['password1'] 
 
            cur, db = connection() 
            x = cur.execute(" SELECT * FROM users WHERE email = (%s)" ,[escape(email)]) 
 
            if int(x) > 0: 
                flash ("email already used ") 
                return render_template ("register.html") 
            else: 
                cur.execute("INSERT INTO users (first_name, email, password) VALUES (%s, %s, %s);" ,(escape(name), escape(email), escape(password) )) 
 
                db.commit() 
        return render_template ("register.html") 

现在 python 正在读取第一个 @app.route 登录表单的 POST 方法

有什么简单的方法可以在 python 中得到这样的行吗?

if request.method == 'POST' for form 1 

和

 if request.method == 'POST' for form 2 

请您参考如下方法:

我猜你想要像 LinkedIn 的起始页这样的东西

为了在 Flask 中实现这一点,将 HTML 模板创建为:

<input type="submit" name="btn" value="Save"> 
<input type="submit" name="btn" value="Cancel">

然后您可以通过以下方式验证:

if request.form["btn"]=="Save": 
    if request.method== 'POST': 
        doSomething() 

这个解决方案可能有效