本文整理匯總了Python中BaseHTTPServer.HTTPServer方法的典型用法代碼示例。如果您正苦於以下問題:Python BaseHTTPServer.HTTPServer方法的具體用法?Python BaseHTTPServer.HTTPServer怎麽用?Python BaseHTTPServer.HTTPServer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類BaseHTTPServer
的用法示例。
在下文中一共展示了BaseHTTPServer.HTTPServer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: http_server
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def http_server(port=8000, cwd=None, terminate_callable=None):
http = HTTPServer(('', port), HTTPRequestHandler)
http.timeout = 1
if cwd is None:
cwd = os.getcwd()
http.cwd = cwd
while True:
if terminate_callable is not None:
terminate = terminate_callable()
else:
terminate = False
if terminate:
break
http.handle_request()
示例2: SetupPrometheusEndpointOnPort
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def SetupPrometheusEndpointOnPort(port, addr=""):
"""Exports Prometheus metrics on an HTTPServer running in its own thread.
The server runs on the given port and is by default listenning on
all interfaces. This HTTPServer is fully independent of Django and
its stack. This offers the advantage that even if Django becomes
unable to respond, the HTTPServer will continue to function and
export metrics. However, this also means that the features
offered by Django (like middlewares or WSGI) can't be used.
Now here's the really weird part. When Django runs with the
auto-reloader enabled (which is the default, you can disable it
with `manage.py runserver --noreload`), it forks and executes
manage.py twice. That's wasteful but usually OK. It starts being a
problem when you try to open a port, like we do. We can detect
that we're running under an autoreloader through the presence of
the RUN_MAIN environment variable, so we abort if we're trying to
export under an autoreloader and trying to open a port.
"""
assert os.environ.get("RUN_MAIN") != "true", (
"The thread-based exporter can't be safely used when django's "
"autoreloader is active. Use the URL exporter, or start django "
"with --noreload. See documentation/exports.md."
)
prometheus_client.start_http_server(port, addr=addr)
示例3: do_POST
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def do_POST(self): #J
parse_identifier(self) #K
if self.path != '/statuses/filter.json': #L
return self.send_error(404) #L
process_filters(self) #M
# <end id="streaming-http-server"/>
#A Create a new class called 'StreamingAPIServer'
#B This new class should have the ability to create new threads with each request, and should be a HTTPServer
#C Tell the internals of the threading server to shut down all client request threads if the main server thread dies
#D Create a new class called 'StreamingAPIRequestHandler'
#E This new class should be able to handle HTTP requests
#F Create a method that is called do_GET(), which will be executed on GET requests performed against this server
#G Call a helper function that handles the fetching of an identifier for the client
#H If the request is not a 'sample' or 'firehose' streaming GET request, return a '404 not found' error
#I Otherwise, call a helper function that actually handles the filtering
#J Create a method that is called do_POST(), which will be executed on POST requests performed against this server
#K Call a helper function that handles the fetching of an identifier for the client
#L If the request is not a user, keyword, or location filter, return a '404 not found' error
#M Otherwise, call a helper function that actually handles the filtering
#END
# <start id="get-identifier"/>
開發者ID:fuqi365,項目名稱:https---github.com-josiahcarlson-redis-in-action,代碼行數:25,代碼來源:ch08_listing_source.py
示例4: run_on
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def run_on(ip, port):
"""
Starts the HTTP server in the given port
:param port: port to run the http server
:return: void
"""
print("Starting a server on port {0}. Use CNTRL+C to stop the server.".format(port))
server_address = (ip, port)
try:
httpd = HTTPServer(server_address, SparrestHandler)
httpd.serve_forever()
except OSError as e:
if e.errno == 48: # port already in use
print("ERROR: The port {0} is already used by another process.".format(port))
else:
raise OSError
except KeyboardInterrupt as interrupt:
print("Server stopped. Bye bye!")
示例5: test_get
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def test_get(self):
#constructs the path relative to the root directory of the HTTPServer
response = self.request(self.tempdir_name + '/test')
self.check_status_and_reason(response, 200, data=self.data)
response = self.request(self.tempdir_name + '/')
self.check_status_and_reason(response, 200)
response = self.request(self.tempdir_name)
self.check_status_and_reason(response, 301)
response = self.request('/ThisDoesNotExist')
self.check_status_and_reason(response, 404)
response = self.request('/' + 'ThisDoesNotExist' + '/')
self.check_status_and_reason(response, 404)
f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
response = self.request('/' + self.tempdir_name + '/')
self.check_status_and_reason(response, 200)
# chmod() doesn't work as expected on Windows, and filesystem
# permissions are ignored by root on Unix.
if os.name == 'posix' and os.geteuid() != 0:
os.chmod(self.tempdir, 0)
response = self.request(self.tempdir_name + '/')
self.check_status_and_reason(response, 404)
os.chmod(self.tempdir, 0755)
示例6: call
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def call(self, input):
"""
Simple implementation to serve the build directory.
"""
try:
dirname, filename = os.path.split(input)
if dirname:
os.chdir(dirname)
httpd = HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)
sa = httpd.socket.getsockname()
url = "http://" + sa[0] + ":" + str(sa[1]) + "/" + filename
if self.open_in_browser:
webbrowser.open(url, new=2)
print("Serving your slides on " + url)
print("Use Control-C to stop this server.")
httpd.serve_forever()
except KeyboardInterrupt:
print("The server is shut down.")
示例7: test_get
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def test_get(self):
#constructs the path relative to the root directory of the HTTPServer
response = self.request(self.tempdir_name + '/test')
self.check_status_and_reason(response, 200, data=self.data)
# check for trailing "/" which should return 404. See Issue17324
response = self.request(self.tempdir_name + '/test/')
self.check_status_and_reason(response, 404)
response = self.request(self.tempdir_name + '/')
self.check_status_and_reason(response, 200)
response = self.request(self.tempdir_name)
self.check_status_and_reason(response, 301)
response = self.request('/ThisDoesNotExist')
self.check_status_and_reason(response, 404)
response = self.request('/' + 'ThisDoesNotExist' + '/')
self.check_status_and_reason(response, 404)
with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
response = self.request('/' + self.tempdir_name + '/')
self.check_status_and_reason(response, 200)
# chmod() doesn't work as expected on Windows, and filesystem
# permissions are ignored by root on Unix.
if os.name == 'posix' and os.geteuid() != 0:
os.chmod(self.tempdir, 0)
response = self.request(self.tempdir_name + '/')
self.check_status_and_reason(response, 404)
os.chmod(self.tempdir, 0755)
示例8: setUp
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def setUp(self):
self.addr = ('127.0.0.1', 22038)
self.proxy_addr = ('127.0.0.1', 22039)
self.response['http-status'] = 200
def _start_http_svr():
self.http_server = HTTPServer(self.addr, HttpHandle)
self.http_server.serve_forever()
def _start_proxy_http_svr():
self.proxy_http_server = HTTPServer(self.proxy_addr, HttpHandle)
self.proxy_http_server.serve_forever()
threadutil.start_daemon_thread(_start_http_svr)
threadutil.start_daemon_thread(_start_proxy_http_svr)
time.sleep(0.1)
self.cli = redisutil.RedisProxyClient([self.addr])
self.n = self.cli.n
self.w = self.cli.w
self.r = self.cli.r
示例9: __init__
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def __init__(self, port):
if VideoHTTPServer.__single:
raise RuntimeError, 'HTTPServer is Singleton'
VideoHTTPServer.__single = self
self.port = port
if globalConfig.get_value('allow-non-local-client-connection'):
bind_address = ''
else:
bind_address = '127.0.0.1'
BaseHTTPServer.HTTPServer.__init__(self, (bind_address, self.port), SimpleServer)
self.daemon_threads = True
self.allow_reuse_address = True
self.lock = RLock()
self.urlpath2streaminfo = {}
self.mappers = []
self.errorcallback = None
self.statuscallback = None
self.ic = None
self.load_torr = None
self.url_is_set = 0
示例10: run
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def run(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer, protocol="HTTP/1.0"):
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 443
server_address = ('', port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
示例11: __init__
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [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
示例12: startServer
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def startServer(ip, port=8000, isb64=False):
try:
DTD_CONTENTS = DTD_TEMPLATE.format(ip, port)
xxeHandler = makeCustomHandlerClass(DTD_NAME, DTD_CONTENTS, isb64)
server = HTTPServer((ip, port), xxeHandler)
#touches a file to let the other process know the server is running. super hacky
with open('.server_started','w') as check:
check.write('true')
print '\n[+] started server on {}:{}'.format(ip,port)
print '\n[+] Request away. Happy hunting.'
print '[+] press Ctrl-C to close\n'
server.serve_forever()
except KeyboardInterrupt:
print "\n...shutting down"
if os.path.exists('.server_started'):
os.remove('.server_started')
server.socket.close()
示例13: t_http
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def t_http():
try:
server = HTTPServer(('0.0.0.0', PORT_NUMBER), myHandler)
print 'Started httpserver on port ', PORT_NUMBER
server.serve_forever()
except:
server.close()
示例14: __init__
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def __init__(self, server_address, request_handler_class):
"""Constructor.
Args:
server_address: the bind address of the server.
request_handler_class: class used to handle requests.
"""
BaseHTTPServer.HTTPServer.__init__(self, server_address,
request_handler_class)
self._events = []
self._stopped = False
示例15: handle_request
# 需要導入模塊: import BaseHTTPServer [as 別名]
# 或者: from BaseHTTPServer import HTTPServer [as 別名]
def handle_request(self):
"""Override the base handle_request call.
Python 2.6 changed the semantics of handle_request() with r61289.
This patches it back to the Python 2.5 version, which has
helpfully been renamed to _handle_request_noblock.
"""
if hasattr(self, "_handle_request_noblock"):
self._handle_request_noblock()
else:
BaseHTTPServer.HTTPServer.handle_request(self)