使用 pycurl 为 url 传递多个参数
我想使用具有多个参数的 URL 进行curl 调用。我在下面列出了代码。例如,是否有“curl -d @filter”的等效选项,或者我是否对参数进行 URL 编码?
SER = foobar
PASS = XXX
STREAM_URL = "http://status.dummy.com/status.json?userId=12&page=1"
class Client:
def __init__(self):
self.buffer = ""
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER,PASS))
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self,data):
self.buffer += data
I want to make a curl call with a URL that has multiple parameters. I have listed the code below. Is there an equivalent option for "curl -d @filter" for instance or do I have URL encode the parameters?
SER = foobar
PASS = XXX
STREAM_URL = "http://status.dummy.com/status.json?userId=12&page=1"
class Client:
def __init__(self):
self.buffer = ""
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER,PASS))
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self,data):
self.buffer += data
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Pycurl 是 libcurl 的一个非常薄的包装。如果你能用 libcurl 做到这一点,你也可以用 pycurl 做到这一点。 (大部分。)
例如:
请参阅: http://pycurl.sourceforge.net/doc/curlobject.html
那是也就是说,curl -d 选项用于发送 HTTP POST 请求...而不是您的示例显示的 GET 样式。
libcurl 确实期望它接收的 url 已经经过 URL 编码。如果需要,只需使用 http://docs.python.org/library/urllib.html 。
您问题中的示例 URL 已经有 2 个参数(userId 和 page)。
一般而言,格式为:URL 后跟“问号”,后跟由 & 符号连接的名称=值对。如果名称或值包含特殊字符,则需要对它们进行百分比编码。
只需使用 urlencode 函数:
另请参阅 urllib.urlopen 函数。也许你根本不需要curl? (但我不知道您的申请...)
希望这有帮助。如果是这样,请标记已回答并告诉我。 :-)
Pycurl is a pretty thin wrapper for libcurl. If you can do it with libcurl, you can do it with pycurl. (Mostly.)
For instance:
See: http://pycurl.sourceforge.net/doc/curlobject.html
That being said, the
curl -d
option is for sending HTTP POST requests... not the GET style your example shows.libcurl does expect that urls it recives already be URL encoded. Just use http://docs.python.org/library/urllib.html if needed.
The sample URL in your question already has 2 parameters (userId and page).
In general the format is: URL followed by a 'question mark', followed by name=value pairs joined by an ampersand symbol. If the name or value contain special chars, you will need to percent-encoded them.
Just use the urlencode function:
Also, see the
urllib.urlopen
function. Perhaps you do not need curl at all? (But I do not know your application...)Hope this helps. If so, mark answered and let me know. :-)