本文整理汇总了Python中urllib2.Request.get_method方法的典型用法代码示例。如果您正苦于以下问题:Python Request.get_method方法的具体用法?Python Request.get_method怎么用?Python Request.get_method使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib2.Request
的用法示例。
在下文中一共展示了Request.get_method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: modified_run
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def modified_run(self):
import sys
try:
try:
from urllib2 import HTTPHandler, build_opener
from urllib2 import urlopen, Request
from urllib import urlencode
except ImportError:
from urllib.request import HTTPHandler, build_opener
from urllib.request import urlopen, Request
from urllib.parse import urlencode
os_ver = platform.system()
py_ver = "_".join(str(x) for x in sys.version_info)
now_ver = __version__.replace(".", "_")
code = "os:{0},py:{1},now:{2}".format(os_ver, py_ver, now_ver)
action = command_subclass.action
cid = getnode()
payload = {"v": "1", "tid": "UA-61791314-1", "cid": str(cid), "t": "event", "ec": action, "ea": code}
url = "http://www.google-analytics.com/collect"
data = urlencode(payload).encode("utf-8")
request = Request(url, data=data)
request.get_method = lambda: "POST"
connection = urlopen(request)
except:
pass
orig_run(self)
示例2: _http
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def _http(self, _method, _path, **kw):
data = None
params = None
if _method == "GET" and kw:
_path = "%s?%s" % (_path, _encode_params(kw))
if _method in ["POST", "PATCH", "PUT"]:
data = bytes(_encode_json(kw), "utf-8")
url = "%s%s" % (_URL, _path)
opener = build_opener(HTTPSHandler)
request = Request(url, data=data)
request.get_method = _METHOD_MAP[_method]
if self._authorization:
request.add_header("Authorization", self._authorization)
if _method in ["POST", "PATCH", "PUT"]:
request.add_header("Content-Type", "application/x-www-form-urlencoded")
try:
response = opener.open(request, timeout=TIMEOUT)
is_json = self._process_resp(response.headers)
if is_json:
return _parse_json(response.read().decode("utf-8"))
except HTTPError as e:
is_json = self._process_resp(e.headers)
if is_json:
json = _parse_json(e.read().decode("utf-8"))
else:
json = e.read().decode("utf-8")
req = JsonObject(method=_method, url=url)
resp = JsonObject(code=e.code, json=json)
if resp.code == 404:
raise ApiNotFoundError(url, req, resp)
raise ApiError(url, req, resp)
示例3: invokeURL
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def invokeURL(url, headers1, data, method):
request = Request(url, headers=headers1)
if method :
request.get_method=lambda: method
print ("Invoking URL ----" + request.get_full_url())
print ("\tmethod ----" + request.get_method())
print ("\t" + str(request.header_items()))
print ("\tInput data=" + str(data))
responseCode = 0
try:
if data :
result = urlopen(request, data)
else :
result = urlopen(request)
print (request.data)
with open("json_output.txt", "wb") as local_file:
local_file.write(result.read())
print ("\t*******OUTPUT**********" + open("json_output.txt").read())
responseCode = result.getcode()
print ("\tRESPONSE=" + str(responseCode))
print ("\t" + str(result.info()))
except URLError as err:
e = sys.exc_info()[0]
print( "Error: %s" % e)
e = sys.exc_info()[1]
print( "Error: %s" % e)
sys.exit()
except HTTPError as err:
e = sys.exc_info()[0]
print( "Error: %s" % e)
sys.exit()
print ("\tInvoking URL Complete----" + request.get_full_url())
return responseCode
示例4: node_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def node_request(self, node, method, path, **kwargs):
url = "http://%s:%s%s" % (node.hostname, node.port, path)
headers = {"X-Request-Id": getattr(logger.local, "request_id", "lunr-%s" % uuid4())}
if method in ("GET", "HEAD", "DELETE"):
url += "?" + urlencode(kwargs)
req = Request(url, urlencode(kwargs), headers=headers)
req.get_method = lambda *args, **kwargs: method
try:
resp = urlopen(req, timeout=self.app.node_timeout)
logger.debug("%s on %s succeeded with %s" % (req.get_method(), req.get_full_url(), resp.getcode()))
return loads(resp.read())
except (socket.timeout, urllib2.HTTPError, urllib2.URLError, HTTPException), e:
raise NodeError(req, e)
示例5: test_webhook
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def test_webhook(self):
print('Testing Webhook')
self._setup_updater('', messages=0)
d = self.updater.dispatcher
d.addTelegramMessageHandler(
self.telegramHandlerTest)
# Select random port for travis
port = randrange(1024, 49152)
self.updater.start_webhook('127.0.0.1', port,
url_path='TOKEN',
cert='./tests/test_updater.py',
key='./tests/test_updater.py')
sleep(0.5)
# SSL-Wrapping will fail, so we start the server without SSL
Thread(target=self.updater.httpd.serve_forever).start()
# Now, we send an update to the server via urlopen
message = Message(1, User(1, "Tester"), datetime.now(),
Chat(1, "group", title="Test Group"))
message.text = "Webhook Test"
update = Update(1)
update.message = message
try:
payload = bytes(update.to_json(), encoding='utf-8')
except TypeError:
payload = bytes(update.to_json())
header = {
'content-type': 'application/json',
'content-length': str(len(payload))
}
r = Request('http://127.0.0.1:%d/TOKEN' % port,
data=payload,
headers=header)
urlopen(r)
sleep(1)
self.assertEqual(self.received_message, 'Webhook Test')
print("Test other webhook server functionalities...")
request = Request('http://localhost:%d/webookhandler.py' % port)
response = urlopen(request)
self.assertEqual(b'', response.read())
self.assertEqual(200, response.code)
request.get_method = lambda: 'HEAD'
response = urlopen(request)
self.assertEqual(b'', response.read())
self.assertEqual(200, response.code)
# Test multiple shutdown() calls
self.updater.httpd.shutdown()
self.updater.httpd.shutdown()
self.assertTrue(True)
示例6: howmuch
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def howmuch(loc_param, date_param, filter_param):
res_list = []
request = Request(url+'&LAWD_CD='+loc_param+'&DEAL_YMD='+date_param)
request.get_method = lambda: 'GET'
try:
res_body = urlopen(request).read()
except UnicodeEncodeError:
return []
soup = BeautifulSoup(res_body, 'html.parser')
items = soup.findAll('item')
rTuple = re.compile('<(.*?)>([^<]+)')
for item in items:
try:
item = item.text.encode('utf-8')
#print item
office={}
for tuples in rTuple.findall(item):
office[tuples[0]] = tuples[1].strip()
#print "\t", tuples[0], tuples[1]
wolse=', 월세:'+office['월세금액']+'만원'
row = office['년']+'/'+office['월']+'/'+office['일']+', '+office['법정동']+' '+office['지번']+', '+office['아파트']+' '+office['층']+'F, '+office['전용면적']+'m², 전세:'+office['보증금액']+'만원'+wolse+'\n'
except:
print str(datetime.now()).split('.')[0]
traceback.print_exc(file=sys.stdout)
if filter_param and row.find(filter_param)<0:
row = ''
if row:
res_list.append(row.strip())
return res_list
示例7: call
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def call(self, call, token, data):
'''
Call the specified authentication API using the
urllib2 library functions.
'''
url = '%s/%s' % (self.url, call)
headersWithAuth = self.headers.copy()
headersWithAuth.update({"Authorization": "Bearer {0}".format(token)})
req = Request(url)
req.add_header("Authorization", "Bearer {0}".format(token));
req.add_header("Accept", "application/json")
logging.debug('Calling {0} with method {1} and headers {2}'.format(url, req.get_method(), headersWithAuth))
result = {}
try:
'''Python's http api is a bit ugly - it will always throw a URLError on any failure. If nothing happens, that means it's ok... '''
response = urlopen(req)
'''data': json.load(response),'''
result = { 'status': 200}
except URLError as e:
if hasattr(e, 'reason'):
logging.warn('We failed to reach a server. Reason: {0}'.format(e.reason))
result = {'status': e.code, 'message': e.reason}
elif hasattr(e, 'code'):
logging.warn('The server couldn\'t fulfill the request. Code: {0}'.format(e.code))
result = {'status': e.code, 'message': e.read()}
return result
示例8: post
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [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
示例9: makeRequest
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def makeRequest(self, method, path, params=None):
if not params:
params = {}
params['key'] = self.api_key
params['token'] = self.oauth_token
url = self.base_url + path
data = None
if method == 'GET':
url += '?' + urlencode(params)
elif method in ['DELETE', 'POST', 'PUT']:
data = urlencode(params).encode('utf-8')
request = Request(url)
if method in ['DELETE', 'PUT']:
request.get_method = lambda: method
try:
if data:
response = urlopen(request, data=data)
else:
response = urlopen(request)
except HTTPError as e:
print(e)
print(e.read())
result = None
else:
result = json.loads(response.read().decode('utf-8'))
return result
示例10: hit_endpoint
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def hit_endpoint(self, url, data_dict={}, http_method='GET'):
"""
A reusable method that actually performs the request to the specified Atlas API endpoint.
"""
if self.verbose == 'true':
print "HIT_ENDPOINT"
data_dict.update({ "access_token" : self.access_token })
if self.verbose == 'true':
print " Added access_token to data_dict (inside hit_endpoint)"
if self.verbose == 'true':
print " Constructing request URL"
request = Request(url, urllib.urlencode(data_dict))
if self.verbose == 'true':
print " Setting request http_method: %s" % http_method
request.get_method = lambda: http_method
try:
if self.verbose == 'true':
print " Opening Request URL: %s?%s" % (request.get_full_url(),request.get_data())
response = urlopen(request)
except URLError, e:
raise SystemExit(e)
示例11: generate_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def generate_request(self, path='', apikey='', limit='1000',
resume=None, filter=None):
"""
Function that generates (but does not call) and %-encodes
the HTTP GET request to the Analytic ALMA API using data
from self.Request and the parameters.
Parameters:
path The relative path to the analytic to be queried
apikey The apikey to use in the query
limit The number of results (25 - 1000) to be returned
resume A resumption token (optional)
filter A filter statement (optional)
Returns:
A properly percent-encoded / utf-encoded urllib2 Request
object ready for sending
"""
params = {}
params['path'] = path.encode('utf-8')
params['apikey'] = apikey.encode('utf-8')
params['limit'] = limit.encode('utf-8')
if filter is not None:
params['filter'] = filter.encode('utf-8')
if resume is not None:
params['token'] = resume.encode('utf-8')
req = Request( self.Request.URL + '?' + urlencode(params) )
req.get_method = lambda: 'GET'
return req
示例12: send
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def send(event, context, response_status, reason=None, response_data=None, physical_resource_id=None):
response_data = response_data or {}
response_body = json.dumps(
{
"Status": response_status,
"Reason": reason or "See the details in CloudWatch Log Stream: " + context.log_stream_name,
"PhysicalResourceId": physical_resource_id or context.log_stream_name,
"StackId": event["StackId"],
"RequestId": event["RequestId"],
"LogicalResourceId": event["LogicalResourceId"],
"Data": response_data,
}
)
opener = build_opener(HTTPHandler)
request = Request(event["ResponseURL"], data=response_body)
request.add_header("Content-Type", "")
request.add_header("Content-Length", len(response_body))
request.get_method = lambda: "PUT"
try:
response = opener.open(request)
print("Status code: {}".format(response.getcode()))
print("Status message: {}".format(response.msg))
return True
except HTTPError as exc:
print("Failed executing HTTP request: {}".format(exc.code))
return False
示例13: howmuch
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def howmuch(loc_param, date_param, filter_param):
res_list = []
request = Request(url+'&LAWD_CD='+loc_param+'&DEAL_YMD='+date_param)
request.get_method = lambda: 'GET'
try:
res_body = urlopen(request).read()
except UnicodeEncodeError:
return []
soup = BeautifulSoup(res_body, 'html.parser')
items = soup.findAll('item')
for item in items:
item = item.text.encode('utf-8')
item = re.sub('<.*?>', '|', item)
parsed = item.split('|')
try:
#row = parsed[2]+'/'+parsed[5]+'/'+parsed[6]+', '+parsed[3]+' '+parsed[4]+', '+parsed[7]+'m², '+parsed[9]+'F, '+parsed[1].strip()+'만원\n'
row = parsed[3]+'/'+parsed[6]+'/'+parsed[7]+', '+parsed[4]+' '+parsed[5]+', '+parsed[8]+'m², '+parsed[11]+'F, '+parsed[1].strip()+'만원\n'
except IndexError:
row = item.replace('|', ',')
#add link
row+="r.fun25.co.kr/r/r.py?l="+loc_param.encode('ascii','ignore')+"&p="+parsed[8]+"&a="+parsed[5].replace(" ","%20")+"&d="+date_param.encode('ascii','ignore')+"\n"
if filter_param and row.find(filter_param)<0:
row = ''
if row:
res_list.append(row.strip())
return res_list
示例14: __api__
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def __api__(self, url, method = None, params = {}, content_type = 'application/x-www-form-urlencoded'):
try:
if(params.has_key('placement')):
del params['extCompId']
#try:
if(not method): method = self.GET
request_handler = build_opener(HTTPHandler)
request_param = urlencode(params) or None
request_url = url
if(method in [self.GET, self.HEAD] and request_param):
if(not request_url.endswith('?')):
request_url += '?'
request_url += request_param
print request_url
request = Request(request_url, data = self.iif((method in [self.GET, self.HEAD]), None, request_param) )
if(method in [self.POST, self.PUT, self.DELETE, self.HEAD]):
request.add_header('Content-Type', content_type)
request.add_header('Content-Length', len(request_param or ''))
request.get_method = lambda: self.METHODS[method]
response = request_handler.open(request)
return True, response.code, response.msg, response.read()
except Exception, e:
return False, 500, str(e), '<No Content>'
示例15: api_request
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_method [as 别名]
def api_request(self, api_endpoint, method='GET', input_dict=None):
if not api_endpoint or len(api_endpoint) < 1:
raise Exception('DEP Web Service URL endpoint too short')
# add beginning slash if it doesn't exist
if not api_endpoint.startswith('/'):
api_endpoint = '/' + api_endpoint
request = Request(self.url_base + api_endpoint)
request.add_header('User-Agent', self.user_agent)
request.add_header('X-Server-Protocol-Version', '2')
request.add_header('X-ADM-Auth-Session', self.session_token)
request.add_header('Content-Type', 'application/json;charset=UTF8')
if method is not 'GET':
request.get_method = lambda: method
input_data = json.dumps(input_dict) if input_dict else None
response = urlopen(request, input_data).read()
resp_dict = json.loads(response)
return resp_dict