【问题标题】:how to access form data using flask?如何使用烧瓶访问表单数据?
【发布时间】:2013-04-06 20:56:02
【问题描述】:

我的login 端点看起来像

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        print request.form # debug line, see data printed below
        user = User.get(request.form['uuid'])
        if user and hash_password(request.form['password']) == user._password:
            login_user(user, remember=True)  # change remember as preference
            return redirect('/home/')
    else:
        return 'GET on login not supported'

当我使用 curl 进行测试时,GET 调用看起来像

⮀ ~PYTHONPATH ⮀ ⭠ 43± ⮀ curl http://127.0.0.1:5000/login/
GET on login not supported

但在POST 上,我无法访问表单数据并获取HTTP 400

⮀ ~PYTHONPATH ⮀ ⭠ 43± ⮀ curl -d "{'uuid': 'admin', 'password': 'admin'}" http://127.0.0.1:5000/login/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

虽然在服务器上,我的调试信息会打印以下内容

ImmutableMultiDict([("{'uuid': 'admin', 'password': 'admin'}", u'')])

我在哪里print request.form。我无法理解我在哪里做错了

【问题讨论】:

    标签: python flask flask-extensions flask-login


    【解决方案1】:

    您没有正确使用curl。试试这样:

    curl -d 'uuid=admin&password=admin'
    

    400 Bad Request 错误是您尝试从 request.form 获取不存在的密钥时的常见行为。

    或者,使用request.json 代替request.form 并像这样调用curl

    curl -d '{"uuid":"admin","password":"admin"}' -H "Content-Type: application/json" 
    

    【讨论】:

      【解决方案2】:

      您仍然需要返回响应:

      from flask import abort
      
      @app.route('/login/', methods=['GET', 'POST'])
      def login():
          if request.method == 'POST':
              user = User.get(request.form['uuid'])
      
              if user and hash_password(request.form['password']) == user._password:
                  login_user(user, remember=True)
                  return redirect('/home/')
              else:
                  return abort(401)  # 401 Unauthorized
          else:
              return abort(405)  # 405 Method Not Allowed
      

      这是custom Flask error pages 的文档。

      另外,请查看 Flask-Bcrypt 以了解密码散列。


      您的 CURL 命令行无效。 JSON 对象需要在键和值周围加上双引号:

      $ curl -d '{"uuid": "admin", "password": "admin"}' http://127.0.0.1:5000/login/
      

      现在,您可以使用request.json 访问密钥。

      【讨论】:

      • 感谢@Blender,但问题是为什么我在发送数据表单客户端时无法访问uuid
      • @daydreamer:仅当您访问request.form object 中不存在的密钥时,Flask 才会发送该响应。尝试使用request.form.get('uuid', None)
      • 正如我的问题中提到的,我的request.formImmutableMultiDict([("{'uuid': 'admin', 'password': 'admin'}", u'')])
      • @daydreamer:我知道。您如何发送此请求?
      • 赞这个curl -X POST -d '{uuid: "admin", "password": "admin"}' http://127.0.0.1:5000/login/
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多