WSGIweb框架--1

from multiprocessing import Process

import re 

import sys

import socket

#设置静态文件根目录

HTML_ROOT_DIR = '.html'

WSGI = './wsgipython'

class HttpServer(object):

  def __init__(self,application):

    #构造函数,框架application

    self.server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    self.server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

    self.app = application

  def start(self):

    self.server_socket.listen(100)

    while True:

      client_socket,client_address = self.server_socket.accept()

      print('[%s,%s]',%client_address)

      client_process = Process(target=self.handle_client,args=(client_socket,))

      client.start()

      client_socket.close()

  def start_response(self,status,headers):

    #status = '200ok'

    #headers = 

    response_headers = 'HTTP/1.1' + status + '\r\n'

    for header in headers:

      response_headers += '%s:%s\r\n'%header

    self.response_headers = response_headers

 

   def handle_client(self,client_socket):

     response_data = client_socket.recv(1024)

     request_lines = request_data.splitlines()

     for line in request_lines:

        print(line)

     #解析请求报文

     #GET /HTTP/1.1

     request_start_line = request_lines[0]

     #提取用户请求文件

     file_name = re.match(r'\w+ +(/[^ ]*)',request_start_line.decode('utf-8')).group(1)

     method = re.match(r'(\w+) +/[^ ]*',request_start_line.decode('utf-8')).group(1)

     env = {

       'path_info':file_name,

       'method':method

     }

     response_bady = self.app(env,self.start_response)

     response = self.response_headers + '\r\n' + response_body

     #向客户端返回响应数据

     client_socket.send(response.encode('utf-8'))

  def bind(self,port):

    self.server_socket.bind('',port)

 

def main():

  sys.path.append('./wsgipython')

  if len(sys.argv)<2:

    sys.exit('输入格式有误')

  module_name,app_name = sys.argv[1].split(':')

  m = __import__(moudle_name)

  app = getattr(m,app)

  http_server = HttpServer(app)

  http_server.bind(8000)

  http_server.start()

if __name__ == '__main__':

  main()

posted @ 2017-08-24 13:02  py小蟒蛇  阅读(214)  评论(0编辑  收藏  举报