Python web学习:Django + uWSGI + Nginx

2024-04-25 03:48

本文主要是介绍Python web学习:Django + uWSGI + Nginx,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、背景

由于工作需要,最近学习了下Python web的开发,现在做一个简要总结。
选用的Python web架构如下:
Python web框架:Django
应用服务器: uWSGI
代理服务器:Nginx
其中Django是最为常用的Python web框架,类似的框架还有:Flask、web2py等。

二、Django

安装Django可在网上搜索资料。

django-admin

安装完Django后,运行django-admin,得到如下结果:
在这里插入图片描述

创建Python web工程

运行如下命令django-admin startproject HelloWorld,可创建名为HelloWorld的Python web工程,目录结构如下:
在这里插入图片描述

目录说明:
  • HelloWorld: 项目的根目录。
  • manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互,例如通过命令行启动该web项目,通过pycharm启动该web项目等。
  • HelloWorld/init.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
  • HelloWorld/settings.py: 该 Django 项目的设置/配置。
  • HelloWorld/urls.py: 该 Django 项目的 URL 声明; 该web项目提供的所有接口均在这里配置。
  • HelloWorld/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
web项目启动

命令行窗口下执行如下命令:

python manage.py runserver 0.0.0.0:8000

0.0.0.0 让其它电脑可连接到开发服务器,8000 为端口号。如果不说明,那么端口号默认为 8000。

在这里插入图片描述
打开浏览器,输入http://localhost:8000/查看效果:
在这里插入图片描述

三、uWSGI

uWSGI是一个应用服务器,可以理解为地位和Tomcat类似,一般和Nginx配合使用,以提供HTTP服务。

uWSGI使用示例
The first WSGI application

Let’s start with a simple “Hello World” example:

def application(env, start_response):start_response('200 OK', [('Content-Type','text/html')])return [b"Hello World"]

(save it as foobar.py).

As you can see, it is composed of a single Python function. It is called “application” as this is the default function that the uWSGI Python loader will search for (but you can obviously customize it).

Deploy it on HTTP port 9090

Now start uWSGI to run an HTTP server/router passing requests to your WSGI application:

uwsgi --http :9090 --wsgi-file foobar.py

打开浏览器输入http://localhost:9090/,结果如下
在这里插入图片描述

Adding concurrency and monitoring

The first tuning you would like to make is adding concurrency (by default uWSGI starts with a single process and a single thread).

You can add more processes with the --processes option or more threads with the --threads option (or you can have both).

uwsgi --http :9090 --wsgi-file foobar.py --master --processes 4 --threads 2

This will spawn 4 processes (each with 2 threads), a master process (will respawn your processes when they die) and the HTTP router (seen before).

uWSGI配置

仍以上面的配置为例:

uwsgi --http :9090 --wsgi-file foobar.py --master --processes 4 --threads 2

Argh! What the hell is this?! dealing with such long command lines is unpractical, foolish and error-prone. Never fear! uWSGI supports various configuration styles. In this quickstart we will use .ini files.

[uwsgi]
socket = 127.0.0.1:3031
chdir = /home/foobar/myproject/
wsgi-file = myproject/wsgi.py
processes = 4
threads = 2
stats = 127.0.0.1:9191
A lot better!

Just run it:

uwsgi yourfile.ini

在浏览器中访问,仍可得到正确结果。

uWSGI详细资料详见本文末尾中的资料链接。

四、Nginx

配置基本和Java web中的Nginx的配置相同,配置文件如下:


# proxy conf
user                        admin;worker_rlimit_nofile        100000;error_log                   "/data/logs/error_log" warn;
pid                         /home/admin/logs/tengine.pid;events {use                     epoll;worker_connections      20480;
}http {include                 mime.types;default_type            application/octet-stream;root                    /home/admin/htdocs;sendfile                on;tcp_nopush              on;server_tokens           off;keepalive_timeout       0;client_header_timeout   1m;send_timeout            1m;client_max_body_size    3m;error_page              506 http://your_error_page.html;index                   index.html index.htm;log_format              proxyformat    "$remote_addr $request_time_usec $http_x_readtime [$time_local] \"$request_method http://$host$request_uri\" $status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$md5_encode_cookie_unb\" \"$md5_encode_$cookie_cookie2\" ";access_log              "/data/logs/access_log" proxyformat;log_not_found           off;gzip                    on;gzip_http_version       1.0;gzip_comp_level         6;gzip_min_length         1024;gzip_proxied            any;gzip_vary               on;gzip_disable            msie6;gzip_buffers            96 8k;gzip_types              text/xml text/plain text/css application/javascript application/x-javascript application/rss+xml;proxy_set_header        Host $host;proxy_set_header        X-Real-IP $remote_addr;proxy_set_header        Web-Server-Type nginx;proxy_set_header        WL-Proxy-Client-IP $remote_addr;proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;proxy_redirect          off;proxy_buffers           128 8k;proxy_intercept_errors  on;# fight mhtml/utf-7 bughat_content             "\r\n";hat_types               text/html text/css;server {listen              8080;server_name         localhost;location /test/tools {include uwsgi_params;uwsgi_pass 127.0.0.1:8000;chunked_transfer_encoding off;}}
}

其中include uwsgi_params;中的配置如下:

uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  HTTPS              $https if_not_empty;uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

include uwsgi_params的作用如下:
在这里插入图片描述

五、资料

Django
  1. https://docs.djangoproject.com/zh-hans/2.2/
  2. https://www.jianshu.com/p/679dee0a4193
  3. http://www.runoob.com/django/django-first-app.html
uWSGI
  1. https://uwsgi-docs.readthedocs.io/en/latest/
PEP 3333 – Python Web Server Gateway Interface v1.0.1
  1. https://www.python.org/dev/peps/pep-3333/

这篇关于Python web学习:Django + uWSGI + Nginx的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/933622

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

如何用Docker运行Django项目

本章教程,介绍如何用Docker创建一个Django,并运行能够访问。 一、拉取镜像 这里我们使用python3.11版本的docker镜像 docker pull python:3.11 二、运行容器 这里我们将容器内部的8080端口,映射到宿主机的80端口上。 docker run -itd --name python311 -p

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

Java Web指的是什么

Java Web指的是使用Java技术进行Web开发的一种方式。Java在Web开发领域有着广泛的应用,主要通过Java EE(Enterprise Edition)平台来实现。  主要特点和技术包括: 1. Servlets和JSP:     Servlets 是Java编写的服务器端程序,用于处理客户端请求和生成动态网页内容。     JSP(JavaServer Pages)