1. The process of browser requesting dynamic pages

def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')])return 'Hello World!'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.
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()HTML files existing in the server:
- index.html
<html><head><title>首页-毕业季</title><meta http-equiv=Content-Type content="text/html;charset=gbk"></head><body>我们仍需共生命的慷慨与繁华相爱,即使岁月以刻薄和荒芜相欺。</body></html>
- biye.html
<!DOCTYPE html><html lang="en"><head><meta charset="gbk"><title>毕业季</title></head><body><br>当年以为六月不过也很平常<br>当自己真正经历了毕业<br>才知道偶尔看到六月毕业季等字里所流露的种种想要重温却不敢提及的回忆<br>毕业了<br>那个夏天,我的毕业季,我的青春年少<br>六月<br>有人笑着说解脱,有人哭着说不舍<br>那年,<br>你对我说的你好<br>在不知不觉中<br>变成了<br>再见。</body></html>

biyeji.png
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
Access results:

Home page

biye.html

''' 自定义的符合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)
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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version
