简体   繁体   English

将参数传递给 flask GET function

[英]Passing argument to a flask GET function

I'm trying to write a simple messaging function and, despite searching, having trouble coming up with a workable solution.我正在尝试编写一个简单的消息 function 并且尽管进行了搜索,但在提出可行的解决方案时遇到了麻烦。 On the get function, the code retrieves stored messages and passes this to be rendered.在获取 function 时,代码检索存储的消息并将其传递给呈现。

The post function stores the message which all works fine, however I'm trying to redirect the user back to the original page they came from to display the new message, hence trying to pass the receiving user variable to the get function.帖子 function 存储了所有工作正常的消息,但是我试图将用户重定向回他们来自的原始页面以显示新消息,因此尝试将接收用户变量传递给 get function。

My code so far below.到目前为止,我的代码如下。 I'm new to flask so would appreciate any other pointers as well.我是 flask 的新手,所以我也会感谢任何其他指针。 Thanks in advance!提前致谢!

@app.route("/messaging", methods=["GET", "POST"])
@login_required
def messaging():
    if request.method == "GET":

        clicked_user = request.args.get('user')
        messages = db.execute("SELECT * FROM messages WHERE (m_sending_user = :self_user AND m_receiving_user = :other_user) OR (m_sending_user = :other_user AND m_receiving_user = :self_user)",
                        self_user = session["user_id"],
                        other_user = clicked_user)

        return render_template("messaging.html", messages=messages, clicked_user=clicked_user)

    if request.method == "POST":

        receiving_user = request.form.get("recipient")

        db.execute("INSERT INTO messages (m_sending_user, m_receiving_user, message) VALUES (:m_sending_user, :m_receiving_user, :message)",
                        m_sending_user = session["user_id"],
                        m_receiving_user = receiving_user,
                        message = request.form.get("reply"))

        flash("Sent!")
        return render_template("messaging.html")

Why do you not simply have the post function also call the get function like so为什么你不简单地有帖子 function 也像这样调用 get function

def get_function(clicked_user):
    messages = db.execute("SELECT * FROM messages WHERE (m_sending_user = :self_user AND m_receiving_user = :other_user) OR (m_sending_user = :other_user AND m_receiving_user = :self_user)",
                  self_user = session["user_id"],
                  other_user = clicked_user)

    return render_template("messaging.html", messages=messages, clicked_user=clicked_user)

@app.route("/messaging", methods=["GET", "POST"])
@login_required
def messaging():
    if request.method == "GET":

        clicked_user = request.args.get('user')

        return get_function(clicked_user)

    if request.method == "POST":

        receiving_user = request.form.get("recipient")

        db.execute("INSERT INTO messages (m_sending_user, m_receiving_user, message) VALUES (:m_sending_user, :m_receiving_user, :message)",
                        m_sending_user = session["user_id"],
                        m_receiving_user = receiving_user,
                        message = request.form.get("reply"))

        flash("Sent!")
        return get_function(m_receiving_user)

But of course with better named functions;)但当然有更好的命名函数;)

If you send data in GET request, it will be visible in URL parameter.如果您在GET请求中发送数据,它将在 URL 参数中可见。 Rather, you can use session object to store variable.相反,您可以使用session object 来存储变量。 More on session object can be found in the [official documentation on session object].(https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions ) More on session object can be found in the [official documentation on session object].(https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions )

You can use url_for with redirect method to redirect user to the original template.您可以使用带有redirect方法的url_for将用户重定向到原始模板。

Here I have shown a basic example:在这里,我展示了一个基本示例:

messaging.html : messaging.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Post request redirect</title>
  </head>
  <body>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}

    {% if clicked_user %}
      Clicked user: {{ clicked_user }}
    {% endif %}

    {% if messages %}
      Messages: {{ messages }}
    {% endif %}

    <h3>Send a Message</h3>
    <form action='{{url_for("messaging")}}' method="post">
      Recipient:
      <input type="text" name="recipient">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

app.py : app.py

from flask import Flask, render_template, redirect, url_for, session, request, flash

app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'



@app.route("/messaging", methods=["GET", "POST"])
def messaging():
    if request.method == "GET":
        data = {
            "shovon": "some messages for shovon",
            "arsho": "other messages for arsho"
        }
        receiving_user = None
        messages = None
        if 'receiving_user' in session:
            receiving_user = session["receiving_user"]
        messages = data.get(receiving_user)
        return render_template("messaging.html", messages=messages, clicked_user=receiving_user)

    if request.method == "POST":
        receiving_user = request.form.get("recipient")
        session["receiving_user"] = receiving_user
        flash("Sent!")
        return redirect(url_for("messaging"))

Output: Output:

  • Before form submission:表单提交前:

表单提交前

  • After form submission:表单提交后:

表单提交后

NB: Here I have mocked the database queries with static dictionary search.注意:这里我使用 static 字典搜索模拟了数据库查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM