简体   繁体   English

如何从python发出curl发布请求

[英]How to make curl post request from python

I am trying to make a post request using curl in python but the below script throws error 我正在尝试使用python中的curl发出发布请求,但以下脚本引发错误

import os

first_name1 = "raj"
last_name1 = "kiran"
full_name = "raj kiran"
headline = "astd"
location1 = "USA"
current_company1 = "ss"

curl_req = 'curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'.format(first_name1,last_name1,current_company1,headline,location1,full_name)

os.popen(curl_req)

Error: 错误:

SyntaxError: invalid syntax

How to make above program work? 如何使以上程序起作用?

The problem in your code is the quotes. 您的代码中的问题是引号。 Change it to: 更改为:

curl_req = '''curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'''.format(first_name1,last_name1,current_company1,headline,location1,full_name)

But, as mentioned in the comments, requests will always be a better choice. 但是,正如评论中提到的那样, requests始终是一个更好的选择。

Requests syntax: 请求语法:

import requests
post_data = { 
   # all the data you want to send 
}
response = requests.post('http://localhost:8090', data=post_data)
print response.text

One good resource I've used for converting a cURL request to Python requests is curlconverter . 我用于将cURL请求转换为Python请求的一种很好的资源是curlconverter You can enter your cURL request and it will format it for Python requests . 您可以输入cURL请求,它将为Python requests格式化。

As a side note, it can also convert for PHP and Node.js. 另外,它还可以转换为PHP和Node.js。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM