本文整理汇总了Python中urllib.request.request方法的典型用法代码示例。如果您正苦于以下问题:Python request.request方法的具体用法?Python request.request怎么用?Python request.request使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.request
的用法示例。
在下文中一共展示了request.request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _make_request
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def _make_request(self, opener, request, timeout=None):
"""Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: urllib.Request object
:param timeout: timeout value or None
:type timeout: float
:return: urllib response
"""
timeout = timeout or self.timeout
try:
return opener.open(request, timeout=timeout)
except HTTPError as err:
exc = handle_error(err)
return exc
示例2: check_ros_version
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def check_ros_version(architecture: str, version: str) -> bool:
"""
:param architecture:
:param version:
:return:
"""
if not all(isinstance(var, str) for var in (architecture, version)):
raise TypeError("Expected str type for architecture and version, got {0} and {1}".format(
type(architecture), type(version)))
url = "{}/{}/routeros-{}-{}.npk".format(MK_DOWNLOAD_CDN, version, architecture, version)
request = urllib.Request(url)
request.get_method = lambda: "HEAD"
try:
urllib.urlopen(request)
except IOError:
return False
return True
示例3: http
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def http(method, url, body=None, headers=None):
url_info = urlparse.urlparse(url)
if url_info.scheme == "https":
con = httplib.HTTPSConnection(url_info.hostname, url_info.port or 443)
else:
con = httplib.HTTPConnection(url_info.hostname, url_info.port or 80)
con.request(method, url_info.path, body, headers)
response = con.getresponse()
try:
if 400 <= response.status < 500:
raise HttpClientError(response.status, response.reason,
response.read())
elif 500 <= response.status < 600:
raise HttpServerError(response.status, response.reason,
response.read())
else:
yield response
finally:
con.close()
示例4: RetrieveHeader
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def RetrieveHeader(Target):
ReplyHeaders = ""
print(O+' [*] Making request to retrieve HHTP headers...')
if "https" in Target[:5]:
sslcontext = ssl.create_default_context()
n = input(O+' [§] Ignore SSL certificate errors? (Y/n) :> ')
if n == 'y' or n == 'Y':
print(GR+" [*] Ignoring certificate errors...")
sslcontext = ssl._create_unverified_context()
try:
ReplyHeaders = urllib.urlopen(Target,context=sslcontext).headers.headers
except ssl.CertificateError:
print(R+" [-] SSL Certificate authentication error...")
return ReplyHeaders
else:
ReplyHeaders = urllib.urlopen(Target).headers.headers
return ReplyHeaders
示例5: get_output_path
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def get_output_path(request, path_format, path_format_var):
# 取得输出文件的路径
OutputPathFormat = (request.GET.get(path_format, USettings.UEditorSettings["defaultPathFormat"]) % path_format_var).replace("\\", "/")
# 分解OutputPathFormat
OutputPath, OutputFile = os.path.split(OutputPathFormat)
OutputPath = os.path.join(USettings.gSettings.MEDIA_ROOT, OutputPath)
# 如果OutputFile为空说明传入的OutputPathFormat没有包含文件名,因此需要用默认的文件名
if not OutputFile:
OutputFile = USettings.UEditorSettings["defaultPathFormat"] % path_format_var
OutputPathFormat = os.path.join(OutputPathFormat, OutputFile)
if not os.path.exists(OutputPath):
os.makedirs(OutputPath)
return (OutputPathFormat, OutputPath, OutputFile)
# 涂鸦功能上传处理
示例6: make_request
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def make_request(self,
method,
request_body=None,
query_params=None,
request_headers=None):
method = method.upper()
if request_headers:
self._set_headers(request_headers)
request_body = json.dumps(request_body) if request_body else None
query_params = query_params if query_params else None
opener = urllib.build_opener()
request = urllib.Request(self._build_url(query_params),
data=request_body)
for key, value in self.request_headers.iteritems():
request.add_header(key, value)
request.get_method = lambda: method
self._response = opener.open(request)
self._set_response(self._response)
self._reset()
示例7: _update_headers
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def _update_headers(self, request_headers):
"""Update the headers for the request
:param request_headers: headers to set for the API call
:type request_headers: dictionary
:return: dictionary
"""
self.request_headers.update(request_headers)
示例8: download
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def download(url, server_fname, local_fname=None, progress_update_percentage=5):
"""
An internet download utility modified from
http://stackoverflow.com/questions/22676/
how-do-i-download-a-file-over-http-using-python/22776#22776
"""
try:
import urllib
urllib.urlretrieve('http://google.com')
except AttributeError:
import urllib.request as urllib
u = urllib.urlopen(url)
if local_fname is None:
local_fname = server_fname
full_path = local_fname
meta = u.info()
with open(full_path, 'wb') as f:
try:
file_size = int(meta.get("Content-Length"))
except TypeError:
print("WARNING: Cannot get file size, displaying bytes instead!")
file_size = 100
print("Downloading: %s Bytes: %s" % (server_fname, file_size))
file_size_dl = 0
block_sz = int(1E7)
p = 0
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
if (file_size_dl * 100. / file_size) > p:
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl *
100. / file_size)
print(status)
p += progress_update_percentage
示例9: GET
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def GET(path):
url = getURL()
opener = getOpener()
request = urllib.Request(url)
response = opener.open(request)
setValues(response)
示例10: POST
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def POST(path):
url = getURL()
opener = getOpener()
request = urllib.Request(url, GLOBALS['POSTDATA'])
response = opener.open(request)
setValues(response)
示例11: create_metadata
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def create_metadata(self, key, secret, ds_name, data_frequency, desc,
has_history=True, has_live=True):
"""
Returns
-------
"""
headers = get_signed_headers(ds_name, key, secret)
r = requests.post(
'{}/marketplace/register'.format(AUTH_SERVER),
json=dict(
ds_name=ds_name,
desc=desc,
data_frequency=data_frequency,
has_history=has_history,
has_live=has_live,
),
headers=headers,
)
if r.status_code != 200:
raise MarketplaceHTTPRequest(
request='register', error=r.status_code
)
if 'error' in r.json():
raise MarketplaceHTTPRequest(
request='upload file', error=r.json()['error']
)
示例12: extractArticlePublishedDate
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def extractArticlePublishedDate(articleLink, html = None):
print("Extracting date from " + articleLink)
articleDate = None
try:
articleDate = _extractFromURL(articleLink)
if html is None:
request = urllib.Request(articleLink)
# Using a browser user agent, decreases the change of sites blocking this request - just a suggestion
# request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
html = urllib.build_opener().open(request).read()
parsedHTML = BeautifulSoup(html,"lxml")
possibleDate = _extractFromLDJson(parsedHTML)
if possibleDate is None:
possibleDate = _extractFromMeta(parsedHTML)
if possibleDate is None:
possibleDate = _extractFromHTMLTag(parsedHTML)
articleDate = possibleDate
except Exception as e:
print("Exception in extractArticlePublishedDate for " + articleLink)
print(e.args)
return articleDate
示例13: get_ueditor_settings
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def get_ueditor_settings(request):
return HttpResponse(json.dumps(USettings.UEditorUploadSettings, ensure_ascii=False), content_type="application/javascript")
示例14: get_ueditor_controller
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def get_ueditor_controller(request):
"""获取ueditor的后端URL地址 """
action = request.GET.get("action", "")
reponseAction = {
"config": get_ueditor_settings,
"uploadimage": UploadFile,
"uploadscrawl": UploadFile,
"uploadvideo": UploadFile,
"uploadfile": UploadFile,
"catchimage": catcher_remote_image,
"listimage": list_files,
"listfile": list_files
}
return reponseAction[action](request)
示例15: stage2discharge
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import request [as 别名]
def stage2discharge(gage, usgs_id):
'''
Function to convert stage data to discharge using usgs reference table
Input
-------
gage : masked array,
array of stage data to be converted
usgs_id : int,
8 digit identifier for river on usgs
Output
---------
flux : masked array,
discharge data in cubic feet
'''
import urllib.request as urllib
# Load lookup table
url = discharge_url + usgs_id
stage = []
discharge = []
header = 0
for line in urllib.urlopen(url):
if not line.startswith(b'#'):
if header < 2:
header += 1
else:
a = line.split(b'\t')
stage.append(float(line.split(b'\t')[0]))
discharge.append(float(line.split(b'\t')[2]))
stage = np.asarray(stage).astype(float)
discharge = np.asarray(discharge).astype(float)
# Convert data
flux = np.ma.masked_array(np.zeros(len(gage)), mask=gage.mask)
for i, f in enumerate(gage):
if f:
flux[i] = discharge[(np.abs(stage - f)).argmin()]
return flux