本文整理汇总了Python中six.moves.http_client.HTTPConnection.request方法的典型用法代码示例。如果您正苦于以下问题:Python HTTPConnection.request方法的具体用法?Python HTTPConnection.request怎么用?Python HTTPConnection.request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.http_client.HTTPConnection
的用法示例。
在下文中一共展示了HTTPConnection.request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compute_engine_id
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def compute_engine_id():
"""Gets the Compute Engine project ID if it can be inferred.
Uses 169.254.169.254 for the metadata server to avoid request
latency from DNS lookup.
See https://cloud.google.com/compute/docs/metadata#metadataserver
for information about this IP address. (This IP is also used for
Amazon EC2 instances, so the metadata flavor is crucial.)
See https://github.com/google/oauth2client/issues/93 for context about
DNS latency.
:rtype: string or ``NoneType``
:returns: Compute Engine project ID if the metadata service is available,
else ``None``.
"""
host = '169.254.169.254'
uri_path = '/computeMetadata/v1/project/project-id'
headers = {'Metadata-Flavor': 'Google'}
connection = HTTPConnection(host, timeout=0.1)
try:
connection.request('GET', uri_path, headers=headers)
response = connection.getresponse()
if response.status == 200:
return response.read()
except socket.error: # socket.timeout or socket.error(64, 'Host is down')
pass
finally:
connection.close()
示例2: report_sauce_status
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def report_sauce_status(self, name, status, tags=[], remote_url=''):
"""Report test status and tags to SauceLabs
"""
job_id = BuiltIn().get_library_instance(
'Selenium2Library')._current_browser().session_id
if USERNAME_ACCESS_KEY.match(remote_url):
username, access_key =\
USERNAME_ACCESS_KEY.findall(remote_url)[0][1:]
else:
username = os.environ.get('SAUCE_USERNAME')
access_key = os.environ.get('SAUCE_ACCESS_KEY')
if not job_id:
return u"No Sauce job id found. Skipping..."
elif not username or not access_key:
return u"No Sauce environment variables found. Skipping..."
token = base64.encodestring('%s:%s' % (username, access_key))[:-1]
body = json.dumps({'name': name,
'passed': status == 'PASS',
'tags': tags})
connection = HTTPConnection('saucelabs.com')
connection.request('PUT', '/rest/v1/%s/jobs/%s' % (
username, job_id), body,
headers={'Authorization': 'Basic %s' % token}
)
return connection.getresponse().status
示例3: send_email
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def send_email(request):
try:
recipients = request.GET['to'].split(',')
url = request.GET['url']
proto, server, path, query, frag = urlsplit(url)
if query: path += '?' + query
conn = HTTPConnection(server)
conn.request('GET',path)
try: # Python 2.7+, use buffering of HTTP responses
resp = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
resp = conn.getresponse()
assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
rawData = resp.read()
conn.close()
message = MIMEMultipart()
message['Subject'] = "Graphite Image"
message['To'] = ', '.join(recipients)
message['From'] = '[email protected]%s' % gethostname()
text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(),url) )
image = MIMEImage( rawData )
image.add_header('Content-Disposition', 'attachment', filename="composer_" + strftime("%b%d_%I%M%p.png"))
message.attach(text)
message.attach(image)
s = SMTP(settings.SMTP_SERVER)
s.sendmail('[email protected]%s' % gethostname(),recipients,message.as_string())
s.quit()
return HttpResponse( "OK" )
except:
return HttpResponse( format_exc() )
示例4: _check_storage
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def _check_storage(ipport, path):
conn = HTTPConnection(*ipport)
conn.request('GET', path)
resp = conn.getresponse()
# 404 because it's a nonsense path (and mount_check is false)
# 507 in case the test target is a VM using mount_check
if resp.status not in (404, 507):
raise Exception(
'Unexpected status %s' % resp.status)
return resp
示例5: export_to_myexp
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def export_to_myexp(self, trans, id, myexp_username, myexp_password):
"""
Exports a workflow to myExperiment website.
"""
trans.workflow_building_mode = workflow_building_modes.ENABLED
stored = self.get_stored_workflow(trans, id, check_ownership=False, check_accessible=True)
# Convert workflow to dict.
workflow_dict = self._workflow_to_dict(trans, stored)
#
# Create and submit workflow myExperiment request.
#
# Create workflow content JSON.
workflow_content = json.dumps(workflow_dict, indent=4, sort_keys=True)
# Create myExperiment request.
request_raw = trans.fill_template(
"workflow/myexp_export.mako",
workflow_name=workflow_dict['name'],
workflow_description=workflow_dict['annotation'],
workflow_content=workflow_content,
workflow_svg=self._workflow_to_svg_canvas(trans, stored).tostring()
)
# strip() b/c myExperiment XML parser doesn't allow white space before XML; utf-8 handles unicode characters.
request = unicodify(request_raw.strip(), 'utf-8')
# Do request and get result.
auth_header = base64.b64encode('%s:%s' % (myexp_username, myexp_password))
headers = {"Content-type": "text/xml", "Accept": "text/xml", "Authorization": "Basic %s" % auth_header}
myexp_url = trans.app.config.get("myexperiment_url", self.__myexp_url)
conn = HTTPConnection(myexp_url)
# NOTE: blocks web thread.
conn.request("POST", "/workflow.xml", request, headers)
response = conn.getresponse()
response_data = response.read()
conn.close()
# Do simple parse of response to see if export successful and provide user feedback.
parser = SingleTagContentsParser('id')
parser.feed(response_data)
myexp_workflow_id = parser.tag_content
workflow_list_str = " <br>Return to <a href='%s'>workflow list." % url_for(controller='workflows', action='list')
if myexp_workflow_id:
return trans.show_message(
"""Workflow '%s' successfully exported to myExperiment. <br/>
<a href="http://%s/workflows/%s">Click here to view the workflow on myExperiment</a> %s
""" % (stored.name, myexp_url, myexp_workflow_id, workflow_list_str),
use_panels=True)
else:
return trans.show_error_message(
"Workflow '%s' could not be exported to myExperiment. Error: %s %s" %
(stored.name, response_data, workflow_list_str), use_panels=True)
示例6: set_test_status
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def set_test_status(self, passed=True):
connection = HTTPConnection("saucelabs.com")
connection.request(
'PUT',
'/rest/v1/{0}/jobs/{1}'.format(
self.username, self.driver.session_id
),
json.dumps({"passed": passed}),
headers={"Authorization": "Basic {0}".format(self.sauce_auth)}
)
result = connection.getresponse()
return result.status == 200
示例7: wait_for_server_to_hangup
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def wait_for_server_to_hangup(ipport):
try_until = time() + 30
while True:
try:
conn = HTTPConnection(*ipport)
conn.request('GET', '/')
conn.getresponse()
except Exception:
break
if time() > try_until:
raise Exception(
'Still answering on %s:%s after 30 seconds' % ipport)
sleep(0.1)
示例8: open_http_connection
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def open_http_connection(self, code, query=None, method='GET'):
"""
Send a request to non-sandboxed Splash, return an HTTPConnection.
create_file Lua function is pre-loaded.
XXX: why can't we use requests or urllib, why
don't they close a connection after a timeout error?
"""
q = {"lua_source": self.CREATE_FILE + "\n" + code}
q.update(query or {})
conn = HTTPConnection('localhost', self.splash_unrestricted.portnum)
conn.request(method, "/execute/?" + six.moves.urllib.parse.urlencode(q))
return conn
示例9: is_alive
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def is_alive(self):
"""Test that the connection is still alive.
Because the remote communication happens over HTTP we need to
make an explicit request to the remote. It is allowed for
WebDriver spec tests to not have a WebDriver session, since this
may be what is tested.
An HTTP request to an invalid path that results in a 404 is
proof enough to us that the server is alive and kicking.
"""
conn = HTTPConnection(self.server.host, self.server.port)
conn.request("HEAD", self.server.base_path + "invalid")
res = conn.getresponse()
return res.status == 404
示例10: _findMatchUrl
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def _findMatchUrl(self, tag):
h3 = tag.find('h3')
if not h3:
return ''
a = h3.find('a')
url = a.attrs.get('href', '')
# decode url
host = parse.urlsplit(url).netloc
path = url[len(parse.urljoin(url, '/')) - 1:]
conn = HTTPConnection(host, timeout=10)
conn.request('GET', path)
req = conn.getresponse()
r_url = req.getheader('Location')
conn.close()
return r_url
示例11: status
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def status(self):
succubus_status = super(AlppacaDaemon, self).status()
if succubus_status != 0:
print("succubus_status is {0}".format(str(succubus_status)))
return succubus_status
conn = HTTPConnection('169.254.169.254', timeout=0.1)
try:
conn.request("GET", "/")
conn.getresponse()
except Exception as e:
print("Error: alppaca is not reachable via IP 169.254.169.254. {0}".format(e))
return 3
else:
return 0
示例12: kill_server
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def kill_server(ipport, ipport2server, pids):
server, number = get_server_number(ipport, ipport2server)
err = Manager([server]).kill(number=number)
if err:
raise Exception("unable to kill %s" % (server if not number else "%s%s" % (server, number)))
try_until = time() + 30
while True:
try:
conn = HTTPConnection(*ipport)
conn.request("GET", "/")
conn.getresponse()
except Exception as err:
break
if time() > try_until:
raise Exception("Still answering on %s:%s after 30 seconds" % ipport)
sleep(0.1)
示例13: check_server
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def check_server(ipport, ipport2server, pids, timeout=CHECK_SERVER_TIMEOUT):
server = ipport2server[ipport]
if server[:-1] in ('account', 'container', 'object'):
if int(server[-1]) > 4:
return None
path = '/connect/1/2'
if server[:-1] == 'container':
path += '/3'
elif server[:-1] == 'object':
path += '/3/4'
try_until = time() + timeout
while True:
try:
conn = HTTPConnection(*ipport)
conn.request('GET', path)
resp = conn.getresponse()
# 404 because it's a nonsense path (and mount_check is false)
# 507 in case the test target is a VM using mount_check
if resp.status not in (404, 507):
raise Exception(
'Unexpected status %s' % resp.status)
break
except Exception as err:
if time() > try_until:
print(err)
print('Giving up on %s:%s after %s seconds.' % (
server, ipport, timeout))
raise err
sleep(0.1)
else:
try_until = time() + timeout
while True:
try:
url, token = get_auth('http://%s:%d/auth/v1.0' % ipport,
'test:tester', 'testing')
account = url.split('/')[-1]
head_account(url, token)
return url, token, account
except Exception as err:
if time() > try_until:
print(err)
print('Giving up on proxy:8080 after 30 seconds.')
raise err
sleep(0.1)
return None
示例14: _get_version
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def _get_version(self, master):
if master is not None:
conn = None
host, port = master.split(':', 2)
port = int(port)
try:
conn = HTTPConnection(host, port, timeout=self._timeout)
conn.request('GET', '/version')
resp = conn.getresponse()
if resp.status < 200 or resp.status >= 300:
return
return json.loads(resp.read().decode('utf-8'))['version']
except Exception:
logger.exception('Error')
pass
finally:
if conn:
conn.close()
示例15: predict
# 需要导入模块: from six.moves.http_client import HTTPConnection [as 别名]
# 或者: from six.moves.http_client.HTTPConnection import request [as 别名]
def predict(self, examples, **kwargs):
"""Run prediction over HTTP/REST.
:param examples: The input examples
:return: The outcomes
"""
verify_example(examples, self.input_keys)
request = self.create_request(examples)
conn = HTTPConnection(self.hostname, self.port)
conn.request('POST', self.path, json.dumps(request), self.headers)
response = conn.getresponse().read()
outcomes_list = json.loads(response)
if "error" in outcomes_list:
raise ValueError("remote server returns error: {0}".format(outcomes_list["error"]))
outcomes_list = outcomes_list["outputs"]
outcomes_list = self.deserialize_response(examples, outcomes_list)
return outcomes_list