search
HomeBackend DevelopmentPython TutorialDetailed introduction to deployment in Python

I have been learning flask for a while, but I have never deployed it, so I was thinking about how to deploy it. Think about it, let’s get the service started first, so I thought about getting the service started first. Here is the choice It is Flask+uwsgi+Nginx+Ubuntu. The Python option is 2.7.2. This is the one that comes with the Ubuntu system. It feels simple to learn without having to go through the software connection. Currently, my own flask is written in python3, and I will slowly transition to it. , let’s get this figured out first, then it will be very easy to optimize. In fact, I don't know much about many principles. Let's set this up first and slowly understand the logic inside.

Nginx

Nginx is an efficient web server and reverse proxy server that can be used as a load balancing (when n users access the server, it can achieve offloading and share the server's load. pressure), compared with Apache, Nginx supports high concurrency, can support millions of TCP connections, and hundreds of thousands of concurrent connections. It is simple to deploy, consumes less memory, and has low cost. However, Nginx does not have as many modules as Apache. Nginx supports uWSGI's uwsgi protocol, so we can combine Nginx with uWSGI, and Nginx hands over dynamic content to uWSGI for processing through uwsgi_pass.

Official documentation is here

The best Nginx tutorial is here

uwsgi

uWSGI is a web server that implements WSGI protocol, uwsgi, http and other protocols. The function of HttpUwsgiModule in Nginx is to exchange with uWSGI server.
Pay attention to the distinction between the three concepts of WSGI / uwsgi / uWSGI.
  • Those who have read the previous section will know that WSGI is a communication protocol.
  • uwsgi is a line protocol rather than a communication protocol. It is often used for data communication between the uWSGI server and other network servers.
  • uWSGI is a web server that implements two protocols, uwsgi and WSGI.
uwsgi protocol is a uWSGI server's own protocol. It is used to define the type of information to be transmitted. The first 4 bytes of each uwsgi packet is a description of the type of information to be transmitted. It Compared with WSGI, they are two different things.
Preparation, first, let’s install the packages we need. First of all, this is my newly installed system, so there is no pip, so I will install pip first
sudo apt-get install python-pip

Use the following command to install flask

pip install flask

After installation, we can test it,

import flask

No error is reported, which proves that our flask is installed successfully. So the next thing we have to do is install ngnix and uwsgi.

sudo apt-get install nginx

After installation, we can start it first, nginx start directly starts from the command line, simple and crude

This way we nginx has started successfully. Next, we use pip to install uwsgi

After we install it, let’s start working.

First I create an app under hellowflak Python package,

#app/__init__.pyfrom flask import Flask
app = Flask(__name__)from app import view

Next we create view.py

from app import app
@app.route('/')def index():return 'hellow'

Then we create hello in the same directory as app. py

from app import appif __name__ == "__main__":
    app.run()

, then we can use Python to debug our program locally,

then we can use the browser to Take a look, enter the address and you can get this. From this point of view, there is no problem with our flask program.

Then what we have to do next is to let nginx take on the web service.

What I did here was to delete the nginx configuration file simply and rudely

$ sudo rm /etc/nginx/sites-enabled/default

Next, I created a configuration file under hellowflask

server {
    listen      8081;
    server_name 127.0.0.1;
    charset     utf-8;
    client_max_body_size 75M;

    location / { try_files $uri @app; }
    location @app {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:9000;
    }
}

A brief explanation: server_name can be a domain name or an IP address. uwsgi_pass indicates the communication method between Nginx and uwsgi. What I chose here is the specified port number.

Then let’s soft-connect our configuration to nginx.

sudo ln -s <span class="hljs-regexp"><span class="hljs-regexp">/home/liwanlei/Desktop/hellowflask/<span class="hljs-regexp">helloflask_nginx.conf /etc<span class="hljs-regexp">/nginx/conf.d/<br/>这样我们再去启动我们的nginx,</span></span></span></span>
sudo /etc/init.d/nginx restart

What’s here is not a welcome, but a 502 error, because our current uwsgi file has not been configured yet, and we have not started uwsgi, so the next step is to get it out For this uwsgi, the example below is my configuration.

[uwsgi]    
    base = /home/liwanlei/Desktop/hellowflask
    app = hello#module = %(app)pidfile = /var/run/uwsgi.pid
    master = true
    wsgi-file = /home/liwanlei/Desktop/hellowflask/hello.py
    pythonpath = /usr/bin/python
    chdir = /home/liwanlei/Desktop/hellowflask
    socket = 127.0.0.1:9000callable = app
    logto = %n.log
    plugins = python
    processes = 8master = true

At this time our uwsgi has been configured, so let’s start it,

sudo /usr/bin/uwsgi --ini/home/liwanlei/Desktop/hellowflask/helloflask_uwsgi.ini

我们去重新启动我们的nginx,

sudo nginx <span class="hljs-_">reload<br/>平滑重启可以用用,重新加载配置文件,用新的工作进程代替旧的工作进程。<br/></span>
sudo nginx -s reload
<span class="hljs-_"><br/>启动后,我这里修改了地址,这里就可以直接访问了,那么我们的部署这样就算可以了,简单的。<br/><img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/000/001/25f4d9be3a729ae5fc17c2fefb915c9c-3.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt=""/></span>
 <br>

完工之后,感觉还是很简单的 有问题那么就去看log,只要log配置得当,那么排除错误是很快的。

The above is the detailed content of Detailed introduction to deployment in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool