1.web服務基本流程
1)client
首先客戶端請求服務資源广料,
2)nginx
nginx作為直接對外的服務接口,接收到客戶端發(fā)送過來的http請求,會解包、分析屹培,
如果是靜態(tài)文件請求就根據(jù)nginx配置的靜態(tài)文件目錄迂苛,返回請求的資源禁悠,
如果是動態(tài)的請求,nginx就通過配置文件,將請求傳遞給uWSGI欧啤;
3)uWSGI
uWSGI 將接收到的包進行處理睛藻,并轉發(fā)給wsgi,
4)wsgi
wsgi根據(jù)請求調用django, flask工程的某個文件或函數(shù)邢隧,
5)web application
處理完后django,flask將返回值交給wsgi店印,
6)wsgi
wsgi將返回值進行打包,轉發(fā)給uWSGI倒慧,
7)uWSGI
uWSGI接收后轉發(fā)給nginx,
8)nginx
nginx最終將返回值返回給客戶端(如瀏覽器)按摘。
2.nginx配制
- flask_nginx.conf
- sudo ln -s /home/wyz/flask_nginx.conf /etc/nginx/conf.d/
- service nginx start/stop/restart
- ps -ef | grep nginx
server {
listen 80; //默認的web訪問端口
server_name xxxxxx; //服務器名
#charset koi8-r;
access_log /home/wyz/flask/logs/access.log; //服務器接收的請求日志,logs目錄若不存在需要創(chuàng)建纫谅,否則nginx報錯
error_log /home/wyz/flask/logs/error.log; //錯誤日志
location / {
include uwsgi_params; //這里是導入的uwsgi配置
uwsgi_pass 127.0.0.1:5051; //需要和uwsgi的配置文件里socket項的地址
//相同,否則無法讓uwsgi接收到請求炫贤。
uwsgi_param UWSGI_CHDIR /home/wyz/flask; //項目根目錄
uwsgi_param UWSGI_PYTHON /home/wyz/flask/env36 //python虛擬環(huán)境
uwsgi_param UWSGI_SCRIPT manage:app; //啟動項目的主程序(在本地上運行
//這個主程序可以在flask內置的
//服務器上訪問你的項目)
}
}
3.uWSGI配制
- flask_uwsgi.ini
- uwsgi --ini /home/wyz/flask/flask_uwsgi.ini
- ps -ef | grep uwsgi
[uwsgi]
socket = 127.0.0.1:5051
#http = 127.0.0.1:5051
pythonpath = /home/wyz/flask
module = manage
wsgi-file = /home/wyz/flask/manage.py
callable = app
master = true
processes = 4
#threads = 2
daemonize = /home/wyz/flask/server.log
4.flask web應用
實現(xiàn)接收上傳文件,并存放在upload目錄下
from werkzeug.utils import secure_filename
from flask import Flask,render_template,jsonify,request
import time
import os
import base64
app = Flask(__name__)
UPLOAD_FOLDER='upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['txt','png','jpg','xls','JPG','PNG','xlsx','gif','GIF'])
# 用于判斷文件后綴
def allowed_file(filename):
return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
# 用于測試上傳付秕,稍后用到
@app.route('/test/upload')
def upload_test():
return render_template('upload.html')
# 上傳文件
@app.route('/api/upload',methods=['POST'],strict_slashes=False)
def api_upload():
file_dir=os.path.join(basedir,app.config['UPLOAD_FOLDER'])
if not os.path.exists(file_dir):
os.makedirs(file_dir)
f=request.files['myfile'] # 從表單的file字段獲取文件兰珍,myfile為該表單的name值
if f and allowed_file(f.filename): # 判斷是否是允許上傳的文件類型
fname=secure_filename(f.filename)
print fname
ext = fname.rsplit('.',1)[1] # 獲取文件后綴
unix_time = int(time.time())
new_filename=str(unix_time)+'.'+ext # 修改了上傳的文件名
f.save(os.path.join(file_dir,new_filename)) #保存文件到upload目錄
token = base64.b64encode(new_filename)
print token
return jsonify({"errno":0,"errmsg":"上傳成功","token":token})
else:
return jsonify({"errno":1001,"errmsg":"上傳失敗"})
if __name__ == '__main__':
app.run(debug=True)