本文整理汇总了Python中urllib.request.Request.get_method方法的典型用法代码示例。如果您正苦于以下问题:Python Request.get_method方法的具体用法?Python Request.get_method怎么用?Python Request.get_method使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.request.Request
的用法示例。
在下文中一共展示了Request.get_method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def upload(self):
###Everything about uploding data to GeoServer is handling in here.
status = 1 # I use it for managing operations. If status = 0 nothing to do.
if not self.upDlg.urlText.text() or not self.upDlg.userText.text() \
or not self.upDlg.passText.text() or not self.upDlg.sldText.text():
QMessageBox.critical(None, 'Information', 'Please fill in all fields.')
else:
username = self.upDlg.userText.text()
password = self.upDlg.passText.text()
sldName = self.upDlg.sldText.text()
login = base64.b64encode(str.encode(username + ':' + password)).decode("utf-8")
basicLogin = 'Basic ' + login # Base64 auth for REST service.
# Deleting the SLD if exists on GeoServer.
if self.upDlg.urlText.text()[-1] == '/':
usableUrl = self.upDlg.urlText.text()[:len(
self.upDlg.urlText.text()) - 1] # Maybe user add slash '/' in the end of url, so this problem is solved in this way.
else: # I didnt use urlparse lib. Because this solution is simplier than it.
usableUrl = self.upDlg.urlText.text()
try:
url = usableUrl + '/styles/' + sldName + ".sld"
requestPut = Request(url)
requestPut.add_header("Authorization", basicLogin)
requestPut.add_header("Content-type", "application/vnd.ogc.sld+xml")
requestPut.add_header("Accept", "*/*")
requestPut.data = str.encode(self.dlg.sldText1.text())
requestPut.get_method = lambda: 'PUT'
urlopen(requestPut)
QMessageBox.information(None, 'Information', 'The style was succesfully uploaded.')
self.upDlg.close()
except:
try:
url = usableUrl + '/styles'
requestPrepare = Request(url)
requestPrepare.add_header("Authorization", basicLogin)
requestPrepare.add_header("Content-type", "text/xml")
requestPrepare.add_header("Accept", "*/*")
requestPrepare.data = str.encode(
'<style><name>' + sldName + '</name><filename>' + (sldName + '.sld') + '</filename></style>') #
urlopen(requestPrepare)
url = usableUrl + '/styles/' + sldName + ".sld"
requestPut = Request(url)
requestPut.add_header("Authorization", basicLogin)
requestPut.add_header("Content-type", "application/vnd.ogc.sld+xml")
requestPut.add_header("Accept", "*/*")
requestPut.data = str.encode(self.dlg.sldText1.text())
requestPut.get_method = lambda: 'PUT'
urlopen(requestPut)
QMessageBox.information(None, 'Information', 'The style was succesfully uploaded.')
self.upDlg.close()
except Exception as error:
QMessageBox.critical(None, 'Information', str(error))
示例2: RequestTests
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
class RequestTests(unittest.TestCase):
def setUp(self):
self.get = Request("http://www.python.org/~jeremy/")
self.post = Request("http://www.python.org/~jeremy/",
"data",
headers={"X-Test": "test"})
def test_method(self):
self.assertEqual("POST", self.post.get_method())
self.assertEqual("GET", self.get.get_method())
def test_add_data(self):
self.assertFalse(self.get.has_data())
self.assertEqual("GET", self.get.get_method())
self.get.add_data("spam")
self.assertTrue(self.get.has_data())
self.assertEqual("POST", self.get.get_method())
def test_get_full_url(self):
self.assertEqual("http://www.python.org/~jeremy/",
self.get.get_full_url())
def test_selector(self):
self.assertEqual("/~jeremy/", self.get.get_selector())
req = Request("http://www.python.org/")
self.assertEqual("/", req.get_selector())
def test_get_type(self):
self.assertEqual("http", self.get.get_type())
def test_get_host(self):
self.assertEqual("www.python.org", self.get.get_host())
def test_get_host_unquote(self):
req = Request("http://www.%70ython.org/")
self.assertEqual("www.python.org", req.get_host())
def test_proxy(self):
self.assertFalse(self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
self.assertTrue(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.get_origin_req_host())
self.assertEqual("www.perl.org", self.get.get_host())
def test_wrapped_url(self):
req = Request("<URL:http://www.python.org>")
self.assertEqual("www.python.org", req.get_host())
def test_urlwith_fragment(self):
req = Request("http://www.python.org/?qs=query#fragment=true")
self.assertEqual("/?qs=query", req.get_selector())
req = Request("http://www.python.org/#fun=true")
self.assertEqual("/", req.get_selector())
示例3: execute
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def execute(self, uri, http_verb, extra_headers=None, **kw):
if not ('app_id' in self.ACCESS_KEYS and 'token' in self.ACCESS_KEYS):
raise PostoError('Missing connection credentials %s' % self.ACCESS_KEYS)
url = uri if uri.startswith(API_ROOT) else API_ROOT + uri
data = kw or {}
if http_verb == 'GET' and data:
url += '?%s' % urlencode(data)
data = {}
data.update(self.ACCESS_KEYS)
data = urlencode(data).encode('utf-8')
headers = {
'Content-type': 'application/x-www-form-urlencoded',
# Need to have user-agent header because API is behind CloudFlare
# and CloudFlare will block requests without user-agent header
'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/38.0',
}
headers.update(extra_headers or {})
request = Request(url, data, headers)
request.get_method = lambda: http_verb
try:
response = urlopen(request, timeout=CONNECTION_TIMEOUT)
except HTTPError as e:
raise PostoError(e.read())
return json.loads(response.read().decode('utf-8'))
示例4: send_request
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def send_request(
self, url, payload="", content_type="application/json", method="GET", raw=False, timeout=30, silent=False
):
try:
opener = build_opener(HTTPHandler)
request = Request(url, data=bytes(payload, "UTF-8") if sys.version_info >= (3,) else bytes(payload))
request.add_header("Content-Type", content_type)
request.get_method = lambda: method
response = opener.open(request, timeout=timeout)
buf = ""
while 1:
data = response.read()
if not data:
break
buf += str(data, "UTF-8") if sys.version_info >= (3,) else data
return json.loads(buf) if not raw else buf
except socket.timeout:
if not silent:
print_color("Error: timed out while trying to communicate with %s:%d" % (self.host, self.port))
except URLError as e:
if not silent:
print_color("Error: %s while attempting to communicate with %s:%d" % (e.reason, self.host, self.port))
except ValueError as e:
if not silent:
print_color("Error: %s while trying to process result from Riak" % e)
return None
示例5: call_api
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def call_api(self, endpoint, method, headers=None, params=[], data=None):
path = self.parse_path(endpoint, params)
# If the caller specified customer headers merge them with the default
# headers.
actual_headers = self.headers.copy()
if headers is not None:
for header_key in headers:
actual_headers[header_key] = headers[header_key]
# Send the request and receive the response
request = Request(
'https://' + self.server_ip + self.base_uri + path,
headers=actual_headers)
request.get_method = lambda: method
try:
# returns response object for opening url.
return urlopen(request, data)
except HTTPError as e:
# an object which contains information similar to a request object
return e
except URLError as e:
if (isinstance(e.reason, ssl.SSLError) and
e.reason.reason == "CERTIFICATE_VERIFY_FAILED"):
print("Certificate verification failed.")
sys.exit(3)
else:
raise e
示例6: request
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self.cj))
if post:
post = bytearray(post, "utf-8")
request = Request(baseurl, data=post)
request.add_header("Content-Type", "application/json")
else:
request = Request(baseurl)
request.add_header("User-Agent", self.useragent)
request.add_header("Authorization", self.get_authkey())
request.add_header("Accept", "*/*")
request.add_header("Accept-Language", "sv-se")
request.add_header("Connection", "keep-alive")
request.add_header("Proxy-Connection", "keep-alive")
self.cj.set_cookie(
Cookie(version=0, name='dsid', value=dsid, port=None,
port_specified=False, domain='.api.swedbank.se',
domain_specified=False, domain_initial_dot=False,
path='/',
path_specified=True, secure=False, expires=None,
discard=True, comment=None, comment_url=None,
rest={'HttpsOnly': None}, rfc2109=False))
request.get_method = lambda: method
tmp = self.pch.open(request)
self.data = tmp.read().decode("utf8")
示例7: raw
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def raw(ctx, method, url, datafp=None):
"""Do the raw http method call on url."""
if method not in ("GET", "POST", "PUT", "DELETE"):
raise ValueError("HTTP method '{}' is not known".format(method))
if method in ("PUT", "DELETE"):
raise NotImplementedError("HTTP method '{}' is not yet implemented".format(method))
#TODO: we need a real debugging
print("DEBUG: {} {}".format(method, url))
data = None
request = Request(url)
if hasattr(request, method):
request.method = method
else:
request.get_method = lambda: method
if method == "POST":
data = datafp.read() if datafp is not None else b""
request.add_header("Content-Type", "application/octet-stream")
response = ctx.opener.open(request, data)
if response.getcode() != 200:
raise NotImplementedError("non 200 responses are not yet implemented")
return response
示例8: request
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def request(url, headers={}, method=None):
if method:
if sys.version_info.major >= 3:
req = Request(url, headers=headers, method=method)
else:
req = Request(url, headers=headers)
req.get_method = lambda: method
else:
req = Request(url, headers=headers)
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
elif hasattr(ssl, '_create_stdlib_context'):
context = ssl._create_stdlib_context()
elif hasattr(ssl, 'SSLContext'):
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
else:
context = None
if context:
res = urlopen(req, context=context)
else:
res = urlopen(req)
if not hasattr(res, 'getheader'):
# urllib2 does not have getheader
res.getheader = lambda name, self=res: self.info().getheader(name)
return res
示例9: _add_logo
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def _add_logo(self, show, audio):
# APIC part taken from http://mamu.backmeister.name/praxis-tipps/pythonmutagen-audiodateien-mit-bildern-versehen/
url = show.station.logo_url
if url is not None:
request = Request(url)
request.get_method = lambda: 'HEAD'
try:
response = urlopen(request)
logo_type = response.info().gettype()
if logo_type in ['image/jpeg', 'image/png']:
img_data = urlopen(url).read()
img = APIC(
encoding=3, # 3 is for utf-8
mime=logo_type,
type=3, # 3 is for the cover image
desc=u'Station logo',
data=img_data
)
audio.add(img)
except (HTTPError, URLError) as e:
message = "Error during capturing %s - %s" % (url, e)
self.log.error(message)
except Exception as e:
raise e
示例10: fetch
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def fetch(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the contents of the response."""
params = urlencode(_prepare_params(params, params_prefix))
binary_params = params.encode('ASCII')
# build the HTTP request
url = "https://%s/%s.xml" % (CHALLONGE_API_URL, uri)
req = Request(url, binary_params)
req.get_method = lambda: method
# use basic authentication
user, api_key = get_credentials()
auth_handler = HTTPBasicAuthHandler()
auth_handler.add_password(
realm="Application",
uri=req.get_full_url(),
user=user,
passwd=api_key
)
opener = build_opener(auth_handler)
try:
response = opener.open(req)
except HTTPError as e:
if e.code != 422:
raise
# wrap up application-level errors
doc = ElementTree.parse(e).getroot()
if doc.tag != "errors":
raise
errors = [e.text for e in doc]
raise ChallongeException(*errors)
return response
示例11: make_api_call
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def make_api_call(self, method, url, json_params=None):
"""
Accesses the branch API
:param method: The HTTP method
:param url: The URL
:param json_params: JSON parameters
:return: The parsed response
"""
url = self.BRANCH_BASE_URI + url
if self.verbose is True:
print("Making web request: {}".format(url))
if json_params is not None:
encoded_params = json.dumps(json_params)
headers = {"Content-Type": "application/json"}
else:
encoded_params = None
headers = {}
if encoded_params is not None and self.verbose is True:
print("Params: {}".format(encoded_params))
request = Request(url, encoded_params.encode("utf-8"), headers)
request.get_method = lambda: method
response = urlopen(request).read()
return json.loads(response.decode("utf-8"))
示例12: shutdown_kernel
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def shutdown_kernel(self):
url = self.baseurl + "/kernels/" + self.kernel_id
req = Request(url)
req.add_header("Content-Type", "application/json")
req.get_method = lambda: "DELETE"
data = urlopen(req)
data.read()
self.status_callback("closed")
示例13: get_method
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def get_method(self):
"""The Request object has been enhanced to handle PUT, DELETE, OPTIONS,
and HEAD request methods.
"""
if self._method:
return self._method
else:
return BaseRequest.get_method(self)
示例14: build_request
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def build_request(self, url, method="GET", data=None):
if not all((self.username, self.password)):
return Request(url)
auth = '%s:%s' % (self.username, self.password)
auth = {'Authorization': 'Basic %s' % (base64.b64encode(auth.encode("utf_8")).decode("utf_8").strip())}
request = Request(url, data, auth)
request.get_method = lambda: method
return request
示例15: turn_off
# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import get_method [as 别名]
def turn_off(self):
"""Turn Light Off"""
req = Request(self.state_url,
data=bytearray('{ "on" : false}', 'utf-8'))
req.get_method = lambda: 'PUT'
response = request.urlopen(req)
self.state['on'] = False
return response.read()