In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
How to implement a HTTP server in Python? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
1 、 WSGI
Here is the first piece of code. The first parameter is environ, which is used to receive a dictionary. The key-value pair provided in the dictionary is an extension of the old CGI environment set. The second parameter itself is callable and is traditionally named start_response (), which is used by WSGI applications to declare the response header information.
# simple HTTP services written in the form of WSGI applications. #! / usr/bin/env python3 # A simple HTTP service built directly against the low-level WSGI spec. From pprint import pformat from wsgiref.simple_server import make_server def app (environ, start_response): headers = {'Content-Type':' text/plain Charset=utf-8'} start_response ('200OK', list (headers.items ()) yield' Here is the WSGI environment: '.encode (' utf-8') yield pformat (environ). Encode ('utf-8') if _ _ name__ =' _ main__': httpd = make_server (', 8000, app) host, port = httpd.socket.getsockname () print ('Serving on', host,' port') Port) httpd.serve_forever ()
The above is just a simple situation. However, when writing server programs, the complexity is greatly increased. This is because many of the caveats and boundary cases described in the standard are fully taken into account.
2. Forward proxy and reverse proxy
Regardless of the forward proxy or reverse proxy, the HTTP proxy is actually a HTTP server that receives requests and then forwards received requests (at least part of the requests). The forwarding request manager acts as a client, sends the forwarded HTTP request to the real server, and finally plays the role of the client in the response received from the server, sends the forwarded request to the real server, and finally sends the response received from the server back to the original client.
The following is a schematic diagram of forward and reverse proxies.
Reverse proxy has been widely used in large-scale HTTP services. Reverse proxies are part of the Web service and are not visible to HTTP clients.
3. Four architectures
Architects typically use a variety of complex mechanisms to combine multiple sub-modules into a HTTP service. There are now four basic patterns in the Python community. If you have written Python code to generate dynamic content and have selected an API or framework that supports WSGI, how do you deploy the HTTP service online?
Run a server written in Python, and the WSGI interface can be called directly in the server's code. Green Unicorn (Gunicorn) servers are popular now, but there are other pure Python servers that can already be used in production environments.
Configure mod_wsgi and run Apache, run Python code in a separate WSFIDaemonProcess, and mod_wsgi starts the daemon.
Run a Python HTTP server similar to Gunicorn (or any server that supports the asynchronous framework of your choice) at the back end, and then run a Web server at the front end that returns static files and reverse proxies dynamic resource services written by Python.
Run a pure reverse proxy (such as Varnish) at the front end, run Apache or nginx at the back end of the reverse proxy, and run the HTTP server written by Python on the back end. This is a three-tier structure. These reverse proxies can be distributed in different geographical locations so that the cached resources on the reverse proxy closest to the client can be returned to the client that sent the request.
For a long time, the selection of these four architectures is mainly based on the three runtime characteristics of CPython, that is, the interpreter occupies a large amount of memory, the interpreter runs slowly, and the global interpreter (GIL,Global Interpreter Lock) forbids multiple threads to run Python bytecode at the same time. But at the same time, only a certain number of Python instances can be loaded in memory.
4. Platform as a Service
The emergence of this concept is due to the complexity of automated deployment, continuous integration, and the emergence and processing of technologies related to high-performance large-scale services. So some providers have proposed PaaS (Platform as a Service), and now they only need to care about how to package their applications in order to deploy their applications on these services.
The PaaS provider will address the various annoyances that arise in building and running HTTP services. You don't need to care about the server, or providing an IP address, or anything like that.
PaaS provides load balancers based on customer size. You only need to provide a configuration file to the PaaS provider to complete a variety of complex steps.
Heroku and Docker are commonly used at this stage.
Most PaaS providers do not support static content unless we implement more support for static content in Python applications or add Apache or ngnix to the container. Although we can put the paths of static resources and dynamic pages in two completely different URL spaces, many architects prefer to put both in the same namespace.
5. Write WSGI callable objects without using Web framework
The first piece of code below is the original WSGI callable object that returns the current time.
#! / usr/bin/env python3 # A simple HTTP service built directly against the low-level WSGI spec. Import time def app (environ, start_response): host = environ.get ('HTTP_HOST',' 127.0.0.1') path = environ.get ('PATH_INFO',' /') if':'in host: host, port = host.split (':', 1) if'?' In path: path, query = path.split ('?', 1) headers = [('Content-Type',' text/plain Charset=utf-8')] if environ ['REQUEST_METHOD']! =' GET': start_response ('501 Not Implemented', headers) yield baked 501 Not Implemented' elif host! =' 127.0.0.1'or path! ='/': start_response ('404 Not Found', headers) yield baked 404 Not Found' else: start_response (' 200 OK' Headers) yield time.ctime () .encode ('ascii')
The first paragraph is rather lengthy. Let's use a third-party library to simplify the schema approach of the original WGSI.
The first example is that a callable object written in WebOb returns the current time.
#! / usr/bin/env python3 # A WSGI callable built using webob. Import time, webob def app (environ, start_response): request = webob.Request (environ) if environ ['REQUEST_METHOD']! =' GET': response = webob.Response ('501 Not Implemented', status=501) elif request.domain! =' 127.0.0.1'or request.path! ='/': response = webob.Response ('404 Not Found', status=404) else: response = webob.Response (time.ctime () return response (environ) Start_response) the second is a WSGI callable object written in Werkzeug that returns the current time.
The second is that the WSGI callable object written in Werkzeug returns the current time.
#! / usr/bin/env python3 # A WSGI callable built using Werkzeug. Import time from werkzeug.wrappers import Request, Response @ Request.application def app (request): host = request.host if':'in host: host, port = host.split (':', 1) if request.method! = 'GET': return Response (' 501 Not Implemented', status=501) elif host! = '127.0.0.1' or request.path! ='/': return Response ('404 Not Found' Status=404) else: return Response (time.ctime ()) the answer to the question about how to implement a HTTP server in Python is shared here. I hope the above content can help you to a certain extent, if you still have a lot of doubts to be solved, you can follow the industry information channel to learn more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.