本文整理汇总了Python中http.server.BaseHTTPRequestHandler方法的典型用法代码示例。如果您正苦于以下问题:Python server.BaseHTTPRequestHandler方法的具体用法?Python server.BaseHTTPRequestHandler怎么用?Python server.BaseHTTPRequestHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.server
的用法示例。
在下文中一共展示了server.BaseHTTPRequestHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_handler
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def generate_handler(html, files=None):
if files is None:
files = {}
class MyHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
"""Respond to a GET request."""
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(html.encode())
elif self.path in files:
content_type, content = files[self.path]
self.send_response(200)
self.send_header("Content-type", content_type)
self.end_headers()
self.wfile.write(content.encode())
else:
self.send_error(404)
return MyHandler
示例2: run
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def run(self):
server = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
"""Serves the GEDCOM file and referenced files."""
# Take the file map in a thread-safe way.
with server.lock:
file_map = server.file_map
# Return 404 if a file is not known.
if not self.path in file_map:
self.send_response(404)
return
# Respond with the file contents.
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'https://pewu.github.io')
self.end_headers()
content = open(file_map[self.path], 'rb').read()
self.wfile.write(content)
# Bind to the local address only.
server_address = ('127.0.0.1', self.port)
httpd = HTTPServer(server_address, Handler)
httpd.serve_forever()
示例3: handler_class
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def handler_class(callback):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != "/":
self.send_response(404)
content = "not found"
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content.encode("utf-8"))
return
content = callback()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content.encode("ascii"))
return Handler
示例4: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def __init__(self, addr, handler, poll_interval=0.5,
log=False, sslctx=None):
class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler):
def __getattr__(self, name, default=None):
if name.startswith('do_'):
return self.process_request
raise AttributeError(name)
def process_request(self):
self.server._handler(self)
def log_message(self, format, *args):
if log:
super(DelegatingHTTPRequestHandler,
self).log_message(format, *args)
HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler)
ControlMixin.__init__(self, handler, poll_interval)
self.sslctx = sslctx
示例5: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def __init__(self):
super(HttpServerThread, self).__init__()
self.done = False
self.hostname = 'localhost'
class MockStardog(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != '/admin/status':
self.send_response(404)
return
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# json.dumps always outputs a str, wfile.write requires bytes
self.wfile.write(ensure_bytes(json.dumps(DATA)))
self.http = HTTPServer((self.hostname, 0), MockStardog)
self.port = self.http.server_port
示例6: _get_singleton_http_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def _get_singleton_http_server() -> HTTPServer:
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
try:
entry = ZIPFILE_ENTRIES[self.path]
except KeyError:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "application/zip")
self.end_headers()
self.wfile.write(entry.body)
server = HTTPServer(("module-zipfile-server", 0), Handler)
thread = threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.005}
)
thread.setDaemon(True) # so it dies when we finish integration-testing
thread.start()
return server
示例7: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def __init__(self, pool, launcher, queue, access_port, *args, **kwargs):
"""Creates a RequestHandler for a http request received by the server.
Args:
pool: multiprocessing process pool object.
launcher: name string of the launcher vm that the server is on.
queue: multiprocessing queue object.
access_port: port number to call on the booted vms.
*args: Other argments to apply to the request handler.
**kwargs: Keyword arguments to apply to the request handler.
"""
self.process_pool = pool
self.launcher = launcher
self.timing_queue = queue
self.access_port = access_port
# BaseHTTPRequestHandler calls do_GET inside __init__
# So we have to call super().__init__ after setting attributes.
super(RequestHandler, self).__init__(*args, **kwargs)
示例8: setUp
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def setUp(self):
super(TestRequestHandler, self).setUp()
client_address = 'localhost'
server = '/tmp/server.lock'
req = mock.MagicMock()
with mock.patch.object(BaseHTTPRequestHandler, '__init__') as m_http:
m_http.return_value = None
self._req_handler = m_pool.RequestHandler(req, client_address,
server)
self._req_handler.rfile = mock.Mock()
self._req_handler.wfile = mock.Mock()
示例9: log_message
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def log_message(self, fmt, *args):
"""
Overrides: :meth:`~http.server.BaseHTTPRequestHandler.log_message`
Ignore all log messages from being displayed in :data:`sys.stdout`.
"""
pass
示例10: _test_integration
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def _test_integration(self, client):
class HTTPHandler(BaseHTTPRequestHandler):
called = False
bearer_header_found = False
def do_HEAD(self):
self.send_response(200)
def do_GET(self):
HTTPHandler.called = True
HTTPHandler.bearer_header_found = any(
k for k in self.headers if k == "authorization" and self.headers[k] == "Bearer secret")
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
sample_dataset = {
"id": "bigqueryproject:datasetname",
"datasetReference": {
"datasetId": "datasetname",
"projectId": "bigqueryproject"
}
}
self.wfile.write(json.dumps({"kind": "bigquery#datasetList", "datasets": [sample_dataset]}).encode("utf-8"))
server_address = urlparse(self.API_BASE_URL)
with HTTPServer((server_address.hostname, server_address.port), HTTPHandler) as httpd:
threading.Thread(target=httpd.serve_forever).start()
for dataset in client.list_datasets():
self.assertEqual(dataset.dataset_id, "datasetname")
httpd.shutdown()
self.assertTrue(
HTTPHandler.called, msg="Fake server was not called from the BQ client, but should have been.")
self.assertTrue(
HTTPHandler.bearer_header_found, msg="authorization header was missing from the BQ request.")
示例11: _test_proxy
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def _test_proxy(self, client):
class HTTPHandler(BaseHTTPRequestHandler):
called = False
proxy_header_found = False
def do_HEAD(self):
self.send_response(200)
def do_GET(self):
HTTPHandler.called = True
HTTPHandler.proxy_header_found = any(
k for k in self.headers if k == "X-KAGGLE-PROXY-DATA" and self.headers[k] == "test-key")
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
sample_dataset = {
"id": "bigqueryproject:datasetname",
"datasetReference": {
"datasetId": "datasetname",
"projectId": "bigqueryproject"
}
}
self.wfile.write(json.dumps({"kind": "bigquery#datasetList", "datasets": [sample_dataset]}).encode("utf-8"))
server_address = urlparse(os.getenv('KAGGLE_DATA_PROXY_URL'))
with HTTPServer((server_address.hostname, server_address.port), HTTPHandler) as httpd:
threading.Thread(target=httpd.serve_forever).start()
for dataset in client.list_datasets():
self.assertEqual(dataset.dataset_id, "datasetname")
httpd.shutdown()
self.assertTrue(
HTTPHandler.called, msg="Fake server was not called from the BQ client, but should have been.")
self.assertTrue(
HTTPHandler.proxy_header_found, msg="X-KAGGLE-PROXY-DATA header was missing from the BQ proxy request.")
示例12: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def __init__(self, app):
self.app = app
self.format = '%s - - [%s] "%s %s %s" - %s'
f = BytesIO()
class FakeSocket:
def makefile(self, *a):
return f
# take log_date_time_string method from BaseHTTPRequestHandler
self.log_date_time_string = BaseHTTPRequestHandler(FakeSocket(), None, None).log_date_time_string
示例13: echo_json_response
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def echo_json_response(handler,code,status=None,results=None):
"""Takes a json package and returns it to the user w/ full HTTP headers"""
if handler is None or code is None:
return False
if status is None:
status = http.client.responses[code]
if results is None:
results = {}
json_res = {'code': code, 'status': status, 'results' : results}
json_response = json.dumps(json_res)
json_response = json_response.encode('utf-8')
if isinstance(handler, BaseHTTPRequestHandler):
handler.send_response(code)
handler.send_header('Content-Type', 'application/json')
handler.end_headers()
handler.wfile.write(json_response)
return True
elif isinstance(handler, tornado.web.RequestHandler):
handler.set_status(code)
handler.set_header('Content-Type', 'application/json')
handler.write(json_response)
handler.finish()
return True
else:
return False
示例14: log_message
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def log_message(self, format, *args):
"""Log an arbitrary message.
This is used by all other logging functions.
It overrides ``BaseHTTPRequestHandler.log_message``, which logs to ``sys.stderr``.
The first argument, FORMAT, is a format string for the message to be logged. If the format
string contains any % escapes requiring parameters, they should be specified as subsequent
arguments (it's just like printf!).
The client ip is prefixed to every message.
"""
self.logger.debug("%s - - %s" % (self.address_string(), format % args))
示例15: run_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import BaseHTTPRequestHandler [as 别名]
def run_server(port, auth_url):
class Server(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
query = urlparse(self.path).query
parsed_query = parse_qs(query)
if 'code' in parsed_query:
print("A request was received with an authorization code.")
global code
code = parsed_query['code'][0]
self.prepare_response()
self.kill_server()
def prepare_response(self):
python_ver = sys.version_info.major
if python_ver == 3:
self.wfile.write(bytes(html_page, 'UTF-8'))
else:
self.wfile.write(html_page)
def kill_server(self):
assassin = threading.Thread(target=httpd.shutdown)
assassin.daemon = True
assassin.start()
handler_class = Server
server_address = ('', port)
httpd = HTTPServer(server_address, handler_class)
open_webbrowser(auth_url)
print('Waiting for authorization code.')
httpd.serve_forever()