初識flask,上傳檔案,uwsgi部署
阿新 • • 發佈:2018-12-07
安裝:
pip install flask
web開發:
app.py
from flask import Flask,request,make_response
from flask import jsonify
app = Flask(__name__)
UPLOAD_FOLDER = 'temp' # 檔案下載路徑
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
#hello world
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
#上傳檔案
@app.route('/upload_file', methods=['POST'])
def ucf101():
files = request.files.getlist("file")
if files:
try:
for file in files:
filename = secure_filename(file.filename) # 使用secure_filename()讓檔名變得安全
tmp_file = os.path.join(UPLOAD_FOLDER, filename)
file.save(tmp_file)
res = jsonify({"status": "success", "message": "上傳成功"})
return make_response(res, 200)
except Exception as e:
res = jsonify({"status": "error", "error": e})
return make_response(res, 200)
else:
res = jsonify({"status": "error", "error": "NO FILE"})
return make_response(res, 200)
if __name__ == '__main__':
app.run(host="172.xxx.xxx.xx", port=5000, debug=True)
執行測試
python app.py
uwsgi部署:
uwsgi.ini
[uwsgi]
http=172.xxx.xxx.xxx:5000
#pythonpath :專案目錄
pythonpath=/home/hayley/flask
#callable:具體執行.run方法的那個實體的名字
callable=app
wsgi-file = /home/hayley/flask/app.py
#processes:伺服器開啟的並行程序個數
processes=1
#threads:每個程序等待處理請求的執行緒個數
threads=4
#daemonize :日誌檔案
daemonize = /home/hayley/flask/conf/uwsgi.log
linux命令:
#開始執行:
uwsgi uwsgi.ini
#停止uwsgi:
pkill -f -9 uwsgi