python
  • rest
  • post
  • curl
  • 2016-06-14 114 views -2 likes 
    -2

    我试图让在python使用curl POST请求,但下面的脚本卷曲POST请求抛出错误如何使从蟒蛇

    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) 
    

    错误:

    SyntaxError: invalid syntax 
    

    如何使上述程序工作?

    +4

    你为什么要这样做,当你可以使用'request'? –

    +0

    如何使用请求以上述格式向此http:// localhost:8090发送发布请求? – Mounarajan

    +2

    阅读http://docs.python-requests.org/en/latest/ – 2016-06-14 10:21:12

    回答

    0

    代码中的问题是引号。将其更改为:

    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) 
    

    但是,正如在评论中提到的,requests将永远是一个更好的选择。

    请求语法:我已经用了卷曲请求转换为Python的请求

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

    你能帮我使用请求吗? – Mounarajan

    0

    一个很好的资源是curlconverter。您可以输入您的cURL请求,并将其格式化为Python requests

    作为一个方面说明,它也可以转换为PHP和Node.js.

    希望有帮助!

    相关问题