【问题标题】:Must be str, not ImmutableMultiDict - Python/Flask必须是 str,而不是 ImmutableMultiDict - Python/Flask
【发布时间】:2017-03-24 09:43:42
【问题描述】:

我对此感到困惑,因为如果我在函数之外运行我的代码并使用 print 而不是 return 我似乎没有任何问题。

我正在通过如下表单将数据从 HTML 发送到 Flask:

<form method="POST" action="/">
    <h4>Search for Your Device</h4>
  <p>Enter the Asset Tag of the device - On the back sticker or in small print at the bottom of the lock screen.</p>
  <p><input type = "text" name = "Name" /></p>
    <p><input type = "submit" value = "submit" /></p>
</form>

然后我接受该输入并使用以下函数向我的移动设备管理服务器发出 API 请求

@app.route('/', methods=["GET","POST"])
def homepage():
    try:
        if request.method == "POST":
            #API URL
            JSS_API = 'https://private_url.com'
            #Pre-Defined username and password
            username = 'username'
            password = 'password'

            #Ask User for the Asset tag
            asset_tag = request.form
            New_JSS_API = JSS_API + asset_tag

            #Disables Warnings about SSL
            requests.packages.urllib3.disable_warnings()

            JSS_Asset_Response = requests.get(New_JSS_API, auth=(username, password), verify=False, headers={'Accept': 'application/json'})

            JSS_json = JSS_Asset_Response.json()

            email_dict = {}
            for item in JSS_json['mobile_devices']:
                email_dict["Stu_name".format(item)]=item['realname']
            #Can call the dictionary value by doing the following:
            stu_name = email_dict['Stu_name']
            return stu_name

        return render_template("index.html")
    except Exception as e:
        return(str(e))

我收到的错误是“必须是 str,而不是 ImmutableMultiDict”,但是如果在我的终端中运行该函数,将 return stu_name 替换为 print(stu_name),我会得到我正在寻找的结果!

我的目标是通过表格输入,然后将学生的全名返回到网页!

【问题讨论】:

  • 分享完整的回溯

标签: python flask


【解决方案1】:

我想request.formImmutableMultiDictJSS_API 是一个字符串,所以你不能将ImmutableMultiDict 附加到一个字符串,这就是你得到错误的原因。

您可以将ImmutableMultiDict 转换为dict:

request.form.to_dict()

然后调试你的代码,获取表单数据,我以前用request.form.to_dict().values()[0]获取json字符串。

或者

如果您使用POST 方法,您可以像这样检索参数:

username = request.form.getlist('username[]')

GET方法,使用这个:

username = request.args.getlist('username[]')

doc查看更多详情。

【讨论】:

  • 谢谢一百万。我不知道我不能像以前那样追加。已经修好了:)
猜你喜欢
  • 2020-11-22
  • 2016-06-25
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 2023-03-29
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多