如何使用pycurl执行此操作?

时间:2015-04-06 17:17:45

标签: python curl

curl https://api.smartsheet.com/1.1/sheet/7846568935090052 -H "Authorization: Bearer 4ziycpnqjvto49oah6t6urd4un" -H "Accept: application/vnd.ms-excel" -o  output.xls

我试过这个:

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

    c = pycurl.Curl()
    c.setopt(pycurl.URL, 'https://api.smartsheet.com/1.1/sheet/5481016912570244')
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDS, data)
    c.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer 3e181f72o602q4dnq3yrg7jd3u',
                             'Content-Type: application/vnd.ms-excel'])
    c.perform()

return redirect('https://app.smartsheet.com/b/home')  

在我的test.xls中: output.xls

预期产量: 我登录智能表并输入我的数据。我的代码应该将该表转换为Excel表。

此代码有效,但我想使用pycurl

输出
curl https://api.smartsheet.com/1.1/sheet/7846568935090052 -H "Authorization: Bearer 4ziycpnqjvto49oah6t6urd4un" -H "Accept: application/vnd.ms-excel" -o  output.xls

1 个答案:

答案 0 :(得分:0)

总是,RTFM ......看看:

https://docs.python.org/2/library/subprocess.html

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_curl.py
#  
#  Copyright 2015 John Coppens
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  

import subprocess as sp

def main():
    res = sp.check_output("curl" + \
                          " https://api.smartsheet.com/1.1/sheet/7846568935090052" + \
                          " -H \"Authorization: Bearer 4ziycpnqjvto49oah6t6urd4un\"" + \
                          " -H \"Accept: application/vnd.ms-excel\"",
                          shell = True)
    with open("test.xls", "w") as f:
        f.write(res)

    return 0

if __name__ == '__main__':
    main()

根据个人喜好添加错误检查和其他香料。 'shell = True'可能存在安全风险。参见文档。