本文整理汇总了Python中urllib2.Request.add_data方法的典型用法代码示例。如果您正苦于以下问题:Python Request.add_data方法的具体用法?Python Request.add_data怎么用?Python Request.add_data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib2.Request
的用法示例。
在下文中一共展示了Request.add_data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def make_request(self, action, **kw):
"""Returns a signed Request object.
>>> conn = Connection('api-key', 'secret-key')
>>> request = conn.make_request('send_message', arg1='blah', arg2='foo')
>>> request.get_full_url()
'https://api.zeepmobile.com/messaging/2008-07-14/send_message'
>>> Auth.signature_valid(request, conn.api_key, conn.secret_key)
True
>>> request.get_method()
'POST'
>>> request.get_data()
'arg1=blah&arg2=foo'
"""
request = Request("%s/%s/%s" % (self.base_url, self.version, action))
request.add_data(urlencode(kw))
Auth.sign_request(request, self.api_key, self.secret_key)
return request
示例2: login
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def login(uname, passwd):
print "Logging in as: ", uname
uri = "https://ecs.victoria.ac.nz"
path = "/login-ticket"
# Firstly we consruct our request
req = Request(uri+path)
# Some services discriminate connections that aren't from a web browser (Request by default will indicate
# it's being sent by an automated process). ECS doesn't do that currently, but it can't hurt to include
# for the future.
req.add_header("User-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
# We make user of some prior knowledge of the redirection system to ensure the correct referer
req.add_header("Referer", "ecs.victoria.ac.nz/login-ticket")
# And we know our host, obviously.
req.add_header("Host","ecs.victoria.ac.nz")
# We want this request to accept our format type
req.add_header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
# And the meat of the request, the POST data, including the username and password, obviously no return
# url or server url is necessary as we will ignore everything in the response bar the auth. cookie
data = {"username":uname,
"password":passwd,
"realm":"ECS.VUW.AC.NZ",
"login":"Log in",
"ReturnUrl":"",
"ServerUrl":"",
".cgifields":"ssl_only"}
# We use urllib to encode this data to the correct url string
req.add_data(urllib.urlencode(data))
# And we use cookielib to keep track of cookies in a managed way
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
try:
# So now we try and use our opener with the username/password combination
resp = urlopen(req)
html = resp.read()
# If the returned page has the standard fail message we divert control to
# the catch clause
if re.search("Incorrect username or password", html) != None:
print "Failure"
raise Exception
# Otherwise, we can inspect our cookie jar for our authentication ticket
for cookie in cj:
print "Login successful"
print "Authorisation ticket: ", str(cookie).split(" ")[1]
# Which we proceed to write to our local memory
o = open("cookie.txt", "w")
o.write(str(cookie).split(" ")[1])
o.close()
break
except:
# If we get here the response contained the default error message, which
# which means the supplied credentials were incorrect. We'll exit now and
# overwrite the cookie file so dependent functions will know something
# strange has happened to their user credentials
print "Login failed"
o = open("cookie.txt", "w")
o.write("Failed")
o.close()
raise Exception("Authentication failed")
示例3: post
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def post(url,data):
req = Request(url)
req.add_data(data)
req.get_method = lambda: 'POST'
if not open(req):
print url
print data
示例4: get_access_token
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def get_access_token(self, client_id, client_secret):
"""
Make an HTTP POST request to the token service, and return the access_token
See description here: http://msdn.microsoft.com/en-us/library/hh454949.aspx
"""
data = urlencode({
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'client_credentials',
'scope': 'http://api.microsofttranslator.com'
})
try:
self.debug('requesting microsoft translator access token.....')
req = Request('https://datamarket.accesscontrol.windows.net/v2/OAuth2-13')
req.add_data(data)
res = urlopen(req)
rtn = json.loads(res.read())
if 'access_token' in rtn.keys():
return rtn['access_token']
except (URLError, TypeError), e:
# just print error in log and let the method return false
# this was split into several exceptions catches but it makes no
# sense since without the access token we are not able to translate
self.error('could not request microsoft translator access token: %s' % e)
示例5: call_hipchat
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def call_hipchat(cls, ReturnType, url='', urlv2='', data=True, **kw):
auth = [('format', 'json'), ('auth_token', hipchat.config.token)]
if hipchat.config.api_version == 2:
url=urlv2
if not data:
auth.extend(kw.items())
req = Request(url=hipchat.config.api_url + url + '?%s' % urlencode(auth))
if data:
req.add_data(urlencode(kw.items()))
if hipchat.config.proxy_server and hipchat.config.proxy_type:
req.set_proxy(hipchat.config.proxy_server, hipchat.config.proxy_type)
try:
res = urlopen(req)
except Exception, e:
resp = "".join(e.readlines())
try:
err_resp = json.loads(resp)
except ValueError:
raise Exception(
"unknown error: %d response was: %s" % (
e.getcode(), resp
),
)
error = err_resp.get("error", {})
raise Exception(
"%d %s error: %s" % (
error.get("code", -1),
error.get("type", "unknown"),
error.get("message", "no message"),
)
)
示例6: open
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def open(self, fullurl, data=None):
"""
Overriding to remove the timeout kwarg which was being used below to
override my own HTTPRequest.timeout attribute.
"""
# accept a URL or a Request object
if isinstance(fullurl, basestring):
req = Request(fullurl, data)
else:
req = fullurl
if data is not None:
req.add_data(data)
# This is what I want to remove and the reason to override
# req.timeout = timeout
protocol = req.get_type()
# pre-process request
meth_name = protocol+"_request"
for processor in self.process_request.get(protocol, []):
meth = getattr(processor, meth_name)
req = meth(req)
response = self._open(req, data)
# post-process response
meth_name = protocol+"_response"
for processor in self.process_response.get(protocol, []):
meth = getattr(processor, meth_name)
response = meth(req, response)
return response
示例7: get_reader
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def get_reader(self, url, values=None, data=None, login = True):
from urllib import urlencode
from urllib2 import Request, urlopen
if login and not self.logged_in:
self.login()
if values == None and data == None:
req = Request(url)
self.add_headers(req)
return urlopen(req)
elif data == None:
if (isinstance(values, dict)):
values = urlencode( values)
req = Request(url, values)
self.add_headers(req)
return urlopen(req)
elif values == None:
content_type, body = data
req = Request(url)
req.add_header('Content-Type', content_type)
req.add_header('Content-Length', len(str(body)))
self.add_headers(req)
req.add_data(body)
return urlopen(req)
示例8: post
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def post(self):
"""
Completes posting
CAPTCHA must be solved at this point
raises Exception, when 4chan doesn't accept your post
"""
self.data.update(self.captcha.getData())
form = http.MultiPartForm()
for k,v in self.data.iteritems():
form.add_field(k, v)
if self.file:
form.add_file('upfile', self.file, open(self.file, 'r'))
request = Request(POST % self.board)
request.add_header('User-agent', USER_AGENT)
request.add_header('Referer', self.ref)
body = str(form)
request.add_header('Content-type', form.get_content_type())
request.add_header('Content-length', len(body))
request.add_data(body)
response = urlopen(request).read()
err = RE_POSTERROR.search(response)
if err:
raise Exception("4chan says: "+err.group(1))
示例9: proxy_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def proxy_request(service_name, instance_name, method, path, body=None, headers=None):
target = get_env("TSURU_TARGET").rstrip("/")
token = get_env("TSURU_TOKEN")
if not target.startswith("http://") and not target.startswith("https://"):
target = "http://{}".format(target)
if instance_name:
url = "{}/services/{}/proxy/{}?callback=/resources/{}/{}".format(target, service_name, instance_name, instance_name, path.lstrip("/"))
else:
url = "{}/services/proxy/service/{}?callback=/resources/{}".format(target, service_name, path.lstrip("/"))
request = Request(url)
request.add_header("Authorization", "bearer " + token)
request.get_method = lambda: method
if body:
body = json.dumps(body)
try:
request.add_data(body)
except AttributeError:
request.data = body.encode('utf-8')
if headers:
for header, value in headers.items():
request.add_header(header, value)
try:
return urlopen(request, timeout=30)
except HTTPError as error:
return error
except Exception:
raise
示例10: post
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def post(self, url, body):
"""
Internal API for POST request on a OTX URL
:param url: URL to retrieve
:param body: HTTP Body to send in request
:return: response as dict
"""
request = Request(url)
request.add_header('X-OTX-API-KEY', self.key)
request.add_header('User-Agent', self.sdk)
request.add_header("Content-Type", "application/json")
method = "POST"
request.get_method = lambda: method
if body:
try: # python2
request.add_data(json.dumps(body))
except AttributeError as ae: # python3
request.data = json.dumps(body).encode('utf-8')
try:
response = urlopen(request)
data = response.read().decode('utf-8')
json_data = json.loads(data)
return json_data
except URLError as e:
if isinstance(e, HTTPError):
if e.code == 403:
raise InvalidAPIKey("Invalid API Key")
elif e.code == 400:
encoded_error = e.read()
decoded_error = encoded_error.decode('utf-8')
json.loads(decoded_error)
raise BadRequest(decoded_error)
return {}
示例11: call
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def call(self, api_call, **kwargs):
"""
Low-level method for making API calls. It handles encoding the
parameters, constructing authentication headers, decoding the response,
and converting API error responses into Python exceptions.
Args:
api_call - The API endpoint as a relative URL.
Keyword Args:
Keyword arguments are specific to the api_call and can be found in
the Janrain API documentation at:
http://developers.janrain.com/documentation/capture/restful_api/
Raises:
InvalidApiCallError, ApiResponseError
"""
# Encode values for the API (JSON, bools, nulls)
params = dict((key, api_encode(value))
for key, value in kwargs.iteritems() if value is not None)
params.update(self.defaults)
if api_call[0] != "/":
api_call = "/" + api_call
url = self.api_url + api_call
self.logger.debug(url)
# Signing the request modifies the request object and params in-place.
# Sign the request *before* encoding and passing the params.
request = Request(url)
if self.sign_requests:
self.sign_request(request, api_call, params)
print_params = params.copy()
if 'client_secret' in print_params:
print_params['client_secret'] = "CLIENT_SECRET_REMOVED"
self.logger.debug(urlencode(print_params))
request.add_data(urlencode(params))
if self.compress:
request.add_header('Accept-encoding', 'gzip')
try:
with closing(urlopen(request)) as response:
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO( response.read())
f = gzip.GzipFile(fileobj=buf)
body = f.read()
else:
body = response.read()
except HTTPError as error:
if error.code in (400, 401): # /oauth/token returns 400 or 401
body = error.fp.read()
elif error.code == 404:
raise InvalidApiCallError(api_call, error.code)
else:
raise error
return self.parse_response(body)
示例12: send_put
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def send_put(url, data):
"""Send HTTP POST."""
req = Request(url)
req.add_data(data)
req.get_method = lambda: 'PUT'
if not open_req(req):
print url
print data
示例13: download
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def download(self, text, lang="en", filename="translate_tts.mp3"):
req = Request(url='http://translate.google.com/translate_tts')
req.add_header('User-Agent', 'My agent !') #Needed otherwise return 403 Forbidden
req.add_data("tl="+lang+"&q="+text+"&ie=UTF-8")
fin = urlopen(req)
mp3 = fin.read()
fout = file(filename, "wb")
fout.write(mp3)
fout.close()
示例14: download
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def download(self, text, lang='en', filename='translate_tts.mp3'):
req = Request(url='http://translate.google.com/translate_tts')
req.add_header('User-Agent', 'Custom agent !')
req.add_data('tl='+lang+'&q='+text+'&ie=UTF-8')
fin = urlopen(req)
mp3 = fin.read()
fout = file(filename, 'wb')
fout.write(mp3)
fout.close()
示例15: _do_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import add_data [as 别名]
def _do_request(self, url, data={}, headers={}, method=None):
request = Request(url)
if method:
request.get_method = lambda: method
if data:
request.add_data(json.dumps(data))
for key, value in headers.items():
request.add_header(key, value)
return json.loads(urlopen(request).read())