Python的web伺服器相關知識點
1.瀏覽器請求動態頁面程序

2.WSGI
Python Web Server Gateway Interface (或簡稱WSGI,讀作“wizgy” )。
WSGI允許開發者將選擇web框架和web伺服器分開。可以混合匹配web伺服器和web框架,選擇一個適合的配對。例如,可以在Gunicorn 或 Nginx/uWSGI 或 Waitress上運行 Django, Flask, 或 Pyramid。真正的混合匹配,得益於WSGI同時支援伺服器和架構.
web伺服器必須具備WSGI接口,所有的現代Python Web框架都已具備WSGI接口,它讓你不對代碼作修改就能使伺服器和特點的web框架協同工作。
WSGI由網頁伺服器支持,而web框架允許你選擇適合自己的配對,但它同樣對於伺服器和框架開發者提供便利使他們可以專注於自己偏愛的領域和專長而不至於相互牽制。其他語言也有類似介面:java有Servlet API,Ruby 有 Rack。
3.定義WSGI介面
WSGI介面定義非常簡單,它只要求Web開發者實作一個函數,就可以回應HTTP請求。讓我們來看一個最簡單的Web版本的「Hello World!」:
def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')])return 'Hello World!'
上面的 application( ) 函數就是符合WSGI標準的一個HTTP處理函數,它接收兩個參數:
environ:一個包含所有HTTP請求資訊的dict物件;
#start_response:一個傳送HTTP回應的函式。
整個application( )函數本身沒有涉及到任何解析HTTP的部分,也就是說,把底層web伺服器解析部分和應用程式邏輯部分進行了分離,這樣開發者就可以專心做一個領域了.
application( )函數必須由WSGI伺服器來呼叫。有很多符合WSGI規範的伺服器。而我們此時的web伺服器專案的目的就是要做一個極可能解析靜態網頁也可以解析動態網頁的伺服器
實作程式碼:
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的檔案:
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
登入後複製
存取結果: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



''' 自定义的符合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)
以上是Python的web伺服器相關知識點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。
