Add a data kwarg to getUrl(Fd) a la urllib2.Request.

This allows plugins to easily make POST requests using our getUrl(Fd)
functions.

Signed-off-by: James Vega <jamessan@users.sourceforge.net>
This commit is contained in:
James Vega 2009-09-16 01:17:33 -04:00
parent e9a896c736
commit de79e679f4

View File

@ -1,5 +1,6 @@
### ###
# Copyright (c) 2002-2005, Jeremiah Fincher # Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2009, James Vega
# All rights reserved. # All rights reserved.
# #
# Redistribution and use in source and binary forms, with or without # Redistribution and use in source and binary forms, with or without
@ -87,17 +88,21 @@ defaultHeaders = {
# application-specific function. Feel free to use a callable here. # application-specific function. Feel free to use a callable here.
proxy = None proxy = None
def getUrlFd(url, headers=None): def getUrlFd(url, headers=None, data=None):
"""Gets a file-like object for a url.""" """getUrlFd(url, headers=None, data=None)
Opens the given url and returns a file object. Headers and data are
dicts as per urllib2.Request's arguments."""
if headers is None: if headers is None:
headers = defaultHeaders headers = defaultHeaders
try: try:
if not isinstance(url, urllib2.Request): if not isinstance(url, urllib2.Request):
if '#' in url: if '#' in url:
url = url[:url.index('#')] url = url[:url.index('#')]
request = urllib2.Request(url, headers=headers) request = urllib2.Request(url, headers=headers, data=data)
else: else:
request = url request = url
request.add_data(data)
httpProxy = force(proxy) httpProxy = force(proxy)
if httpProxy: if httpProxy:
request.set_proxy(httpProxy, 'http') request.set_proxy(httpProxy, 'http')
@ -117,9 +122,13 @@ def getUrlFd(url, headers=None):
except ValueError, e: except ValueError, e:
raise Error, strError(e) raise Error, strError(e)
def getUrl(url, size=None, headers=None): def getUrl(url, size=None, headers=None, data=None):
"""Gets a page. Returns a string that is the page gotten.""" """getUrl(url, size=None, headers=None, data=None)
fd = getUrlFd(url, headers=headers)
Gets a page. Returns a string that is the page gotten. Size is an integer
number of bytes to read from the URL. Headers and data are dicts as per
urllib2.Request's arguments."""
fd = getUrlFd(url, headers=headers, data=data)
try: try:
if size is None: if size is None:
text = fd.read() text = fd.read()