Python exercise five-simple web App

Source: Internet
Author: User
Tags python script

Configure Apache

My previous web development was basically based on the Java platform, such as Tomcat,servlet, and so on, by Tomcat to receive HTTP requests, and then to the servlet processing, the servlet processing after the completion of the return of the results to Tomcat, Returned by Tomcat to the client, this time when learning Python CGI, the first thing to think about is the CGI circular principle, how to process a complete HTTP request? The process is as follows:

    1. Client initiates HTTP request
    2. Apache receives HTTP requests
    3. Apache (must load the corresponding processing module, such as the mod_cgid.so processing Python) to the written Python script processing
    4. The python script takes parameters and outputs an HTTP page
    5. Apache returns these outputs to the client

This is quite similar to what we know about servlet processing, but there are two unresolved issues:

    • What is the difference between Tomcat and Apache?
    • How does Apache know to hand over the request to Python (that is, Apache configuration)
The difference between Tomcat and Apache

There is no complex comparison here, and I just need to know in this column:

    1. Apache is an efficient HTTP static server that handles requests for static pages (if you need to handle dynamic requests, you need to load corresponding modules, such as Php,perl)
    2. Tomcat is a Java application server that can handle static requests, or it can handle servlet
Configure Apache to handle Pyton scripts
    1. Install Apache2 first without saying that most Linux distributions should now have their own apache2
    2. To configure apache2.conf (some may be httpd.conf, you can use locate to locate the file), modify the following
# apache2.conf Config # load the module that handles Python CGI, must have loadmodule cgid_module/usr/lib/apache2/modules/mod_cgid.so# Be sure to note the configuration of the server root is what it is, mine is/var/www
# tell Apache2 to visit/cgi-bin/time to/var/www/cgi-bin/to find the script, pay attention to have'/'Scriptalias/cgi-bin//var/www/cgi-bin/# Configure the directory where the Python script is located<directory"/var/www/cgi-bin">allowoverride None Options+execcgi-multiviews +symlinksifownermatch Order allow,deny allow from all AddHandler CGI-script CGI</Directory># recognize CGI script suffix addhandler CGI-script. CGI. py
Test configuration

Good posture is set up, you can write an example to try to configure whether the success.

Write a Python script

Create a new test.py under the/var/www/cgi-bin/directory

#!/usr/bin/env python#-*-coding=utf-8-*-ImportCGIImportcgitb;cgitb.enable ()Print "content-type:text/html"Print    #Note that a blank line must be printed out here, or the CGI cannot be resolvedPrint """"""Cgi.print_environ ()Print "</BODY></HTML>"
Modify Script Permissions
# Special Note I use the root user to log in directly, here for the sake of simplicity used 777, in the actual configuration of the weight of this is very insecure chmod 777 test.py
Launch Apache Service
# Some may be httpdservice apache2 start
viewing pages in a browser

In the browser, type: localhost/cgi-bin/test.py

See the following (as long as there is content on the line, the exact content is not the same) description of the configuration is successful

 shell environment:context_document_root /var/www/cgi-bin/ Context_prefix /cgi-bin/ Document_root /var/www/html .... (Omitted here)::  1   Server_admin [email  protected] server_name localhost server_port  80   Server_protocol HTTP /1.1   Server_ SIGNATURE  <address>apache/2.4 . 10  (Debian) Server at localhost Port 80  </address> Server_software Apache /2.4 . 10  (Debian) 
View Code

Online Editor

Above is the Python web learning before some of the environment to build work, the following is a simple Pyhton CGI program, complete the function of an online editor, you can open the file, edit the file, save the file (need to enter a password).

The whole function is relatively simple, no longer explained to the detailed process, the code is as follows:

Home
<HTML>  <Head>    <title>Editor</title>  </Head>  <Body>    <formAction= ' edit2.py 'Method= ' POST '>      <b>File name</b>      <inputtype= ' text 'name= ' filename '/>      <inputtype= ' Submit 'value= ' Open '/>  </Body></HTML>
View CodeEdit Page
#!/usr/bin/env python#-*-coding=utf-8-*-import cgiimport sysfrom os.path import join, abspath# first loss of information, so that the information can be normal output after Print "" "Content-type:text/html" "# file directory Base_dir = abspath (' data ') Form = cgi. Fieldstorage () filename = form.getvalue (' filename ') if not filename:print ' "please input a filename ' sys.exit () Text = Open (Join (base_dir, filename)). Read () print "" "<HTML>  <Head>    <title>Editing</title>  </Head>  <Body>    <formAction= ' save.py 'Method= ' POST '>      <b>File:%s</b> </BR>      <inputtype= ' hidden 'value= '%s 'name= ' filename '/>      <b>Password:</b><BR/>      <inputtype= ' Password 'name= ' Password '/><BR/>      <b>Text:</b> <BR/>      <textareacolumn= ' a 'Row= ' Ten 'name= ' text '>%s</textarea> </BR>      <inputtype= ' Submit 'value= ' Save '/>    </form>  </Body></HTML>"" " % (filename, filename, text)
View CodeSave page
#!/usr/bin/env python#-*-coding=utf-8-*-ImportCGIImportSYS fromOs.pathImportJoin, Abspath#first to lose the information, so that the output is normal backPrint "content-type:text/html\n"#directory where the files are locatedBase_dir = Abspath ('Data') Form=CGI. Fieldstorage () Text= Form.getvalue ('text') filename= Form.getvalue ('filename') Password= Form.getvalue ('Password')#Check if the parameter is emptyif  not(Text andFileName andpassword):Print 'Invalid params'sys.exit ()#Verification PasswordifPassword! ='123':    Print 'Invalid params'Sys.exit () F= Open (Join (base_dir, filename),'W') f.write (text) f.close ()Print 'The file has been saved'
View Code

Attention:

    1. Create a new file under/var/www/cgi-bin/data Edit2.dat, the file must be readable and writable
    2. Copy the above three pages into the Cgi-bin directory, the script remembers to modify the permissions, the current user must be readable executable
    3. When writing the Pyhton script, the returned HTML contains header information, there should be no blank line in front of the header, there must be a blank line between the header and the body

Code location

Http://pan.baidu.com/s/1bo5z4pL

Python exercise five-simple web App

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.