Python implementation of a simple Web full version (i)

Source: Internet
Author: User
Tags local time

After a week of drag, today finally in one hours to write a mini-web, recently changed other items of the bug head is very big, but good like this state.

Black December, all the tasks are gathered in the December, and then the final exam also ignored the good review, but, I will step by step on the hands of the project to do it!!!

Return to the point: this time the Python network programming is also a crash, for Python just look at the general language framework and directly on the handwriting network programming part, the wrong hope that the elder correction ~ ~

Python version: 2.7

Ide:pycharm

Then the first few foundations of this time mainly modified the following sections:

The final completion is the following structure:

First, respond to static pages

So this step is to deal with static pages, the processing of static pages is based on the requested page name to get the magnetic
The paging file on the disk and returns.
Create a new file in the current directory plain.html, this is a static page for testing

<! DOCTYPE html>

Import the required libraries in server.py

Import sys, OS, basehttpserver
Write an exception class for the server program

Class Serverexception (Exception): "Server Internal Error" Pass

Overriding the Do_get function
# deal with a request Def do_get (self): Try:full_path = os.ge TCWD () + Self.path if not os.path.exists (Full_path): Raise Serverexception ("' {0} ' not found"                . Format (Self.path)) elif Os.path.isfile (Full_path): Self.handle_file (Full_path)                # Access Root path elif Os.path.isdir (full_path): # FullPath = Os.path.join (FullPath, "index.html") Full_path + = "index.html" if Os.path.isfile (Full_path): Self.handle_file (full                 _path) else:raise serverexception ("' {0} ' not found". Format (Self.path)) Else:            Raise Serverexception ("Unknown object ' {0} '". Format (Self.path)) except Exception as msg: Self.handle_error (msg) 

First look at the full path of the code, OS.GETCWD () is the current working directory, Self.path saved the relative path of the request, RequestHandler is inherited from Basehttprequesthandler, it has

The relative path of the request is saved in the Self.path.
Write file-handling functions and error-handling functions:

# page Model page = "
Look at the effect:

Test the wrong path again:

It also returns the error page

But at the same time if using Postman observation, return is 200 status code, do not want it to return 404, haha, so also need to modify a

Lower Handle_error and Send_content functions

This time, if you enter a URL that does not exist, you can return a 404 status code.

Display the first page content at the root URL

Add a index.html file under working directory

<! DOCTYPE html>

At this point the Do_get function also needs to be modified:

    def do_get (self):        try:            Full_path = OS.GETCWD () + Self.path            if not os.path.exists (Full_path):                    Raise Serverexception ("' {0} ' not found". Format (Self.path))            elif Os.path.isfile (full_path):                    self.handle_file ( Full_path)                # Access Root path            elif os.path.isdir (full_path):                # FullPath = Os.path.join (FullPath, "index.html")                Full_path + = "index.html"                if Os.path.isfile (full_path):                    self.handle_file (Full_path)                else:                    Raise Serverexception ("' {0} ' not found". Format (Self.path))            else:                raise Serverexception ("Unknown Object ' {0} ' ". Format (Self.path))        except Exception as msg:            self.handle_error (msg)


Look at the effect:

. CGI protocol

Sometimes, most people do not want to add new functionality to the server every time to the server source code to do
Modify. So it would be nice if the program could run independently in another script file. The following implements CGI:

The local time is displayed on the HTML page as below.
Create a new file time.py

From datetime import Datetimeprint "' 

  Imports Import subprocess, which is a module that generates child processes in a program, which is the Fork (), exec () and other functions are encapsulated

"But I haven't mastered it yet," said the seniors . later in the operating system course to learn ~ ~ ~ "

Modify the Handlefile () function

    def handle_file (self, Full_path):          # processing Python script         if Full_path.endswith ('. Py '):             # Data is the return value             after the script is run data = Subprocess.check_output ([' Python ', Full_path])             self.send_content (data)             return         try:            With open (Full_path, ' RB ') as reader:                content = Reader.read ()            self.send_content (content)         except IOError as msg:            msg = "' {0} ' cannot be read: {1}". Format (Self.path, msg)            Self.handle_error (msg)


Look at the effect:

 

W (? Д?) W.

It successfully shows the current time, see after the fear must not be able to be in the teaching area of the aunt to drive out of the study room.

No, no, not running.

The above features are written in the guidance of seniors to do their own modification of a line to achieve the ~ ~

The next chapter will also be based on the Basehttpserver.httpserver,

Basehttpserver.basehttprequesthandler again learning to achieve, now just achieve the most basic
of the infrastructure.

The following complete code is as follows:

#-*-coding:utf-8-*-import basehttpserverimport osimport subprocessclass RequestHandler (    Basehttpserver.basehttprequesthandler): "" "dealt with and return page" "" # Page Model page = "' 

  

 

Python implementation of a simple Web full version (i)

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.