WSGI服务器实践二--实践一个基本功能的WSGI服务器
生活随笔
收集整理的這篇文章主要介紹了
WSGI服务器实践二--实践一个基本功能的WSGI服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
由于各種PYTHON框架都實現了WSGI接口,所以,通用性很廣的。
在調試過程過,有一個字母拼錯,搞了一個小時。
看來PYTHON自帶的編輯器沒有高亮,不爽。
在有提示的編輯器里一看就看了來啦。。:)
webserver.py
import socket import StringIO import sysclass WSGIServer(object):address_family = socket.AF_INETsocket_type = socket.SOCK_STREAMrequest_queue_size = 1def __init__(self, server_address):# Create a listening socketself.listen_socket = listen_socket = socket.socket(self.address_family,self.socket_type)# Allow to reuse the same addresslisten_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)# Bind listen_socket.bind(server_address)# Active listen_socket.listen(self.request_queue_size)# Get server host name and porthost, port = self.listen_socket.getsockname()[0:2]self.server_name = socket.getfqdn(host)self.server_port = port# Return headers set by web framework/Web applicationself.headers_set = []def set_app(self, application):self.application = applicationdef serve_forever(self):listen_socket = self.listen_socketwhile True:# New client connectionself.client_connection, client_address = listen_socket.accept()# Handle one request and close the client connection. Then# loop over to wait for another client connection self.handle_one_request()def handle_one_request(self):self.request_data = request_data = self.client_connection.recv(1024)# Print formatted request data a la 'curl -v'print(''.join('< {line} \n'.format(line=line)for line in request_data.splitlines()))self.parse_request(request_data)# Construct environment dictionary using requst dataenv = self.get_environ()# It's time to call our application callable and get# back a result that will become HTTP response bodyprint 'self.application: ********************', self.applicationresult = self.application(env, self.start_response)# Construct a response and send it back to the client self.finish_response(result)def parse_request(self, text):request_line = text.splitlines()[0]request_line = request_line.rstrip('\r\n')# Break down the request line into components(self.request_method, #GETself.path, #/helloself.request_version # HTTP/1.1) = request_line.split()def get_environ(self):env = {}# The following code snippet does not follow PEP8 conventions# but it's formatted the way it is for demonstration purposes# to emphasize the required variables and their values# # Required WSGI variablesenv['wsgi.version'] = (1, 0)env['wsgi.url_scheme'] = 'http'env['wsgi.input'] = StringIO.StringIO(self.request_data)env['wsgi.errors'] = sys.stderrenv['wsgi.multithread'] = Falseenv['wsgi.multiprocess'] = Falseenv['wsgi.run_once'] = False# Required CGI variablesenv['REQUEST_METHOD'] = self.request_method # GETenv['PATH_INFO'] = self.path # /helloenv['SERVER_NAME'] = self.server_name # localhostenv['SERVER_PORT'] = str(self.server_port) # 8888return envdef start_response(self, status, response_headers, exc_onfo=None):# Add necessary server headersserver_headers = [('Date', 'Tue, 31 Mar 2015 12:54:48 GMT'),('Server', 'WSGIServer 02'),]self.headers_set = [status, response_headers + server_headers]# To adhere to WSGI specification the start_response must return# a 'write' callable. We simplicity's sake we'll ignore that detail# for now.# return self.finish_responsedef finish_response(self, result):try:status, response_headers = self.headers_setresponse = 'HTTP/1.1 {status}\r\n'.format(status=status)for header in response_headers:response += '{0}: {1}\r\n'.format(*header)response += '\r\n'for data in result:response += data# Print formatted response data a la 'curl -v'print(''.join('> {line}\n'.format(line=line)for line in response.splitlines()))self.client_connection.sendall(response)finally:self.client_connection.close()SERVER_ADDRESS = (HOST, PORT) = '', 8888def make_server(server_address, application):server = WSGIServer(server_address)server.set_app(application)return serverif __name__ == '__main__':if len(sys.argv) < 2:sys.exit('Provide a WSGI application object as module:callable')app_path = sys.argv[1]module, application = app_path.split(':')module = __import__(module)application = getattr(module, application)httpd = make_server(SERVER_ADDRESS, application)httpd.serve_forever()print("WSGIServer: Serving HTTP on port {port}...\n".format(port=PORT))wsgiapp.py
def app(environ, start_response):""" A barebones WSGI application.This is a starting point for you own Web Framework :)"""status = '200 OK'response_headers = [('Content-Type', 'text/plain')]start_response(status, response_headers)return ['Hello world from a simple WSGI application!\n']運行命令:
python webserver.py wsgiapp:app結果:
總結
以上是生活随笔為你收集整理的WSGI服务器实践二--实践一个基本功能的WSGI服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 将一堆文件名读到一个文本里
- 下一篇: 印度浦那三周感受