python
  • rest
  • post
  • curl
  • 2016-06-14 184 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.

    希望有幫助!

    相關問題