APP逻辑代码
Flask逻辑代码
from flask import Flask, request
app = Flask(__name__)
@app.route('/imageretrieval', methods=['GET', 'POST'])
def test():
return 'hello'
if __name__ == "__main__":
app.run()
Django逻辑代码
urls.py
from . import index
urlpatterns = [
path('notify/<str:rlist>/', index.index),
]
settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = ['gunicorn']
index.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request, rlist=None):
result = notify_img.notify_msg(str(request.body, encoding='utf-8'), rlist)
return HttpResponse(json.dumps(result))
Nginx+Gunicorn/uWSGI+Django/Flask搭建
1. 说明
Gunicorn是使用Python实现的WSGI服务器, 直接提供了http服务, 在多worker最大化里用CPU的同时, 还可以使用协程来提供并发支撑, 对于网络IO密集的服务比较有利。工作进程类型包括 sync(默认), eventlet, gevent, or tornado, gthread, gaiohttp,默认自带sync效率很低,gevent/eventlet方式效果最好。
uWSGI是使用C写的, 它的socket fd创建, worker进程的启动都是使用C语言系统接口来实现的。
一般我们会在Gunicorn/uWSGI前面再加一层Nginx, 这样做的原因有一下几点:
- 做负载均衡
- 静态文件服务器
- 更安全
- 扛并发
2. Gunicorn
2.1 Gunicorn安装
pip install gunicorn -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install gevent -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install eventlet -i https://pypi.tuna.tsinghua.edu.cn/simple/
2.2 gunicorn+django使用
- django配置
settings.py+INSTALLED_APPS=>gunicorn
- 启动(自动重载)
kill $( lsof -i:8881 -t )
gunicorn xxx.wsgi -b 0.0.0.0:8881 -w 2 --timeout 30 --access-logfile log_access.log --log-file log_err.log -k gevent --reload --daemon --capture-output
2.3 gunicorn+flask使用
- 启动(自动重载)
kill $( lsof -i:8880 -t )
gunicorn xxx:app -b 0.0.0.0:8880 -w 2 --access-logfile log_access.log --log-file log_err.log -k gevent --reload --daemon --capture-output
3. uWSGI
- 安装
conda install -c conda-forge uwsgi
- 启动
uwsgi --http :8880 --wsgi-file run_web.py --callable app --processes 10 --threads 100 --stats 8880.status --pidfile 8880.pid --daemonize 8880.log
4.Nginx
- 方式一:直接安装
apt install nginx
- 方式二:下载安装Nginx(源码编译方式)
export PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin
sudo apt-get install libpcre3 libpcre3-dev
wget http://nginx.org/download/nginx-1.16.1.tar.gz
tar xvf nginx-1.16.1.tar.gz
./configure --prefix=/home/xxx/soft/nginx --sbin-path=/home/xxx/soft/nginx/nginx --conf-path=/home/xxx/soft/nginx/conf/nginx.conf --error-log-path=/home/xxx/soft/nginx/error.log --http-log-path=/home/xxx/soft/nginx/access.log --pid-path=/home/xxx/soft/nginx/nginx.pid --lock-path=/home/xxx/soft/nginx/nginx.lock --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre
make
make install
- 服务启动和停止
nginx 启动服务
nginx -s reload 不停止服务重读配置文件
nginx -s stop 停止服务
- 配置
- 源码安装:conf/nginx.conf
- 直接安装:/etc/nginx/conf.d/default.conf
server {
listen 8882;
# 静态文件
location /aida {
alias /home/xxx/data/yyy;
}
# 重定向
location / {
proxy_pass http://127.0.0.1:8881;
}
}
- Log地址
- 源码安装: log_access.log log_err.log
- 直接安装: /var/log/nginx/access.log /var/log/nginx/error.log