search
HomeBackend DevelopmentPython TutorialPython web server related knowledge points

Python web server related knowledge points

Jun 23, 2017 am 11:46 AM
pythonwebserver

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!'

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 = &#39;<h1>很抱歉,服务器中找不到你想要的内容<h1>&#39;else:if &#39;/&#39;== fileName:
                    filePath += &#39;/index.html&#39;else:
                    filePath += fileNametry:
                    file = None
                    file =open(filePath,&#39;r&#39;,encoding=&#39;gbk&#39;)
                    responseBody = file.read()

                    responseLine = &#39;HTTP/1.1 200 OK&#39;
                    responseHeader = &#39;Server: ererbai&#39; + os.linesep
                    responseHeader += &#39;Date:%s&#39; % time.ctime()except FileNotFoundError:
                    responseLine = &#39;HTTP/1.1 404 NOT FOUND&#39;
                    responseHeader = &#39;Server: ererbai&#39; + os.linesep
                    responseHeader += &#39;Date:%s&#39; % time.ctime()
                    responseBody = &#39;很抱歉,服务器中找不到你想要的内容&#39;finally:if (file!=None) and (not file.closed):
                        file.close()except Exception as ex:
            responseLine = &#39;HTTP/1.1 500 ERROR&#39;
            responseHeader = &#39;Server: ererbai&#39; + os.linesep
            responseHeader += &#39;Date: %s&#39; % time.ctime()
            responseBody = &#39;服务器正在维护中,请稍后再试。%s&#39;%exfinally:
            senData = responseLine + os.linesep + responseHeader + os.linesep + os.linesep + responseBody
            print(senData)
            senData = senData.encode(&#39;gbk&#39;)
            clientSocket.send(senData)if (clientSocket!=None) and ( not clientSocket._closed):
                clientSocket.close()def startResponse(self,status,responseHeaders):
        self.responseLine = status
        self.responseHeader = &#39;&#39;for k,v in responseHeaders:
            kv = k + &#39;:&#39; + v + os.linesep
            self.responseHeader += kvif __name__ == &#39;__main__&#39;:
    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>![](http://localhost:51017/day18/html/biyeji.png)<br>当年以为六月不过也很平常<br>当自己真正经历了毕业<br>才知道偶尔看到六月毕业季等字里所流露的种种想要重温却不敢提及的回忆<br>毕业了<br>那个夏天,我的毕业季,我的青春年少<br>六月<br>有人笑着说解脱,有人哭着说不舍<br>那年,<br>你对我说的你好<br>在不知不觉中<br>变成了<br>再见。</body></html>

biyeji.png
mytime.py file

import timedef application(env,startResponse):
    status = &#39;HTTP/1.1 200 OK&#39;
    responseHeaders = [(&#39;Server&#39;,&#39;bfe/1.0.8.18&#39;),(&#39;Date&#39;,&#39;%s&#39;%time.ctime()),(&#39;Content-Type&#39;,&#39;text/plain&#39;)]
    startResponse(status,responseHeaders)

    responseBody = str(time.ctime())return responseBody

Access results:


Home page

biye.html
##mytime.py
&#39;&#39;&#39;
自定义的符合wsgi的框架
&#39;&#39;&#39;import timeclass Application(object):def __init__(self, urls):&#39;&#39;&#39;框架初始化的时候需要获取路由列表&#39;&#39;&#39;
        self.urls = urlsdef __call__(self, env, startResponse):&#39;&#39;&#39;
        判断是静态资源还是动态资源。
        设置状态码和响应头和响应体
        :param env:
        :param startResponse:
        :return:
        &#39;&#39;&#39;# 从请求头中获取文件名
        fileName = env.get(&#39;PATH_INFO&#39;)# 判断静态还是动态if fileName.startwith(&#39;/static&#39;):
            fileName = fileName[7:]if &#39;/&#39; == fileName:
                filePath += &#39;/index.html&#39;else:
                filePath += fileNametry:
                file = None
                file = open(filePath, &#39;r&#39;, encoding=&#39;gbk&#39;)
                responseBody = file.read()
                status = &#39;HTTP/1.1 200 OK&#39;
                responseHeaders = [(&#39;Server&#39;, &#39;ererbai&#39;)]except FileNotFoundError:
                status = &#39;HTTP/1.1 404 Not Found&#39;
                responseHeaders = [(&#39;Server&#39;, &#39;ererbai&#39;)]
                responseBody = &#39;<h1>找不到<h1>&#39;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 = &#39;HTTP/1.1 404 Not Found&#39;
                responseHeaders = [(&#39;Server&#39;, &#39;ererbai&#39;)]
                responseBody = &#39;<h1>找不到<h1>&#39;
                startResponse(status, responseHeaders)return responseBodydef mytime(env, startResponse):
    status = &#39;HTTP/1.1 200 OK&#39;
    responseHeaders = [(&#39;Server&#39;, &#39;time&#39;)]
    startResponse(status, responseHeaders)
    responseBody = str(time.ctime())return responseBodydef mynews(env, startResponse):
    status = &#39;HTTP/1.1 200 OK&#39;
    responseHeaders = [(&#39;Server&#39;, &#39;news&#39;)]
    startResponse(status, responseHeaders)
    responseBody = str(&#39;xx新闻&#39;)return responseBody&#39;&#39;&#39;路由列表&#39;&#39;&#39;
urls = [
    (&#39;/mytime&#39;, mytime),
    (&#39;/mynews&#39;, mynews)
]

application = Application(urls)
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
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
How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment