【问题标题】:Passing arguments url_for Python传递参数 url_for Python
【发布时间】:2019-12-17 13:30:35
【问题描述】:

我有两个用于创建问题和预览问题的定义。

我想将问题的 ID 从 def create() 传递到 def preview()。但是def preview()无法实现ID。

我尝试过使用return redirect(url_for('preview', question_id=question_id)),在我的def preview() 中我使用了question_id = request.args.get('question_id',type=str)

我该如何解决这个问题?

我的代码在这里:

@app.route("/create/", methods=['GET','POST'])
def create():
    question = "How are you?"
    question_id = "123456"
    return redirect(url_for('preview'), question_id=question_id)

@app.route("/preview/", methods=['GET','POST'])
def preview():
    question_id = request.args.get('question_id', type=str)
    print(question_id)

【问题讨论】:

  • 你能分享错误信息吗? (如果有的话)
  • 顺便说一下,您将question_id 参数传递给url_for 函数而不是redirect。请更正至:redirect(url_for('preview'), question_id=question_id)
  • 它应该显示页面上的 ID,但它只是显示一个空白页面!

标签: python flask url-for


【解决方案1】:

在预览路由中,您正在执行print(question_id),它不会向页面写入或呈现任何内容,它只会将值打印到您的控制台(stdout),仅此而已。

像这样尝试render_template_string

from flask import render_template_string

[...]



@app.route("/preview/", methods=['GET','POST'])
def preview():
    question_id = request.args.get('question_id', type=str)
    return render_template_string('question_id = {{ question_id }}', question_id=question_id)

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2022-07-09
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多