如何使用pycurl执行以下代码

时间:2015-04-01 11:45:43

标签: python pycurl

curl https://api.smartsheet.com/1.1/sheets -H "Authorization: Bearer 26lhbngfsybdayabz6afrc6dcd" -H "Content-Type: application/json" -X POST -d @test.json

1 个答案:

答案 0 :(得分:2)

如果您不熟悉编码,请不要使用pycurl它通常被认为是过时的。而是使用可以与pip install requests一起安装的requests

以下是如何使用requests执行等效操作:

import requests

with open('test.json') as data:
    headers = {'Authorization': 'Bearer 26lhbngfsybdayabz6afrc6dcd'
               'Content-Type' : 'application/json'}
    r = requests.post('https://api.smartsheet.com/1.1/sheets', headers=headers, data=data)
print r.json

如果您必须使用pycurl我建议您启动reading here。通常,这将由此(未经测试的)代码完成:

import pycurl

with open('test.json') as json:
    data = json.read()

    c = pycurl.Curl()
    c.setopt(pycurl.URL, 'https://api.smartsheet.com/1.1/sheets')
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDS, data)
    c.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer 26lhbngfsybdayabz6afrc6dcd',
                                 'Content-Type: application/json'])
    c.perform()

这表明requests更优雅。