1. The process of browser requesting dynamic pages
##2.WSGI
Python Web Server Gateway Interface (or WSGI for short, pronounced "wizgy" ).
WSGI allows developers to separate the web framework of choice from the web server. You can mix and match web servers and web frameworks to choose a suitable pairing. For example, you can run Django, Flask, or Pyramid on Gunicorn or Nginx/uWSGI or Waitress. A true mix and match, thanks to WSGI supporting both server and architecture.
The web server must have a WSGI interface. All modern Python web frameworks already have a WSGI interface, which allows you to use it without modifying the code. The server works together with the featured web framework.
WSGI is supported by web servers, and web frameworks allow you to choose the pairing that suits you, but it also provides convenience for server and framework developers so that they can focus on their preferred areas and expertise without hindering each other. . Other languages have similar interfaces: Java has the Servlet API, and Ruby has Rack.
3. Define the WSGI interface
The WSGI interface definition is very simple. It only requires web developers to implement a function to respond to HTTP requests. Let's take a look at the simplest Web version of "Hello World!":
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])return 'Hello World!'
Copy after login
The above application() function is an HTTP processing function that complies with the WSGI standard. It receives two parameters:
- environ: a dict object containing all HTTP request information;
- start_response: a function that sends an HTTP response.
The entire application() function itself does not involve any HTTP parsing part, that is to say, the underlying web server parsing part and the application logic part are separated, so that developers can You can concentrate on one area. The
application() function must be called by the WSGI server. There are many servers that comply with the WSGI specification. The purpose of our web server project at this time is to make a server that is very likely to parse static web pages and also parse dynamic web pages.
Implementation code:
import time,multiprocessing,socket,os,reclass MyHttpServer(object):def __init__(self):
serveSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serveSocket = serveSocket
self.HTMLPATH = './html'def bind(self,port=8000):
self.serveSocket.bind(('',port))def start(self):
self.serveSocket.listen()while True:
clientSocket, clientAddr = self.serveSocket.accept()
print(clientSocket)
multiprocessing.Process(target=self.serveHandler, args=(clientSocket, clientAddr)).start()
clientSocket.close()def serveHandler(self,clientSocket,clientAddr):try:
recvData = clientSocket.recv(1024).decode('gbk')
fileName = re.split(r' +', recvData.splitlines()[0])[1]
filePath = self.HTMLPATHif fileName.endswith('.py'):try:
pyname=fileName[1:-3]# 导入
pyModule = __import__(pyname)
env={}
responseBody = pyModule.application(env,self.startResponse)
responseLine = self.responseLine
responseHeader = self.responseHeaderexcept ImportError:
responseLine = 'HTTP/1.1 404 NOT FOUND'
responseHeader = 'Server: ererbai' + os.linesep
responseHeader += 'Date: %s' % time.ctime()
responseBody = '<h1>很抱歉,服务器中找不到你想要的内容<h1>'else:if '/'== fileName:
filePath += '/index.html'else:
filePath += fileNametry:
file = None
file =open(filePath,'r',encoding='gbk')
responseBody = file.read()
responseLine = 'HTTP/1.1 200 OK'
responseHeader = 'Server: ererbai' + os.linesep
responseHeader += 'Date:%s' % time.ctime()except FileNotFoundError:
responseLine = 'HTTP/1.1 404 NOT FOUND'
responseHeader = 'Server: ererbai' + os.linesep
responseHeader += 'Date:%s' % time.ctime()
responseBody = '很抱歉,服务器中找不到你想要的内容'finally:if (file!=None) and (not file.closed):
file.close()except Exception as ex:
responseLine = 'HTTP/1.1 500 ERROR'
responseHeader = 'Server: ererbai' + os.linesep
responseHeader += 'Date: %s' % time.ctime()
responseBody = '服务器正在维护中,请稍后再试。%s'%exfinally:
senData = responseLine + os.linesep + responseHeader + os.linesep + os.linesep + responseBody
print(senData)
senData = senData.encode('gbk')
clientSocket.send(senData)if (clientSocket!=None) and ( not clientSocket._closed):
clientSocket.close()def startResponse(self,status,responseHeaders):
self.responseLine = status
self.responseHeader = ''for k,v in responseHeaders:
kv = k + ':' + v + os.linesep
self.responseHeader += kvif __name__ == '__main__':
server = MyHttpServer()
server.bind(8000)
server.start()
Copy after login
HTML files existing in the server:
biyeji.png
mytime.py file
import timedef application(env,startResponse):
status = 'HTTP/1.1 200 OK'
responseHeaders = [('Server','bfe/1.0.8.18'),('Date','%s'%time.ctime()),('Content-Type','text/plain')]
startResponse(status,responseHeaders)
responseBody = str(time.ctime())return responseBody
Copy after login
Access results:
Home page
biye.html
##mytime.py
'''
自定义的符合wsgi的框架
'''import timeclass Application(object):def __init__(self, urls):'''框架初始化的时候需要获取路由列表'''
self.urls = urlsdef __call__(self, env, startResponse):'''
判断是静态资源还是动态资源。
设置状态码和响应头和响应体
:param env:
:param startResponse:
:return:
'''# 从请求头中获取文件名
fileName = env.get('PATH_INFO')# 判断静态还是动态if fileName.startwith('/static'):
fileName = fileName[7:]if '/' == fileName:
filePath += '/index.html'else:
filePath += fileNametry:
file = None
file = open(filePath, 'r', encoding='gbk')
responseBody = file.read()
status = 'HTTP/1.1 200 OK'
responseHeaders = [('Server', 'ererbai')]except FileNotFoundError:
status = 'HTTP/1.1 404 Not Found'
responseHeaders = [('Server', 'ererbai')]
responseBody = '<h1>找不到<h1>'finally:
startResponse(status, responseHeaders)if (file != None) and (not file.closed):
file.close()else:
isHas = False # 表示请求的名字是否在urls中,True:存在,False:不存在for url, func in self.urls:if url == fileName:
responseBody = func(env, startResponse)
isHas = Truebreakif isHas == False:
status = 'HTTP/1.1 404 Not Found'
responseHeaders = [('Server', 'ererbai')]
responseBody = '<h1>找不到<h1>'
startResponse(status, responseHeaders)return responseBodydef mytime(env, startResponse):
status = 'HTTP/1.1 200 OK'
responseHeaders = [('Server', 'time')]
startResponse(status, responseHeaders)
responseBody = str(time.ctime())return responseBodydef mynews(env, startResponse):
status = 'HTTP/1.1 200 OK'
responseHeaders = [('Server', 'news')]
startResponse(status, responseHeaders)
responseBody = str('xx新闻')return responseBody'''路由列表'''
urls = [
('/mytime', mytime),
('/mynews', mynews)
]
application = Application(urls)
Copy after login
If you encounter any problems during the learning process or want to obtain learning resources, welcome to join the learning exchange group 626062078, let’s learn Python together!
The above is the detailed content of Python web server related knowledge points. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2023-03-14 15:58:02
-
1970-01-01 08:00:00
-
2023-03-15 07:38:01
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00