python - Django POST curl REST api

标签 python rest python-requests

我想通过使用 POST 的 django 调用 RESTful api。我知道如何执行 GET,但如何执行 POST?

对于获取,我使用requests.get(...)

API 调用是:

curl -v -X POST -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -X POST \
     --user user:password \
     https://this.is.an.external.domain \
     -d "{\"name\": \"Marcus0.1\",\"start\": 500000,\"end\": 1361640526000}"

更新

所以,我找到了requests.post,但是如何翻译上面的curl命令

最佳答案

curl 命令转换为 Python 请求调用将是:

# construct a python dictionary to serialize to JSON later
item = { "name": "Marcus0.1", "start": 500000, "end": 1361640526000 }

resp = requests.post("https://this.is.an.external.domain", 
              data=json.dumps(item),  # serialize the dictionary from above into json
              headers={
                       "Content-Type":"application/json",
                       "Accept": "application/json"
                      })

print resp.status_code
print resp.content

关于python - Django POST curl REST api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18086291/

相关文章:

web-services - 多个依赖资源的 REST 式 URI 设计

python - 纯Python中的矩阵乘法?

python - 在 Pandas 中如何在移动窗口的基础上计算 'Countif'?

rest - Docker Maven 插件

javascript - 使用请求登录到具有 javascript 登录表单的网站

Python 请求测量响应时间

python - 将 curl PUT 转换为 Python 请求的问题 : "Problems parsing JSON"

python - Selenium Python 按文本/样式单击页面上的链接

python - Django Rest 序列化程序 : Use nested serializer on GET but not POST

java - 将 JSON URL 传递给 java Restful WebService