首页 > 解决方案 > 将简单的 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 响应返回

{}

关于我的代码中可能存在问题的任何想法?

谢谢!

标签: pythondjango

解决方案


除了尼古拉所说的,我认为您希望整个数据线如下所示,这样您就不会将整个数据作为字符串传递。请求将为您处理序列化和将 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}

推荐阅读