【问题标题】:how to make POST method works for two different forms on same page with flask?如何使用烧瓶使 POST 方法适用于同一页面上的两种不同形式?
【发布时间】:2017-06-15 06:17:15
【问题描述】:

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

这是我的代码来自主要的 __int__.py 文件,用于烧瓶/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

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我猜你想要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()
    

    此解决方案可能有效

    【讨论】:

    • 感谢您的回答,但它给出了这个错误 400 Bad Request: The browser (or proxy) sent an request that this server could not understand.
    • 我想我必须使用 WTForms,毕竟我有一个项目要使用尽可能少的框架,再次感谢好友
    • 是的,我想你必须这样做。Flask 有一个简单的 API 用于 link
    【解决方案2】:

    我想出了在 JavaScript 中为同一页面上的每个表单使用 Ajax 请求的方法

    例子:-

    HTML 表单

    <form onsubmit="formSumbit()">
      email: <input id="email" type="text">
      password: <input id="password" type="password">
      <input type="submit">
    </form>
    

    每个表单的 JavaScript POST 请求函数看起来像这样

    function formSumbit(event) {
        event.preventDefault()
        fetch("http://yourwebsite.com/login", {
            method: "POST",
            headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
            body: JSON.stringify({ email: document.getElementById('email').value, password: document.getElementById('password').value })
        }).then((res) => {
            console.log(res);
            return res.json();
        }).then((data) => {
            console.log(data);
        }).catch((err) => {
            console.log(err);
        });
    }
    

    并在 Flask 中为每个表单使用两个 POST 路由处理程序,或者传递名为 'form1''form2' 的额外参数并检查 Flask 路由处理程序中的参数。

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      相关资源
      最近更新 更多