The first Python Web program in getting started with Python-a simple Web Server

Source: Internet
Author: User

The first Python Web program in getting started with Python-a simple Web Server

 

Today, let's talk about the specific implementation of the Python Web service: the first Python Web program-a simple Web server.

Unlike other backend Web languages, the Python language requires you to write your own Web servers.

If you use some existing frameworks, skip this step;

If you use Python CGI programming, you can skip this step;

Use Python to create the simplest web server. Use the Python package to create a simple web server. In DOS, cd to the path to prepare the root directory of the server. Enter the following command:

Python-m Web server module [port number, default value: 8000]

For example:

Python-m SimpleHTTPServer 8080

Then you can enter

Http: // localhost: Port Number/path

To access server resources.

For example:

Http: // localhost: 8080/index.htm(of course, you must create your own index.htm file)

Other machines can also be accessed through the IP address of the server.

There are three types of "Web Server Module:

BaseHTTPServer: provides basic Web services and processor classes, including HTTPServer and BaseHTTPRequestHandler.

SimpleHTTPServer: SimpleHTTPRequestHandler class that executes GET and HEAD requests.

CGIHTTPServer: contains the class for processing POST requests and executing CGIHTTPRequestHandler.

 

Custom Handler

Google provides a service on http://chart.apis.google.com that automatically converts form data to charts. However, this service is difficult to interact with, because you need to put data as a query in the URL. This program provides a better interface for a data format: given a small text segment, it will call the chart server to generate a QR code (QR code), which is a lattice matrix for encoding text. This image can be captured by your mobile phone camera and interpreted as a string, such as a URL, which saves you the trouble of typing a URL on a small mobile phone keyboard.

The complete program is as follows:

 

Import OS # The OS module in the Python standard library contains the general operating system function import re # introduce the regular expression object import urllib # It is used to encode the URL from BaseHTTPServer import HTTPServer, baseHTTPRequestHandler # import HTTP processing-related modules # custom processing program for processing HTTP request class TestHTTPHandler (BaseHTTPRequestHandler): # process GET request def do_GET (self ): # templateStr = '''
% S

''' # Compile the regular expression into the Pattern object pattern = re. compile (R'/qr \? S = ([^ \ &] +) \ & qr = Show \ + QR ') # use Pattern to match the text and obtain the matching result. If the match fails, None match = pattern is returned. match (self. path) qrImg = ''if match: # Use Match to obtain the group information qrImg ='
'+ Urllib. unquote (match. group (1) self. protocal_version = 'HTTP/1.1 '# sets the Protocol version self. send_response (200) # Set the response status code self. send_header ("Welcome", "Contect") # sets the Response Header self. end_headers () self. wfile. write (templateStr % qrImg) # output response content # Start the service function def start_server (port): http_server = HTTPServer ('', int (port), TestHTTPHandler) http_server.serve_forever () # Set the OS to listen continuously and receive requests. chdir ('static ') # change the working directory to the static directory start_server (8000) # Start the service and listen to port 8000 for access

Here I save the above Code as: C: \ Python \ webserver \ server1.py, using UTF-8 encoding;

Open the command line and switch to the C: \ Python \ webserver \ directory,

Run: python server1.py

A firewall warning may pop up. Click "Allow access.

Access in the browser and view the effect. Open the browser and enter http: // localhost: 8000/. The result is as follows:

Enter a URL in the text box, such as (http://blog.csdn.net/testcs_dn), Click Show QR, will generate a picture of the QR code

Scan this QR code and check it out.

Summary

Unlike other backend Web languages, the Python language requires you to write your own Web servers;

However, compared with the Go language, Python is somewhat difficult to use.

Here is just a simple example of writing and running. Let's look at the effect.

Although Python has been known for a long time, it has only recently been a real contact. There are some mistakes in this article. If you have a better method, please give me more advice!

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.