Python:Django+uWSGI+Nginx项目学习小结

Python:Django+uWSGI+Nginx项目学习小结

去年学习的,记录一下!

一、项目环境

主机服务器: 阿里云ECS云服务器

操作系统: CentOS Linux release 8.3.2011 || Ubuntu 20.04 || Ubuntu 16.04

编程语言: Python 3.8.3

Web 框架: Django 3.2.3

Web 服务器: uWSGI 2.0.19.1

Web 服务器: Nginx 1.14.1

数据库服务器: MariaDB 10.3.28

二、项目框架

在这里插入图片描述

(上图双箭头应是uwsgi协议)

为了与其他项目环境分离,最好安装虚拟环境配置virtualenv

#Ubuntu update
sudo apt update && sudo apt full-upgrade
#下载解压Python
sudo wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz
sudo tar zxvf Python-3.9.7.tgz
#安装依赖
sudo apt install build-essential  zlib1g-dev  libffi-dev libssl-dev libncurses5-dev libsqlite3-dev  libreadline-dev libtk8.6  libgdm-dev libdb4o-cil-dev libpcap-dev -y
#测试配置
cd Python-3.9.6
./configure
./configure --enable-optimizations
#开始编译
make
#正式安装
sudo make install
#指定清华源下载pip的包
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple virtualenv
#升级pip工具
pip3 install --upgrade pip
#查看版本
pip3 -V
  1. 安装virtualenv
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple virtualenv
  1. 创建目录
mkdir Myproject
cd Myproject
  1. 创建独立运行环境-命名
virtualenv --no-site-packages --python=python3  venv
#报错就试下面
virtualenv -p python3 --system-site-packages venv
#得到独立第三方包的环境,并且指定解释器是python3
  1. 进入虚拟环境
source venv/bin/activate#此时进入虚拟环境(venv)Myproject
  1. 安装第三方包
(venv)Myproject: pip3 install django==3.2.6
#此时pip的包都会安装到venv环境下,venv是针对Myproject创建的
  1. 退出venv环境
deactivate
  1. virtualenv是如何创建“独立”的Python运行环境的呢?

原理很简单,就是把系统Python复制一份到virtualenv的环境,用命令source venv/bin/activate进入一个virtualenv环境时,virtualenv会修改相关环境变量,让命令python和pip均指向当前的virtualenv环境。

  1. 确保开发环境的一致性
    1.假设我们在本地开发环境,准备好了项目+依赖包环境
    2.现在需要将项目上传至服务器,上线发布
    3.那么就要保证服务器的python环境一致性

解决方案:
(1). 通过命令保证环境的一致性,导出当前python环境的包

pip3 freeze > requirements.txt 

这将会创建一个 requirements.txt 文件,其中包含了当前环境中所有包及 各自的版本的简单列表。
可以使用 “pip list”在不产生requirements文件的情况下, 查看已安装包的列表。

(2). 上传至服务器后,在服务器下创建virtualenv,在venv中导入项目所需的模块依赖

pip3 install -r requirements.txt
  1. 安装有jupyter的环境下调用下面的命令,使得jupyter中可以调用虚拟环境。
    其他地方不变,最后一个单词换成你的虚拟环境的名字。
python -m ipykernel install --user --name venv_name

三、Django

# 创建一个Django项目,名为SpiderWebsite
django-admin startproject SpiderWebject
# 进入SpiderWebsite工程文件夹下
cd SpiderWebject/
# 创建项目中的static目录:
mkdir static
# 启动Django项目
python3 manage.py runserver 0.0.0.0:8000
# 选择一个浏览器输入:http://115.159.214.215:8000/
# 注意:IP地址换成自己的主机IP

# 创建一个名为demo的程序
python3 manage.py startapp demo
# models建表命令(做项目时使用,此时该步骤忽略)
python3 manage.py makemigrations
python3 manage.py migrate
# 创建templates文件夹,用于存放html文件
cd demo
mkdir templates

Django框架 WHY ?
封装----大量的功能封装
简化----把相对复杂的功能进行封装后做到简化
优化----直白的说是大咖帮你把很多py代码优化了提升效率漏洞----弥补了已知的网站传输漏洞,比如sql注入
管理----框架以模块划分,负责不同的功能,清晰易于管理

启动

nohup python manage.py runserver 0.0.0.0:8000
# ctrl+c 可退出runserver

关闭

方法一:在当前终端下,ctrl+c 可退出runserver

方法二:在其他终端下,查找进程:根据django端口号查找进程

lsof -i tcp:8000

img

关闭进程:根据pid强制关闭进程

Kill -9 pid

安装uwsgi

sudo pip3 install uwsgi==2.0.18 -i https://pypi.tuna.tsinghua.edu.cn/simple/

阿里云:http://mirrors.cloud.aliyuncs.com/pypi/simple/

四、安装uwsgi报错

windows 不支持uWSGI

ERROR: Command errored out with exit status 1: /root/python_project/SpiderWebsite/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-lc8ejazx/uwsgi_474007c2381a4cb786efcd1e9a57796b/setup.py'"'"'; __file__='"'"'/tmp/pip-install-lc8ejazx/uwsgi_474007c2381a4cb786efcd1e9a57796b/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-l34b3299/install-record.txt --single-version-externally-managed --compile --install-headers /root/python_project/SpiderWebsite/venv/include/site/python3.8/uwsgi Check the logs for full command output.
# 如果处于虚拟环境中(venv),则先退出虚拟环境
(venv) [root@CentOS8 SpiderWebsite]# deactivate 
# 检查本机环境中是否安装了相关依赖python3-devel,没有则安装,执行如下命令
# 另外,注意python3-devel的版本,
# python3-devel>>这是python3.6 | python38-devel>>这是python3.8,
[root@CentOS8 SpiderWebsite]# yum install python3-devel
Last metadata expiration check: 2:47:28 ago on Sat 22 May 2021 02:22:53 PM CST.
Package python36-devel-3.6.8-2.module_el8.3.0+562+e162826a.x86_64 is already installed.
Dependencies resolved.
Nothing to do.
Complete!
# 在本机中安装uwsgi
[root@CentOS8 SpiderWebsite]# pip3 install uwsgi==2.0.19
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting uwsgi==2.0.19
  Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/6f/e9/729f0eb15f4847c729c1a841bcbb5e327d08d208de0cbe661224955c9297/uWSGI-2.0.19.tar.gz (804kB)
    100% |████████████████████████████████| 808kB 35.0MB/s 
Installing collected packages: uwsgi
  Running setup.py install for uwsgi ... done
Successfully installed uwsgi-2.0.19
[root@CentOS8 SpiderWebsite]# ls
requirements.txt  SpiderWebject  venv
# 重新创建虚拟环境
[root@CentOS8 SpiderWebsite]# virtualenv  --python=python38  venv
created virtual environment CPython3.6.8.final.0-64 in 321ms
  creator CPython3Posix(dest=/root/python_project/SpiderWebsite/venv, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
    added seed packages: pip==21.1.1, setuptools==56.0.0, wheel==0.36.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
[root@CentOS8 SpiderWebsite]# ls
requirements.txt  SpiderWebject  venv
[root@CentOS8 venv]# cd venv/bin/
[root@CentOS8 bin]# ls
activate       activate_this.py  flask    pip3.6       python     sqlformat  wheel3.6
activate.csh   activate.xsh      pip      pip-3.8      python3    wheel      wheel-3.8
activate.fish  django-admin      pip3     pip3.8       python3.6  wheel3     wheel3.8
activate.ps1   django-admin.py   pip-3.6  __pycache__  python3.8  wheel-3.6
# 启动虚拟环境
[root@CentOS8 bin]# source activate
(venv) [root@CentOS8 bin]# cd ..
(venv) [root@CentOS8 venv]# cd ..
(venv) [root@CentOS8 SpiderWebsite]# ls
requirements.txt  SpiderWebject  venv
(venv) [root@CentOS8 SpiderWebsite]# cd SpiderWebject/
(venv) [root@CentOS8 SpiderWebject]# ls
db.sqlite3  demo  manage.py  SpiderWebject
# 检查虚拟环境中是否安装了uwsgi,有的话命令行会显示,我的没有显示,则在虚拟环境中再安装一遍
(venv) [root@CentOS8 SpiderWebject]# pip3 freeze|grep -i 'uwsgi'
(venv) [root@CentOS8 SpiderWebject]# pip3 install uwsgi==2.0.19
Looking in indexes: http://mirrors.cloud.aliyuncs.com/pypi/simple/
Collecting uwsgi==2.0.19
  Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/6f/e9/729f0eb15f4847c729c1a841bcbb5e327d08d208de0cbe661224955c9297/uWSGI-2.0.19.tar.gz (804 kB)
     |████████████████████████████████| 804 kB 13.5 MB/s 
Building wheels for collected packages: uwsgi
  Building wheel for uwsgi (setup.py) ... done
  Created wheel for uwsgi: filename=uWSGI-2.0.19-cp36-cp36m-linux_x86_64.whl size=510064 sha256=8485df888626d01d816cbbba0e15a60e1534c78675281414f2cbddb6e9d97a8a
  Stored in directory: /root/.cache/pip/wheels/12/e6/4b/f94f542464364699fb13f91b0df9b4dae45058e205d50f8832
Successfully built uwsgi
Installing collected packages: uwsgi
Successfully installed uwsgi-2.0.19
(venv) [root@CentOS8 SpiderWebject]# 
# 经过以上就成功了

新建uwsgi.ini文件

[uwsgi]
  
socket          = 127.0.0.1:8000 # 套接字方式的IP地址:端口号【此模式需要有nginx】
chdir           = /home/keen/python_project/SpiderWebsite  指定运行目录
wsgi-file       = SpiderWebsite/wsgi.py  载入 wsgi-file
master          = true  允许主进程存在,开起主进程管理模式
processes       = 2  开启的进程数量
threads         = 2  运行线程
vacuum          = true  当服务器退出的时候自动清理环境,删除 unix socket 文件和 pid 文件
pidfile         = uwsgi.pid   指定pid文件的位置,记录主进程的pid号。
daemonize       = uwsgi.log  使进程在后台运行,并将日志打到指定的日志文件或者 udp 服务器(daemonize uWSGI)。实际上最常用的,还是把运行记录输出到一个本地文件上。

启动uwsgi

# 启动uwsgi
(venv) [root@CentOS8 SpiderWebject]# uwsgi --ini uwsgi.ini
[uWSGI] getting INI configuration from uwsgi.ini
# 查看是否启动
(venv) [root@CentOS8 SpiderWebject]# ps aux|grep 'uwsgi'
root       38523  0.0  0.3 145944 12312 ?        Sl   19:46   0:00 uwsgi --ini uwsgi.ini
root       38524  0.0  0.1  59296  6616 ?        S    19:46   0:00 uwsgi --ini uwsgi.ini
root       38527  0.0  0.0  12112   972 pts/0    S+   19:46   0:00 grep --color=auto uwsgi
# 查看目录,多了uwsgi.log(日志文件)和uwsgi.pid
(venv) [root@CentOS8 SpiderWebject]# ls
asgi.py      __pycache__  urls.py    uwsgi.log  wsgi.py
__init__.py  settings.py  uwsgi.ini  uwsgi.pid
# 关闭uwsgi
(venv) [root@CentOS8 SpiderWebject]# uwsgi --stop uwsgi.pid
(venv) [root@CentOS8 SpiderWebject]# ps aux|grep 'uwsgi'
root       38532  0.0  0.0  12112  1096 pts/0    S+   19:48   0:00 grep --color=auto uwsgi
(venv) [root@CentOS8 SpiderWebject]# 

uWSGl常见问题汇总

1,启动失败:端口被占用
原因:有其他进程占用uwSGI启动的端口;
解决方案:可执行sudo lsof -i:端口号 查询出具体进程;杀掉进城后,重新启动uwSGI即可
2,停止失败: stop无法关闭uWSGl
原因:重复启动uwSGI,导致pid文件中的进程号失准
解决方案:ps出uWSGI进程,手动kill掉

五、Nginx

sudo /etc/init.d/nginx start | stop | restart | status
#或
sudo service nginx start | stop| restart | status 
#启动– 
sudo /etc/init.d/nginx start
#停止- 
sudo /etc/init.d/nginx stop
#重启- 
sudo /etc/init.d/nginx restart
# 检查配置语法是否有问题
sudo nginx -t

注意: nginx配置只要修改,就需要进行重启,否则配置不生效

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

我们需要进入 /etc/nginx/sites-available 目录下进行配置 default 文件(有些 Linux 发行版的配置文件是在 /etc/nginx/nginx.conf 下(如下图的Centos系统),还有一些在其他地方,这里我们以 Ubuntu 16.04 为准)。
在这里插入图片描述
在这里插入图片描述

  1. 配置 Nginx

Nginx 默认的配置文件都在 /etc/nginx 目录下

setup@labideas-data:/etc/nginx$ ll
total 64
drwxr-xr-x  6 root root 4096 Mar 20 09:37 ./
drwxr-xr-x 95 root root 4096 Mar 19 19:56 ../
drwxr-xr-x  2 root root 4096 Mar 19 20:13 conf.d/
-rw-r--r--  1 root root 1077 Feb 12  2017 fastcgi.conf
-rw-r--r--  1 root root 1007 Feb 12  2017 fastcgi_params
-rw-r--r--  1 root root 2837 Feb 12  2017 koi-utf
-rw-r--r--  1 root root 2223 Feb 12  2017 koi-win
-rw-r--r--  1 root root 3957 Feb 12  2017 mime.types
-rw-r--r--  1 root root 1919 Mar 20 09:33 nginx.conf
-rw-r--r--  1 root root  180 Feb 12  2017 proxy_params
-rw-r--r--  1 root root  636 Feb 12  2017 scgi_params
drwxr-xr-x  2 root root 4096 Mar 20 10:00 sites-available/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 sites-enabled/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 snippets/
-rw-r--r--  1 root root  664 Feb 12  2017 uwsgi_params
-rw-r--r--  1 root root 3071 Feb 12  2017 win-utf

·修改nginx的配置文件/etc/nginx/sites-enabled/default;sudo vim该文件
#在server节点下添加新的location项,指向uwsgi的ip与端口。(系统Ubuntu 20.04)

# /etc/nginx/sites-enabled/default 系统Ubuntu 20.04
server {
	location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        # try_files $uri $uri/ =404;
		uwsgi_pass 127.0.0.1:8000; # 重定向到127.0.0.1的8000端口
		include /etc/nginx/uwsgi_params ; # 将所有的参数转到uwsgi下
	}
    ...
}

将原有配置文件进行备份,并打开 nginx 配置文件

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
sudo vi /etc/nginx/sites-available/default

将默认的 80 端口号改成其它端口号,如 8080。因为默认的 80 端口号很容易被其它应用程序占用,而且我们配置我们自己的 Django 项目也需要用到默认端口。

internal server error

*** Starting uWSGI 2.0.19.1 (64bit) on [Sun May 23 19:56:43 2021] ***
compiled with version: 8.3.1 20191121 (Red Hat 8.3.1-5) on 23 May 2021 08:21:08
os: Linux-4.18.0-147.5.1.el8_1.x86_64 #1 SMP Wed Feb 5 02:00:39 UTC 2020
nodename: CentOS8
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 2
current working directory: /home/keen/python_project/SpiderWebsite
writing pidfile to uwsgi.pid
detected binary path: /home/keen/python_project/spider_website_venv/bin/uwsgi
chdir() to /home/keen/python_project/SpiderWebsite
your processes number limit is 15002
your memory page size is 4096 bytes
detected max file descriptor number: 65535
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8000 fd 6
uwsgi socket 0 bound to TCP address 127.0.0.1:40565 (port auto-assigned) fd 5
Python version: 3.8.3 (default, Aug 31 2020, 16:03:14)  [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]
Python main interpreter initialized at 0x2368080
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 250128 bytes (244 KB) for 4 cores
*** Operational MODE: preforking+threaded ***
# !!!!注意下面两行信息
failed to open python file SpiderWebsite.wsgi
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 48903)
spawned uWSGI worker 1 (pid: 48904, cores: 2)
spawned uWSGI worker 2 (pid: 48905, cores: 2)
spawned uWSGI http 1 (pid: 48906)
--- no python application found, check your startup logs for errors ---
[pid: 48904|app: -1|req: -1/1] 180.136.88.169 () {38 vars in 763 bytes} [Sun May 23 19:57:00 2021] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)

排查问题宗旨->看日志!看日志!!看日志!!!

nginx日志位置:
异常信息/var/log/nginx/error.log
正常访问信息/var/log/nginx/access.log
uwsgi日志位置:
项目同名目录下, uwsgi.log

六、正式项目中静态文件

静态文件配置步骤

1,创建新路径-主要存放Django所有静态文件如:/home/tarena/项目名_static

在Django settings.py中添加新配置

# Django settings.py
STATIC_ROOT = '/home/tarena/项目名_static/static' # 注意此配置路径为存放所有正式环境中需要的静态文件

3,进入项目,执行python3 manage.py collectstatic执行该命令后
Django将项目重所有静态文件复制到STATIC_ROOT中,包括Django内建的静态文件

Nginx配置中添加新配置

# file : /etc/nginx/sites-enabled/default
#新添加location /static路由配置,重定向到指定的第一步创建的路径即可
server {
	location /static {
		#root第一步创建文件夹的绝对路径,如:
        root /home/tarena/项目名_static;
	}
}

七、数据库

create database database_name default charset utf8

八、Admin配置步骤

创建后台管理帐号 – 该账号为管理后台最高权限账号

python3 manage.py createsuperuser

九、django 项目迁移

sudo scp /home/user/djangoproject root@88.77.66.55:/home/user/xxx

3.用uWSGI替代python3 manage.py runserver方法启动服务器

4.配置nginx反向代理服务器

5.用nginx配置静态文件路径,解决静态路径问题

特殊说明: Django 的settings.py需要做如下配置

1,修改settings.py将 DEBUG=True改为DEBUG=False

2,修改settings.py将ALLOWED_HOSTS =改为
ALLOWED_HOSTS =['网站域名]或者[‘服务监听的ip地址’]

十、项目组成员角色

产品/运营经理:负责产品功能细节的把控

开发:

  • 前端:负责显示部分内容的开发
  • 后端:负责服务器部分的功能开发

运维:管理 Linux 服务器,组件化配置,安全问题

测试:负责找出产品功能的问题BUG

美术:负责产品素材方面得绘制

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值