跟老刘学python

新猿教育老刘带你学习python,学完即可就业。

新猿0基础python教程 uwsgi启动Python的Web项目中不要使用全局变量

# 一 使用uwsgi部署python的web项目

```python

一般在部署Django或者Flask时,我们为了利用多核优势,一般使用uwsgi部署,原理如下

如果我们设定uwsgi进程数为3,那么操作系统是开启3个进程来运行python的web程序

如果我们在web项目中使用全局变量,由于多进程间数据是隔离的,所以定义的全局变量,分别在3个进程中

```

# 二 测试

## 2.1 写一个flask程序(s1.py)

```python

from flask import Flask

import time

app = Flask(__name__)

count = 0

@app.route('/')

def hello_world():

    global count

    count+=1

    return 'Hello World!'+str(count)

if __name__ == '__main__':

    app.run(host='0.0.0.0')

```

## 2.2 编写uwsgi的配置文件 (uwsgi.ini)

```python

[uwsgi]

http = 0.0.0.0:5000

chdir = /root/

wsgi-file = /root/s1.py

processes = 1

threads = 2

buffer-size = 32768

master = true

pidfile = uwsgi.pid

daemonize = uwsgi.log

callable = app

# uwsgi uwsgi.ini  使用一个进程启动uwsgi

```

## 2.2 自己机器压测代码

```python

import requests

from threading import Thread

import time

def task():

    res=requests.get('https://101.133.225.166:5000/')

    print(res.text)

if __name__ == '__main__':

    for i in range(1000):

        t=Thread(target=task)

        t.start()

        # time.sleep(0.9)


 # 如果使用1个进程启动uwsgi,可以看到返回的数据中不会有重复的数字

# 但如果使用多个进程启动uwsgi,可以看到返回的数据中会有重复的数据,由于不同的进程中同一个变量不共享

# 如果使用python s1.py 就是一个进程运行,也不会有重复的数据

```


评论