Python Application-python Server Evolution

Source: Internet
Author: User

Vamei source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

* * Note that in Python 3.x, basehttpserver, simplehttpserver, Cgihttpserver integration into the Http.server package, socketserver renamed to socketserver, please check the official Documentation.

In the previous article (writing a Python server with a socket), I used the socket interface to make a Python server that handles HTTP Requests. Any computer with an operating system and a Python interpreter can be used as an HTTP Server. I'm going to rewrite the program in the previous article here and introduce a more advanced Python package to write a more mature Python server.

Support Post

I first increase the functionality of the Server. The table is added here, as well as the "POST" method for processing the table submission Data. If you've read a Python server with a socket, you'll find that it's just a little bit more.

Original program:

# written by vamei# A Messy HTTP server based on TCP socket import socket
# addresshost = ' PORT = 8000text_content = ' ' http/1.x OK content-type:text/html# if GET method Request if Method = = ' GET ':
# if ULR is/test.jpg if src = = '/test.jpg ': content = pic_content Else:content = text_content
# Send Message Conn.sendall (content) # if POST method Request if Method = = ' POST ': form = Request.spli T (' \ r \ n ') idx = form.index (") # Find the empty line entry = form[idx:] # Main con Tent of the request value = Entry[-1].split (' = ') [-1] conn.sendall (text_content + ' \ n <p> ' + value + ' & lt;/p> ') ###### # operations, such as put the form into database # ... ######
# Close Connection Conn.close ()

The operation of the server is simple, extracting data from the POST request and then displaying it on the Screen.

Run the above Python server, as in the previous article, open with a browser.

The page has a new form and submit Button. Enter AA in the form and submit, and the page shows Aa.

My next step is to use some premium packages to simplify the previous Code.

Using Socketserver

First use the Socketserver package to conveniently set up the Server. In the process of using the socket above, we first set the socket type, then call bind (), Listen (), accept (), and finally use the while loop to let the server accept the request Continuously. The above steps can be simplified by socketserver packages.

Socketserver:

# written by vamei# use tcpserverimport socketserverhost = ' PORT = 8000text_content = ' ' http/1.x OK content-type:t ext/html

I created a tcpserver object, a server that uses a TCP Socket. While establishing the tcpserve, set the IP address and port of the Server. Use the Server_forever () method to keep the server working (just like the while loop in the original program).

We pass to tcpserver a mytcphandler class. This class defines how the socket is Manipulated. Mytcphandler inherits from Baserequesthandler. Rewrite the handler () method to specify the operation of the server in different situations.

In handler (), a self.request is queried for the request to enter the server through the socket (as we did with the socket recv () and the Sendall () operation in Handler (). You also use Self.address to refer to the client address of the Socket.

After the Socketserver transformation, the code is not simple Enough. Our communication above is based on the TCP protocol, not the HTTP Protocol. therefore, we must parse the HTTP protocol manually. We will establish a server based on the HTTP Protocol.

Simplehttpserver: using static files to respond to requests

The HTTP protocol is based on the TCP protocol, but adds more specifications. These specifications, although restricting the functionality of the TCP protocol, greatly improve the convenience of information encapsulation and Extraction.

For an HTTP request (request), it contains two important information: the request method and the Url.

Request method URL Action

GET/send text_content

Get/text.jpg Send Pic_content

POST/analyze the value contained in the request body (which is actually what we fill in the table); Send Text_content and value

Depending on the request method and url, a large HTTP server can handle thousands of different requests. In python, we can use the Simplehttpserver package and the Cgihttpserver package to prescribe actions for different requests. Where simplehttpserver can be used to handle requests for the Get method and head Method. It reads the URL address in the request, finds the corresponding static file, parses the file type, and sends the file to the client using the HTTP Protocol.

Simplehttpserver

We place the text_content in the index.html and store the text.jpg files separately. If the URL points to the index_html parent folder, Simplehttpserver reads the index.html file under the Folder.

I generate the index.html file in the current directory:

Rewrite the python server Program. Use the only class Simplehttprequesthandler in the Simplehttpserver package:

# Written by vamei# simple httpserverimport socketserverimport simplehttpserverhost = ' PORT = 8000# Create the server, Si Mplehttprequesthander is pre-defined handler in simplehttpserver packageserver = Socketserver.tcpserver ((HOST, PORT), Simplehttpserver.simplehttprequesthandler) # Start The Serverserver.serve_forever ()

The program here cannot process the post Request. I'll use CGI in the back to compensate for this FLAW. It is important to note that Python server programs become very simple. Stores content in a static file and provides the client with content based on the url, which separates the content from the server Logic. Each time I update the content, I can modify only the static file without stopping the entire Python server.

These improvements also pay a price. In the original program, the URL in request is only instructive, and I can specify any Action. In simplehttpserver, the operation is closely related to the direction of the Url. I use degrees of freedom, in exchange for a more concise Program.

Cgihttpserver: use static files or CGI to respond to requests

The Cgihttprequesthandler class in the Cgihttpserver package inherits from the Simplehttprequesthandler class, so it can be used instead of the example above to provide a service for static Files. In addition, the Cgihttprequesthandler class can also be used to run CGI Scripts.

Cgihttpserver

First look at what is CGI (Common Gateway Interface). CGI is a set of interface standards between server and application Scripts. Its function is to let the server program run the script program, the output of the program as response sent to the Customer. The overall effect is to allow the server to dynamically generate reply content without having to be confined to static files.

The cgi-enabled server receives the Client's request and runs the corresponding script file according to the URL in the Request. The server passes the information of the HTTP request and the socket information to the script file and waits for the output of the Script. The output of the script is encapsulated into a legitimate HTTP reply that is sent to the Customer. CGI can give full play to the programmability of the server and make the server "smarter".

The communication between the server and the CGI script conforms to the CGI Standard. There are many ways to implement cgi, such as CGI scripts written by Apache servers and perl, or CGI scripts written by Python servers and Shells.

In order to use cgi, we need to build the server using the Httpserver class in the Basehttpserver package. The Python server changes are Simple.

Cgihttpserver:

# written by vamei# A Messy HTTP server based on TCP socket import basehttpserverimport cgihttpserverhost = ' PORT = 8000# Create the server, cgihttprequesthandler is pre-defined handlerserver = basehttpserver.httpserver (HOST, PORT), Cgihttps Erver. Cgihttprequesthandler) # Start The Serverserver.serve_forever ()

Cgihttprequesthandler the files in the Cgi-bin and Ht-bin folders in the default current directory are CGI scripts, and files stored elsewhere are considered static files. therefore, We need to modify the index.html to change the action where the form element points to Cgi-bin/post.py.

I create a Cgi-bin folder and put the following post.py file in the cgi-bin, which is our CGI script:

#!/usr/bin/env python
# Written by Vamei
Import Cgiform = Cgi. Fieldstorage () # Output to stdout, Cgihttpserver would take this as response to the Clientprint "content-type:text/html" 
   # HTML is followingprint                               # blank line, end of Headersprint "<p>hello world!</p>"         # Start of CONTENTP Rint "<p>" +  repr (form[' FirstName ') + "</p>"

(post.py need to have execute permission, see comment area)

The first line describes the language in which the script is used, Python. The CGI package is used to extract the table information contained in the Request. The script is only responsible for outputting all the results to the standard output (using print). The Cgihttprequesthandler collects these outputs, which are encapsulated in an HTTP reply and sent to the Client.

For a request to the post method, its URL needs to point to a CGI script (that is, a file in Cgi-bin or ht-bin). Cgihttprequesthandler inherits from simplehttprequesthandler, so it can also handle requests for the Get method and head Method. At this point, if the URL points to a CGI script, the server transmits the result of the script to the client, and when the URL points to a static file, the server transfers the contents of the file to the Client.

further, I can have CGI scripts perform database operations, such as putting the received data into the database and richer program Operations. Related content Withheld.

Summarize

I used some of the advanced packages in the Python standard library to simplify the Python server. The final effect separates static content, CGI applications, and servers, reducing the coupling between the three, making the code simple and easy to maintain.

I hope you enjoy the process of erecting a server on your own computer.

Welcome to the Python quick tutorial

Python Application-python Server Evolution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.