安装flask及环境
1.使用虚拟环境
mkdir transfer
cd transfer
python3 -m venv .venv
激活虚拟环境
. .venv/bin/activate
在虚拟环境中安装
pip install Flask
pip install requests
pip install pyuwsgi
2.代码描述,接受一个请求,然后将请求的内容转发到另一个地址上,并返回相应结果。vim transfer.py
from flask import Flask, request
import requests
app = Flask(__name__)
@app.route('/transfer', methods=['GET', 'POST'])
def transfer():
data = request.get_json()
method = data.get('method')
url = data.get('url')
headers = data.get('headers')
postdata = data.get('postdata')
response = requests.request(method=method, url=url, headers=headers, data=postdata)
return response.content
@app.route('/', methods=['GET', 'POST'])
def index():
return 'hello world'
if __name__ == '__main__':
app.run()
3.测试运行
export FLASK_APP=transfer #文件名称,如果文件名为 app.py 或者 wsgi.py ,那么不需要设置 FLASK_APP 环境变量
flask run
4.uwsgi启动
创建wsgi.py
from transfer import app as application
启动uwsgi
#前台运行
uwsgi -s :8801 -b 8192 --master -p 1 --threads 2 --virtualenv /home/ubuntu/www/transfer/.venv --wsgi-file wsgi.py
#后台运行
uwsgi -s :8801 -b 8192 --master -p 1 --threads 2 --virtualenv /home/ubuntu/www/transfer/.venv --wsgi-file wsgi.py --daemonize /dev/null
也可以将启动命令放入脚本中,方便使用
PORT=8801 #
PROCESS=1
THREADS=2
FILEPATH=$(cd "$(dirname "$0")"; pwd)
UWSGI_FILE=$FILEPATH/wsgi.py
PIDS=`ps -ef |grep $UWSGI_FILE |grep -v grep | awk '{print $2}'`
if [ ! $1 ] || [ "$1" == 'false' ]; then
if [ "$PIDS" != "" ]; then
kill -7 $PIDS
echo 'kill process...'
else
if [ "$1" == 'false' ];then
uwsgi -s :$PORT -b 8192 --master -p $PROCESS --threads $THREADS --virtualenv $FILEPATH/.venv --wsgi-file $UWSGI_FILE
else
uwsgi -s :$PORT -b 8192 --master -p $PROCESS --threads $THREADS --virtualenv $FILEPATH/.venv --wsgi-file $UWSGI_FILE --daemonize /dev/null
echo 'start success'
fi
fi
fi
5.nginx配置
server {
listen 80;
server_name test.com;
location / {
uwsgi_pass 127.0.0.1:8801;
uwsgi_read_timeout 120s;
include uwsgi_params;
}
}
6.重启nginx
service nginx reload