The Web server and web framework _python Python builds the web site

Source: Internet
Author: User
Tags comments documentation http request mysql database in python

Before using Django to do a small site, the feeling that Django is too cumbersome, so ready to change a more lightweight Web framework to play. web.py author has been hung up, the project has not been updated for a long time, so not ready to use it. And flask is also a mature lightweight Web framework, with many Star and Fork on the GitHub, and rich in documentation and extension, worth learning.

The best way to learn a framework is to use the framework to do a project and understand the framework in actual combat. Here I use the flask framework, using the Mysql database to do a forum system. Though small, spite, Forum effect chart as follows:

Forum System screenshot

The following are the basic features of the Forum:

Complete user module (registration, login, change, retrieve password, information modification, Station message notification); Rich Forum Module (create, reply topic, site Search, markdown support, @user reminders); Strong background management, support shielding users, topics, comments, support a variety of conditions search topics, comments;

This blog will use a series of articles to record the process of building the forum system, hoping to help students just getting started web development.

We've often heard of Django, flask the web framework of these Python languages, so what is the framework, and what is the difference between a web framework and a Web server (Nginx, Apache, and so on)? Leaving the frame can you build a Web site with Python? To resolve these questions, It is necessary to understand how the Web server works and the nature of the web framework.

Web Server

When we enter a URL in the browser, the browser first requests the DNS server to obtain the IP address of the requesting site. Then send an HTTP request (request) to the host that owns the IP, and then receive the HTTP Response (response) that the server gives us, and the browser renders it to us in a better effect after rendering. In this process, it is the Web server behind the scenes silently contribute.

In simple terms, a Web server is a program running on a physical server that permanently waits for clients (primarily browsers, such as Chrome,firefox, etc.) to send requests. When a request is received, it generates the corresponding response and returns it to the client. The Web server communicates with the client through the HTTP protocol and is therefore called an HTTP server.

Web Server

Web servers are not working in a complex, generally divided into 4 steps: Establishing a connection, requesting a process, answering a process, and closing a connection.

Establish a connection: the client establishes a TCP connection to the server through the TCP/IP protocol. Request process: The client sends an HTTP protocol request packet to the server requesting the resource documentation in the server. Answer process: The server sends an HTTP protocol reply pack to the client, and if the requested resource contains content from a dynamic language, the server invokes the dynamic language's interpretation engine to handle "dynamic content" and returns the processed data to the client. The client interprets the HTML document and renders the graphic results on the client screen. Close connection: The client is disconnected from the server.

Here we implement a simple Web server. After running the sample program, it listens on local port 8000, and the response content is visible when the browser accesses the http://localhost:8000. Our program can also print out the request from the client, as shown below:

Simple Web Server

Both the request and Response are required to comply with the HTTP protocol, the HTTP protocol details, you can read the HTTP authoritative guide, or look at the HTTP part of my collation.

Although the main job of the Web server is to return response based on request, the actual Web server is far more complex than the example above, because there are so many factors to consider, such as:

Caching mechanism: Some pages that are often accessed are cached to improve the response speed; Security: Prevent hackers from all kinds of attacks, such as SYN Flood attacks; Concurrent processing: How to respond to requests initiated simultaneously by different clients; LOG: Record access date to facilitate some analysis.

The most popular free WEB servers currently available under UNIX and Linux platforms are Apache and Nginx.

WEB Application

The WEB server accepts Http Request, returns Response, many times Response is not a static file, therefore need an application to generate corresponding Response according to request. The applications here are mainly used to process the related business logic, read or update the database, and return the corresponding Response according to different Request. Note that this is not the WEB server itself doing this, it is only responsible for Http protocol level and some things such as concurrency, security, log and so on.

Applications can be written in a variety of languages (Java, PHP, Python, Ruby, etc.), the application will receive requests from the Web server, processing is completed, and then returned to the Web server, and finally returned to the client by the Web server. The entire architecture is as follows:

Web application

In Python, for example, the most primitive and straightforward way to develop the web using Python is to use the CGI standard, which was popular in the 1998. First make sure that the WEB server supports CGI and has configured the CGI handler, then set up the CGI directory, add the corresponding Python file in the directory, each Python file processing the corresponding input, generate an HTML file, the following example:

#!/usr/bin/python 
#-*-coding:utf-8-*- 
print ' content-type:text/html ' 
Print # empty line, tell server end header 
print ' & Lt;html> ' 
print '  
 

This allows you to access the file in the browser and get a simple Hello world page content. Writing a WEB application directly through CGI looks very simple, with each file processing input, generating HTML. But the actual development, may encounter many inconvenient places. Like what:

Each standalone CGI script may duplicate the Write database connection, and close the code; The backend developer will see a bunch of content-type and other HTML page elements that are irrelevant to them; Web Framework

The early development site did a lot of repetitive work, and later, to reduce duplication and avoid writing complex and confusing code, people extracted the key process of web development and developed a variety of web frameworks. With a framework, you can focus on writing clear, maintainable code without being concerned with repetitive work such as database connections.

One of the more classic web frameworks uses the MVC architecture, as shown in the following illustration:

MVC Architecture

The user enters the URL, the client sends the request, the controller (Controller) first obtains the request, then uses the model (Models) to take out all the necessary data from the database, carries on the necessary processing, sends the processing result to the view, the view uses obtains the data, carries on the rendering generation The Html response is returned to the client.

Taking the Python web framework flask As an example, the framework itself does not define which architecture we use to organize our applications, but flask can well support an MVC approach to organizing applications.

Controller: Flask can use adorners to add routing items as follows:

@app. Route ('/') 
def Main_Page (): 
  

Model: used primarily to take out the required data, as in the following function:

@app. Route ('/') 
def main_page (): "" " 
  searches the database for entries, then displays, them. 
  " " db = get_db () 
  cur = db.execute (' SELECT * from entries ORDER by id desc ') 
  entries = Cur.fetchall () 
  

Views: Flask uses JINJA2 to render the page, and the following template file specifies the style of the page:

{% for entry in entries%} 
<li> 
  
 

We know that Python has a lot of web frameworks, and there are a lot of Web servers (Apache, Nginx, Gunicorn, etc.) that need to communicate between the framework and the Web server, if they can't match each other at design time, It is obviously unreasonable to choose a framework that restricts the choice of WEB servers.

So how do you make sure that you can use your own chosen server without modifying the Web server code or network framework code, and match multiple different network frameworks? The answer is interface, design a set of interfaces that both sides can follow. For Python, it is the WSGI (WEB server Gateway Interface,web Server gateways Interface). Other programming languages also have similar interfaces: Java's servlet API and Ruby's rack, for example.

The advent of Python WSGI allows developers to separate Web frameworks from Web server choices and no longer restrict each other. Now you can really mix the different Web servers with the Web framework and choose a combination that meets your needs. For example, you can use Gunicorn or Nginx/uwsgi to run Django, flask, or web.py applications.

WSGI Fitting

In the next article we will carefully analyze the WSGI interface standards and then write a simple WSGI Web server together.

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.