Basic concepts and development preparation for the "Python" Web development Framework

Source: Internet
Author: User
Tags install openssl virtual environment virtualenv

Basic concepts of web frameworks

It's obviously a bit of an afterthought to write this article now. But it is precisely because you have learned the flask framework, and the future plan to learn more systematic Django framework, in the learning process encountered many terms and so on, it is necessary through such a seemingly empty but the field of theoretical knowledge learning to fill themselves

Framework of the MVC system

Python has evolved to today, with dozens of different web frameworks already in the way. One of the more famous, is widely used has django,flask,tornado,twisted and so on. As a web framework, they provide the consumer with the encapsulation of the network and threads, which enables the customization of the HTTP request-response model. In addition, the top three offers a range of convenient packages for HTML templates, database read/write management, HTTP stacks, etc. from the foreground to the backend. The framework of these packages, also known as the full stack framework, is a good helper for developers.

MVC is Model,view and controller. is a software architecture model developed around the 80 's in the last century. The model, which encapsulates the data associated with the business logic of the application and how the data is processed, is part of the data logic used by the Web program to process the application, and the model provides only a performance interface through which the model can be called to access the data. Some models also provide an event notification mechanism that provides real-time updates of data to the view and controller registered on it.

View, which is responsible for the display and presentation of the data, is the direct output to the user, and in MVC, a model tends to serve multiple views, and the view needs to be registered to the model as soon as possible.

Controller, which is responsible for collecting data from the client, can be viewed as a reverse operation of the view. This means that the controller's role is to change the view according to the user's will. Of course, this change may not be directly between the two, but through model as a data center to contact the two.

Because MVC is isolated from each other, so in the process of program development, improve the interface, user interaction process and other elements without rewriting the entire program logic, just replace the relevant part of it.

Installation of a Python virtual environment

A long time ago, the first time I learned Python, I saw virturalenv this thing. The virtual environment was not a priority at the time, but it was best to use the virtual environment when doing web development. Since the development of multiple Web projects on a single computer, different projects may have different requirements for the support package, and the version may be different. If you are using the default Python environment, a project requires that a package version is 1.0,b when the project requirement is 2.0. With a virtual environment, we can have a single virtual environment for a project to manage the dependency packages it needs.

Create a virtual environment with the package called virtualenv, can be installed through the PIP install virtualenv. After the installation is complete, type the command in a specific directory

Virtualenv venv

You can generate a directory named Venv in the directory, the directory is a Python virtual environment, mainly including several directories such as include,lib,scripts, the functions of these directories and Pythonhome in the same name directory is similar. Using Venv/scripts/python.exe in a virtual environment as a binary file to execute related scripts, the context of this script is the current VENV virtual environment.

If you find it cumbersome to write the path, then you can run venv/scripts/activate.exe to switch the python context of the current system to the virtual environment, where Python is directly pointing to the python of the virtual environment. If you want to exit the context of the virtual environment, you can run Venv/scripts/deactivate.exe to exit.

Web server

Although verbally we often say that using a web framework to develop a server, but it needs to be clear that the web framework developed only a service-side program, and the real Web server is not our development. The Web server is the middle node that connects the user's browser and the Python server-side program, and currently the main Web server can choose Nginx,apache,lighthttpd,iis and so on. The role of these server components is to open a httpd process on the server side (not just one, not necessarily called httpd, which is, in short, the meaning) to accept requests from outside.

In addition, to implement the connection between the Web server and the Python program, a layer of programs called WSGI is required. WSGI's representative has UWSGI,APACHE,MOD_WSGI and so on. The WSGI full name is the Web server Gateway Interface, which is essentially an interface layer that has contacted the Web server and contacted the Pythonweb program on the other side. Examples of interfaces to one end of a Web server connection are uwsgi,fast CGI and so on, all of which are implemented by the WSGI program itself, and we need to focus on how to interface between our own programs and WSGI in accordance with WSGI rules.

Some of the WSGI implementations of Python can be used to design the interface of WSGI to the service program. Like what:

defapplication (env, Start_reponse): Start_response ('OK',[('Content-type','text/html')])    return ''## # #这个application函数就可以视作是一个简单的服务端程序 # # ### # #下面就是在编写wsgi到服务端程序的接口了 # # # fromWsgiref.simple_serverImportMake_serverif __name__=='__main__': Server= Make_server ("', 8080, application) server.serve_forever ()

After the program has started running, access to localhost:8080 can see the fixed H1 Hello,world. It can also be seen that although the WSGI program was previously said to be the interface-Layer Connection service program and the Web server, the WSGI itself could be run as a Web server. In this example we do not have a server similar to Nginx, but we can also make it run. However, for performance reasons, no production environment program will directly take the WSGI program to do the server, so wsgi as a Web server to listen to external requests are mostly used in the test environment.

In fact, the above program packaging WSGI interface layer is not very convenient for the development of service programs, so the Web development framework will basically put this layer of interface development encapsulated, we only need to use UWSGI and other WSGI program instances and it for docking, and do not care how to implement. That way we can focus on the development of the service program.

Publishing Web applications with Linux+nginx+uwsgi as a backing

Before studying flask, there was a special article about this: "http://www.cnblogs.com/franknihao/p/7202253.html", here to a certain degree of supplement to this article.

Installation Configuration Nginx

The first is nginx from the default Yum (Redhat series) or Apt-get (Ubuntu series), which is mainly installed in the following location

Where to/usr/sbin/nginx binary executable files

/ETC/NGINX/NGINX.CONF Global configuration file

/var/log/nginx/access.log Access Log

/var/log/nginx/error.log error Log

The previous article had a brief description of the configuration file in/etc/nginx/conf.d, but it was/etc/nginx/nginx.conf around the global configuration file. Now let's take a look at some of this nginx.conf configuration. :

User Nginx;##定义运行Nginx的用户worker_process4;##Nginx的最大进程数, should be set to the same number of system CPU is more reasonablePID/var/run/Nginx.pid;worker_rlimit_nofile65535;##限制每个nginx进程最多可以打开多少文件events{worker_connections768;##每个Nginx进程允许连接的最大客户端数目}http{#########    #some basic settings    #########Sendfile on;#whether to allow file uploadsClilent_header_buffer_size 32k;#upload file size limitTcp_nopush on; #Prevent network congestionTcp_nodelay on;#Prevent network congestionKeepalive_timeout 65;#maximum number of seconds to allow clients to connect longtypes_hash_max_size2048;#nginx Hash Table size setting, the larger the value is set, the greater the memory space, but the faster the routing speedError_log/var/log/nginx/Error.log; Access_log/var/log/nginx/Access.log; Include/etc/nginx/conf.d/*.conf;#load the site configuration fileinclude/etc/nginx/site-enabled/*;#load the site configuration file}

Above the last two lines mentioned in the site configuration file, Nginx Open after the service can be configured behind it a number of service programs, each service program can be regarded as a Web site. It is obviously unreasonable to configure all the sites in nginx.conf, so it is more appropriate to write the configuration of various sites in CONF.D and then include them in the application. Each site's conf file is configured with a server code block, such as the following example:

server{Listen80;##指出监听的端口, typically a site listens on one port. Is the fact that different server code blocks do not allow the same listen port to appear,
Otherwise, some of these sites will be forcibly ignored. So if you enter the URL without entering the port number (the default 80 port) in order to access the friendliness of the
You may need to configure only one server code block globally, and then access to different sites is implemented through subsequent routing settings. Root/usr/share/nginx/html;##配置HTTP根页面目录, Nginx provides default display of some default HTML files for accessing some of the underlying pages. Index index.html index.htm##配置HTTP根页面中的默认页面server_name localhost; Location/users/ { ##此处配置的是http: Forwarding address for//server_name/users/Proxy_pass http://127.0.0.1:8080/;##把指向users的所有路由都转发到本机的8080端口的/Interfaceproxy_redirect default; } error_page404/404.html##配置错误页面指向的模板}

After the configuration is complete, you can nginx-t to test whether the configuration file is syntactically correct, if OK, you can type Nginx startup Nginx,nginx-s stop off, nginx-s reload reload the profile to start.

*nginx configuration file, inside the tips and details are still a lot of, here is only coarse, after a bit, if there is a need for a special learning how to configure Nginx.

Installation Configuration Uwsgi

Uwsgi is an implementation of the WSGI program on Linux. Can be installed directly via PIP install Uwsgi (note, is a lowercase oh). The startup method can be Uwsgi--http:8080--wsgi-file app.py. This starting point means that port 8080 accepts HTTP requests, and the backend service is provided by app.py.

In addition to the way this command line is started, it is actually more of an INI-based configuration file to start the method. That is, type the command Uwsgi Uwsgi.ini. About the configuration file Uwsgi.ini, in the article published flask in detail, here is a brief explanation:

[uwsgi]  = 9090= 127.0.0.1:9090
ChDir =/opt/flasky
UID == 4= 3

Processes and threads specify the number of processes that the UWSGI program opens and the maximum number of threads per process. In other words, the maximum number of processing threads is processs * threads. CHDIR specifies the current directory after the Uwsgi is opened, so that the contents of the Wsgi-file and other involved paths can be written relative to the path. The UID specifies who is the user running the UWSGI program.

HTTP Specifies the port number when the UWSGI program is accessed directly through the HTTP method. The socket specifies the address through which the socket is connected to the UWSGI, in general, the socket interface is the same as the Nginx and other Web server docking address. If you decide to deploy the Web application in a Nginx+uwsgi way, you can write the socket without writing HTTP.

When the Uwsgi configuration file is written in the socket, in the Nginx configuration file point to the socket configuration can let the front-end request information to reach the backend service program. For example, according to the socket set in Uwsgi.ini above, set in Nginx:

server {  listen;  Location/{    uwsgi_pass http://127.0.0.1:9090;  }}

Build HTTPS Web site

The HTTP data that is transmitted based on the SSL protocol is the category of HTTPS. Here's a quick introduction to how to build an HTTPS site.

For each client that wants to access an HTTPS site, you need to go through some of these steps:

1. Install dependent packages such as OpenSSL in the server

2. Generate SSL keys and certificates

3. Configure the certificate to the Web server

4. Install the CA certificate on the client

You can first install OpenSSL and openssl-devel two packages via Yum or Apt-get. After the installation is complete, the executable file/usr/bin/openssl and the associated configuration file/usr/lib/ssl/* will be installed on the system by default. Then execute the following command in turn to generate the CA certificate, server key, and server certificate:

2048365 -2048-new-key server.key--req- in 365

After you have created all the necessary things, you can adjust the Nginx configuration to make the HTTPS site effective.

server{  listen 443;  server_name 0.0.0.0;  SSL on;  SSL_CERTIFICATE/ETC/NGINX/SSL/SERVER.CRT;  Ssl_certificate_key/etc/nginx/ssl/server.key;  Location/{    uwsgi_pass http://127.0.0.1:9090;  }}

It is important to note that Ssl_certificate and Ssl_sertificate_key must use an absolute path to the server certificate and server key.

Basic concepts and development preparation for the "Python" Web development Framework

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.