程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python WSGI learning notes

編輯:Python

Purpose : Build the simplest server framework ( Access local static and dynamic resources )

One 、 General train of thought :

        1、 Create a listening socket

        2、 Bind local information (IP and port)

        3、 Use listen Change monitoring status

        4、 Wait for the client ( browser ) Link to , And create a service socket serving the client ( Use the multi process call service method to serve the client )

        5、 The service method : Get the data sent by the client >>> Use regular expressions to match the information sent by the client , Get the information needed by the server

>>> Visit the static web page , Directly match the resource address locally , Read and send to the client ( browser ) 

>>> Access dynamic resources , Calling the framework application Method , Get the data returned by the framework , Assemble into response data , Send to client ( browser ) 

Code up :Wsgi_Server.py

from socket import *
import re,multiprocessing,time
import mini_frame
class WSGIServer(object):
def __init__(self):
# 1、 Create a listening socket
self.server_socket = socket(AF_INET, SOCK_STREAM)
self.server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
# self.server_socket.setblocking(False)
# 2、 Binding local IP and port Information , Local information is in tuple format
self.server_socket.bind(('', 8080))
# 3、 Use listen Change monitoring status , Set listening capacity
self.server_socket.listen(128)
def client_sever(self,new_socket):
# 5、 Get the information sent by the client , And set the received data byte size
request = new_socket.recv(1024).decode('utf-8')
# 6、 Use regular expressions to match the information sent by the client , Get the information needed by the server , Local matching resource address
g = re.match(r'[^/]*/+([^ ]*)\s+', request)
if g:
file_name = g.group(1)
# 7、 According to the match , Operate locally
# Open local resource , Read the local data as the response body
if not file_name.endswith('.py'):
try: # Execute code
with open(file_name, 'rb') as f:
response_body = f.read()
except: # Execute when an exception occurs
response_body = '<h1>hello world! not found</h1>'.encode('utf-8')
finally: # Whether there is any abnormality , Code that will execute
response_header = 'HTTP/1.1\r\n'
response_header += '\r\n'
print(file_name)
# Assemble local data
response = response_header.encode('utf-8') + response_body
# 8、 Send the matched local resources to the client
new_socket.send(response)
# 9、 Close client socket , End of service , Wait for the next client link .
new_socket.close()
else:
# Calling the framework application Method , Pass dictionary and class methods , Support wsgi agreement
env=dict()
env['path_info'] = file_name
response_body = mini_frame.application(env,self.start_response)
# Assemble response head , Be careful , Each row of data must be followed by \r\n
response_header = 'HTTP/1.1 {} \r\n'.format(self.status)
for i in self.hearders:
response_header += '{}:{}\r\n'.format(i[0],i[1])
response_header += '\r\n'
response =response_header + response_body
new_socket.send(response.encode('utf-8'))
# 9、 Close client socket , End of service , Wait for the next client link .
new_socket.close()
def start_response(self,status,hearders):
# Save the status code and response header returned by the framework , For class properties , Convenient for subsequent calls
self.status = status
self.hearders = hearders
def run_forever(self):
while True:
# 4、 Receive the server link , Create a client socket to serve the client
new_socket, client_addr = self.server_socket.accept()
# Create a process to serve clients
p=multiprocessing.Process(target=self.client_sever,args=(new_socket,))
p.start()
# Close the client socket
new_socket.close()
def main():
''' Control the whole , Create a web Server object , Then call a method to execute '''
w=WSGIServer()
w.run_forever()
if __name__ == '__main__':
main()

mini_frame.py

import time
def login():
return ' This is the landing page , current time :{}'.format(time.ctime())
def index():
return ' This is the home page , current time :{}'.format(time.ctime())
def application(env,start_response):
# Call the passed method , Return the response status code and header information
start_response('200 OK',[('Content-Type','text/html;charset=UTF-8')])
if env['path_info'] == 'login.py':
return login()
elif env['path_info'] == 'index.py':
return index()
else:
return 'hello world! Winter came body'


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved