【问题标题】:Passing arguments between routes in flask [duplicate]在烧瓶中的路线之间传递参数[重复]
【发布时间】:2020-02-07 20:43:14
【问题描述】:

我正在创建一个基于 Flask 的 Web 应用程序。在我的主页上,我从用户那里获取某些输入,并在其他路由中使用它们来执行某些操作。我目前正在使用global,但我知道这不是一个好方法。 我在 Flask 中查找了Sessions,但我的网络应用程序没有注册用户,所以我不知道在这种情况下会话将如何工作。简而言之:

  • Webapp 不需要用户注册
  • 用户选择通过表单传递三个lists 参数。
  • 这三个列表,浮点数列表、字符串列表和整数列表,必须传递给其他路由处理信息。

有什么巧妙的方法吗?

【问题讨论】:

  • 使用session 对象。会话不需要注册 - 它们使用 cookie 使用户在请求中保持唯一性。
  • 谢谢。我会再试一次

标签: python python-3.x flask web-applications global-variables


【解决方案1】:

您可以通过 url 参数从主页传递用户输入。即您可以将用户输入的所有参数作为参数附加到接收器 url 中,并在接收器 url 端检索它们。请在下面找到相同的示例流程:

from flask import Flask, request, redirect

@app.route("/homepage", methods=['GET', 'POST'])
def index():
    ##The following will be the parameters to embed to redirect url.
    ##I have hardcoded the user inputs for now. You can change this
    ##to your desired user input variables.
    userinput1 = 'Hi'
    userinput2 = 'Hello'

    redirect_url = '/you_were_redirected' + '?' + 'USERINPUT1=' + userinput1 + '&USERINPUT2=' + userinput2
    ##The above statement would yield the following value in redirect_url:
    ##redirect_url = '/you_were_redirected?USERINPUT1=Hi&USERINPUT2=Hello'

    return redirect(redirect_url)

@app.route("/you_were_redirected", methods=['GET', 'POST'])
def redirected():
    ##Now, userinput1 and userinput2 can be accessed here using the below statements in the redirected url
    userinput1 = request.args.get('USERINPUT1', None) 
    userinput2 = request.args.get('USERINPUT2', None)
return userinput1, userinput2

【讨论】:

  • 有很多比通过字符串连接附加查询参数更好的方法...?
猜你喜欢
  • 2021-08-25
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2016-06-21
  • 2016-03-11
相关资源
最近更新 更多