Python Web server and Web framework for building Web sites

Source: Internet
Author: User
before using Django to make a small site, feel Django is too cumbersome, so ready to switch to 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 GitHub, and the documentation and extensions are plentiful and worth learning.

The best way to learn a framework is to use a framework to do a project and understand the framework in combat. Here I use the Flask framework, using the Mysql database to do a forum system. Perfectly formed, the Forum is as follows:

Forum System

Here are the basic functions of the Forum:

Complete user module (registration, login, change, retrieve password, information modification, site message notification); Rich Forum Module (create, reply to topics, site search, markdown support, @user reminders); Strong background management, support to block 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, I hope that the new web development of the students have been helpful.

We often hear about Django, Flask these Python language web frameworks, so what is the framework, and what is the difference between a web framework and a Web server (Nginx, Apache, etc.)? Can I use Python to build a Web site? To resolve these questions, We need to understand how the Web server works and the nature of the web framework.

Web Server

When we enter the URL in the browser, the browser will first request 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 server to our HTTP Response (response), the browser after rendering, with a good effect presented to us. In this process, it is the Web server that makes contributions silently behind the scenes.

Simply put, a Web server is a program that runs on a physical server, and it waits forever for the client (primarily a browser, such as Chrome,firefox, etc.) to send a request. When the request is received, it generates the corresponding response and returns it to the client. The Web server communicates with the client over the HTTP protocol and is therefore also referred to as an HTTP server.

Web Server

The Web server does not work in a complex way, and can generally be 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 a resource document from the server. Answer process: The server sends the HTTP protocol reply package to the client, and if the requested resource contains content with dynamic language, then 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 graphical results on the client screen. Close connection: The client and server are disconnected.

Below we implement a simple Web server. After running the sample program, the local port 8000 is listened to, and the response content is visible in the browser's access to http://www.php.cn/:8000. And our program can print out the client's request content, such as:

Simple Web Server

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

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

Caching mechanism: Some pages that are frequently accessed are cached to improve response speed; Security: To prevent hackers from various attacks, such as SYN Flood attack; Concurrent processing: How to respond to requests originating at the same time by different clients; LOG: Record access date to, convenient to do some analysis.

Currently the most widely used free WEB servers in UNIX and Linux platforms are Apache and Nginx.

WEB Application

The WEB server accepts Http Request, returns Response, and many times Response is not a static file, so an application is required to generate the corresponding Response based on the request. The application is 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 to do this, it is only responsible for the Http protocol level and some such as concurrency, security, logs and other related things.

Applications can be written in a variety of languages (Java, PHP, Python, Ruby, etc.), the application receives the client's request from the Web server, finishes processing, returns the response to the Web server, and finally returns the Web server to the client. The entire architecture is as follows:

Web application

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

#!/usr/bin/python #-*-coding:utf-8-*-print "content-type:text/html" Print # blank line, telling the server to end print ' 

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

Each stand-alone CGI script may duplicate the Write database connection, closing the code; Back-end developers will see a bunch of content-type and other HTML page elements unrelated to their own; Web Framework

The early development site did a lot of repetitive work, and later, in order to reduce duplication and avoid writing complex, confusing code, people extracted the critical process of web development and developed various web frameworks. With the framework, you can focus on writing clear, maintainable code without worrying about repetitive work such as database connectivity.

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

MVC Architecture

The user enters the URL, the client sends the request, the controller first gets the request, and then uses the model (MODELS) to fetch all the required data from the database, perform the necessary processing, send the processed results to the view, and the view uses the obtained data for rendering generation. The Html response is returned to the client.

In the case of the Python web framework flask, the framework itself does not restrict which architectures we use to organize our applications, but flask can well support the organization of applications in MVC.

Controller: Flask can use adorners to add route entries, as follows:

@app. Route ('/') def main_page ():   Pass

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

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

View: 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, while there are many Web servers (Apache, Nginx, Gunicorn, etc.) that need to communicate between the framework and the Web server, and if they don'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 the server of your choice without modifying your Web server code or network framework code, and match multiple different network frameworks? The answer is interface, design a set of interfaces that both parties adhere to. 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 different Web servers with Web frameworks and choose a combination that meets your needs. For example, you can use Gunicorn or Nginx/uwsgi to run a Django, flask, or web.py app.

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.