【问题标题】:Python requests returns 403Python 请求返回 403
【发布时间】:2017-12-21 06:06:26
【问题描述】:

所以,我一直在开发一个小型烧瓶应用程序。我已经能够从 Web 表单调用 activate 方法,但我正在尝试使用 python 请求库发布到它并不断收到 403(没有使用身份验证)。

但是当我使用 httplib2 发布到它时,它突然就可以工作了。我这里有什么遗漏吗?

import httplib2 
import requests

http = httplib2.Http()
content = http.request('http://127.0.0.1:5000/services/activate', method="POST")

print content

res = requests.post('http://127.0.0.1:5000/services/activate')

print res

给我输出:

({'status': '200', 'content-length': '20', 'server': 'Werkzeug/0.12.2 Python/2.7.12', 'date': 'Thu, 21 Dec 2017 05:55:20 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}, '{\n  "status": "ok"\n}')
<Response [403]>

【问题讨论】:

  • 你能发布你的路线/services/activate吗?
  • 这可能是因为您的烧瓶应用程序需要 csrf_token 传递
  • flask 在表单中使用隐藏字段,您也必须在帖子中发送该字段 - 但 requests 不会自动发送,您必须手动发送。

标签: python flask python-requests httplib2


【解决方案1】:

如果您可以发布所有相关代码,那就太好了。但总的来说 -

如果使用 FlaskForm,您的 HTML 应该如下所示:

<form action="{{url_for('activate') }}" method = "post">
    {{ form.csrf_token }}
    <!-- other form stuff -->
</form>

否则,

 <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

来自:http://flask-wtf.readthedocs.io/en/stable/csrf.html

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 2014-02-12
    • 2012-11-13
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多