python - 将简单的 curl 调用转换为 python/django 请求
问题描述
我正在尝试将以下 curl 请求转换为将在 django 中运行的内容。
curl -X POST https://api.lemlist.com/api/hooks --data '{"targetUrl":"https://example.com/lemlist-hook"}' --header "Content-Type: application/json" --user ":1234567980abcedf"
我已经在 git bash 中运行了它,它返回了预期的响应。
我在我的 django 项目中拥有以下内容:
apikey = '1234567980abcedf'
hookurl = 'https://example.com/lemlist-hook'
data = '{"targetUrl":hookurl}'
headers = {'Content-Type': 'application/json'}
response = requests.post(f'https://api.lemlist.com/api/hooks/', data=data, headers=headers, auth=('', apikey))
运行此 python 代码将其作为 json 响应返回
{}
关于我的代码中可能存在问题的任何想法?
谢谢!
解决方案
除了尼古拉所说的,我认为您希望整个数据线如下所示,这样您就不会将整个数据作为字符串传递。请求将为您处理序列化和将 python 对象转换为 json [编辑:如果您使用 json 参数而不是数据]。
来源:https ://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests
除了自己编码dict,你也可以直接使用json参数(在2.4.2版本中添加)传递它,它将自动编码:
请注意,如果传递数据或文件,则忽略 json 参数。
在请求中使用 json 参数会将标头中的 Content-Type 更改为 application/json。
data = {"targetUrl":hookurl}
推荐阅读
- angularjs - 从前端客户端访问超级账本作曲家休息服务器访问令牌
- python - 在 Pandas DataFrame 图中填充缺失值
- python-3.x - Pythons requests.session cookie 检索问题
- android - 在 OSMDROID 中的快速覆盖上设置图标
- web-scraping - python程序在尝试发出get http请求时卡住了
- bash - 替换的相同命令不起作用
- push-notification - 渐进式 Web 应用程序 (PWA) 的本地和推送通知
- ios - 我有数组中的纬度和经度数。我想在谷歌地图中显示多个标记
- ios - 红色分隔线未出现在 UITableViewCell 中的自定义标题下
- python - 解决一个列表是否充当另一个列表的子列表