【问题标题】:Problems POST-ing with pyCurl使用 pyCurl 发布问题
【发布时间】:2010-11-11 12:18:01
【问题描述】:

我正在尝试使用 CURL 将文件发布到网络服务(这是我需要使用的,所以我不能使用扭曲或其他东西)。问题是当使用 pyCurl 时,webservice 没有收到我发送的文件,就像文件底部注释的情况一样。我在我的 pyCurl 脚本中做错了什么?有什么想法吗?

非常感谢。

import pycurl
import os

headers = [ "Content-Type: text/xml; charset: UTF-8; " ]
url = "http://myurl/webservice.wsdl"
class FileReader:
    def __init__(self, fp):
        self.fp = fp
    def read_callback(self, size):
        text = self.fp.read(size)
        text = text.replace('\n', '')
        text = text.replace('\r', '')
        text = text.replace('\t', '')
        text = text.strip()
        return text

c = pycurl.Curl()
filename = 'my.xml'
fh = FileReader(open(filename, 'r'))

filesize = os.path.getsize(filename)
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
c.setopt(c.HTTPHEADER, headers)
c.setopt(c.READFUNCTION , fh.read_callback)
c.setopt(c.VERBOSE, 1)
c.setopt(c.HTTP_VERSION, c.CURL_HTTP_VERSION_1_0)
c.perform()
c.close()
# This is the curl command I'm using and it works
# curl -d @my.xml -0 "http://myurl/webservice.wsdl" -H "Content-Type: text/xml; charset=UTF-8"

【问题讨论】:

  • 我只是想知道您是否找到了问题的正确答案?
  • VERBOSE输出到stdout的值是多少?

标签: python webservice-client pycurl


【解决方案1】:

PyCurl 似乎是一个孤立的项目。两年没更新了。我只是将命令行 curl 称为子进程。

import subprocess

def curl(*args):
    curl_path = '/usr/bin/curl'
    curl_list = [curl_path]
    for arg in args:
        # loop just in case we want to filter args in future.
        curl_list.append(arg)
    curl_result = subprocess.Popen(
                 curl_list,
                 stderr=subprocess.PIPE,
                 stdout=subprocess.PIPE).communicate()[0]
    return curl_result 

curl('-d', '@my.xml', '-0', "http://myurl/webservice.wsdl", '-H', "Content-Type: text/xml; charset=UTF-8")

【讨论】:

    【解决方案2】:

    尝试以这种方式进行文件上传:

    c.setopt(c.HTTPPOST, [("filename.xml", (c.FORM_FILE, "/path/to/file/filename.xml"))])

    【讨论】:

      【解决方案3】:

      解决此类问题可能会很痛苦,因为问题是 1) 您的代码、2) 您正在使用的库、3) Web 服务或某种组合并不总是很清楚。

      已经观察到 PyCURL 并不是一个真正的活跃项目。考虑改写在httplib2 之上。在众多使用 HTTP 的 Python 库中,它可能是重建 CURL 所需内容的最佳选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-22
        • 2018-05-01
        • 2018-11-26
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多