本文整理汇总了Python中http.client.HTTPConnection方法的典型用法代码示例。如果您正苦于以下问题:Python client.HTTPConnection方法的具体用法?Python client.HTTPConnection怎么用?Python client.HTTPConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.client
的用法示例。
在下文中一共展示了client.HTTPConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_networks
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def get_networks(ignore_error=False):
"""
Get list of active ZeroTier networks.
"""
auth_token = get_auth_token()
if auth_token is None:
return []
conn = HTTPConnection("localhost", 9993)
path = "/network"
headers = {
"X-ZT1-Auth": auth_token
}
conn.request("GET", path, "", headers)
res = conn.getresponse()
data = json.loads(res.read())
# nwid field is deprecated, so make sure id field exists.
for network in data:
if 'id' not in network and 'nwid' in network:
network['id'] = network['nwid']
return data
示例2: test_http_over_https
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_http_over_https(self):
if self.scheme != 'https':
return self.skip('skipped (not running HTTPS)... ')
# Try connecting without SSL.
conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
conn.putrequest('GET', '/', skip_host=True)
conn.putheader('Host', self.HOST)
conn.endheaders()
response = conn.response_class(conn.sock, method='GET')
try:
response.begin()
self.assertEqual(response.status, 400)
self.body = response.read()
self.assertBody('The client sent a plain HTTP request, but this '
'server only speaks HTTPS on this port.')
except socket.error:
e = sys.exc_info()[1]
# "Connection reset by peer" is also acceptable.
if e.errno != errno.ECONNRESET:
raise
示例3: manage_network
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def manage_network(nwid, action="join"):
"""
Join or leave a ZeroTier network.
nwid: ZeroTier network ID, e.g. "e5cd7a9e1c8a5e83"
action: either "join" or "leave"
"""
if action == "join":
method = "POST"
elif action == "leave":
method = "DELETE"
else:
raise Exception("Unsupported action: {}".format(action))
conn = HTTPConnection("localhost", 9993)
path = "/network/{}".format(nwid)
body = "{}"
headers = {
"Content-Type": "application/json",
"X-ZT1-Auth": get_auth_token()
}
conn.request(method, path, body, headers)
res = conn.getresponse()
data = json.loads(res.read())
return data
示例4: status
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def status(self, status, **kwargs):
if self.server:
try:
conn = HTTPConnection(self.server, self.port)
conn.request('GET', '/version/')
resp = conn.getresponse()
if not resp.read().startswith('Experiment'):
raise RuntimeError()
HTTPConnection(self.server, self.port).request('POST', '', str(dict({
'id': self.id,
'version': __version__,
'status': status,
'hostname': self.hostname,
'cwd': self.cwd,
'script_path': self.script_path,
'script': self.script,
'comment': self.comment,
'time': self.time,
}, **kwargs)))
except:
warn('Unable to connect to \'{0}:{1}\'.'.format(self.server, self.port))
示例5: test_connection
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_connection(self):
""" Tests if the capability is up, and sending
HTTP 401 (Unauthorized) headers.
"""
def http_request():
client = httpclient.HTTPConnection('127.0.0.1', 8888)
client.request('GET', '/')
response = client.getresponse()
self.assertEqual(response.status, 401)
options = {'enabled': 'True', 'port': 8888, 'users': {'test': 'test'}}
http_cap = http.Http(options, self.loop)
server_coro = asyncio.start_server(
http_cap.handle_session, '0.0.0.0', 8888, loop=self.loop)
self.server = self.loop.run_until_complete(server_coro)
http_task = self.loop.run_in_executor(None, http_request)
self.loop.run_until_complete(http_task)
示例6: block_http
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def block_http(whitelist):
def whitelisted(self, host, *args, **kwargs):
try:
string_type = basestring
except NameError:
# python3
string_type = str
if isinstance(host, string_type) and host not in whitelist:
logger.warning("Denied HTTP connection to: %s" % host)
raise MockHttpCall(host)
logger.debug("Allowed HTTP connection to: %s" % host)
return self.old(host, *args, **kwargs)
whitelisted.blockade = True
if not getattr(httplib.HTTPConnection, "blockade", False):
logger.debug("Monkey patching httplib")
httplib.HTTPConnection.old = httplib.HTTPConnection.__init__
httplib.HTTPConnection.__init__ = whitelisted
示例7: disable_network
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def disable_network():
""" Disable network """
class DisableNetwork:
def __init__(self, *args, **kwargs):
raise Exception("Network through socket is disabled!")
def __call__(self, *args, **kwargs):
raise Exception("Network through socket is disabled!")
real_socket = socket.socket
client.HTTPConnection = DisableNetwork
try:
from urllib3 import connection
connection.HTTPConnection = DisableNetwork
except ImportError:
pass
socket.socket = DisableNetwork
patcher = mock.patch("asyncio.selector_events.socket.socket", real_socket)
patcher.start()
return patcher
示例8: send
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def send(verb, endpoint, body):
__API_LISTENER = __IP_ADDR + ":" + __PORT
iprint("sending to: " + __API_LISTENER)
try:
conn = httplib.HTTPConnection(__API_LISTENER)
if len(body) != 0:
conn.request(
verb,
endpoint,
body,
{"Content-Type": "application/json"}
)
else :
conn.request(verb, endpoint)
response = conn.getresponse()
body = response.read()
return response.status, response.reason, body
except (httplib.HTTPException, socket.error) as ex:
print ("Error: %s" % ex)
quit()
示例9: http
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [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()
示例10: _http_req
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def _http_req(self, method, path, payload=None, retries=2):
serialized_payload = json.dumps(payload) if payload is not None else None
try:
self._http.request(method, path, serialized_payload, self._COMMON_HEADERS)
http_response = self._http.getresponse()
except (http.BadStatusLine, http.CannotSendRequest):
self._http = http.HTTPConnection(self._host)
if retries > 0:
return self._http_req(method, path, payload, retries-1)
self._handle_error(self, None, Connection.OperationalError, "Connection has expired.")
if not http_response.status in [200, 201]:
message = "Server returned unexpected response: " + ustr(http_response.status) + ustr(http_response.read())
self._handle_error(self, None, Connection.OperationalError, message)
return http_response
示例11: test_ipv6host_header
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_ipv6host_header(self):
# Default host header on IPv6 transaction should wrapped by [] if
# its actual IPv6 address
expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
b'Accept-Encoding: identity\r\n\r\n'
conn = client.HTTPConnection('[2001::]:81')
sock = FakeSocket('')
conn.sock = sock
conn.request('GET', '/foo')
self.assertTrue(sock.data.startswith(expected))
expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
b'Accept-Encoding: identity\r\n\r\n'
conn = client.HTTPConnection('[2001:102A::]')
sock = FakeSocket('')
conn.sock = sock
conn.request('GET', '/foo')
self.assertTrue(sock.data.startswith(expected))
示例12: test_host_port
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_host_port(self):
# Check invalid host_port
for hp in ("www.python.org:abc", "user:password@www.python.org"):
self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
"fe80::207:e9ff:fe9b", 8000),
("www.python.org:80", "www.python.org", 80),
("www.python.org:", "www.python.org", 80),
("www.python.org", "www.python.org", 80),
("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
c = client.HTTPConnection(hp)
self.assertEqual(h, c.host)
self.assertEqual(p, c.port)
示例13: test_send_updating_file
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_send_updating_file(self):
def data():
yield 'data'
yield None
yield 'data_two'
class UpdatingFile():
mode = 'r'
d = data()
def read(self, blocksize=-1):
return self.d.__next__()
expected = b'data'
conn = client.HTTPConnection('example.com')
sock = FakeSocket("")
conn.sock = sock
conn.send(UpdatingFile())
self.assertEqual(sock.data, expected)
示例14: test_epipe
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def test_epipe(self):
sock = EPipeSocket(
"HTTP/1.0 401 Authorization Required\r\n"
"Content-type: text/html\r\n"
"WWW-Authenticate: Basic realm=\"example\"\r\n",
b"Content-Length")
conn = client.HTTPConnection("example.com")
conn.sock = sock
self.assertRaises(OSError,
lambda: conn.request("PUT", "/url", "body"))
resp = conn.getresponse()
self.assertEqual(401, resp.status)
self.assertEqual("Basic realm=\"example\"",
resp.getheader("www-authenticate"))
# Test lines overflowing the max line size (_MAXLINE in http.client)
示例15: send_key
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPConnection [as 别名]
def send_key(key):
addr = '127.0.0.1'
port = 8901
method = "POST"
url = '/ryu_daolicloud/'
body = json.dumps(key)
headers = {'Content-Type': 'application/json'}
try:
conn = HTTPConnection(addr, port, timeout=3)
conn.request(method, url, body, headers)
response = conn.getresponse()
if response.status != 200:
return False
except NotConnected:
return False
except Exception:
conn.close()
return False
return True