fix: dev: 优化Flask语法 & 修正Flask找不到templates文件夹的问题
1. 优化Flask语法,使用flask自带的jsonify进行json回复;使用flask自带的render_template进行html模版回复; 简化Flask书写语法 2. 将server文件夹更名flask_templates,在Flask初始化时将模版文件夹路径指向此文件夹
This commit is contained in:
@@ -23,8 +23,8 @@ class Constant(object):
|
|||||||
|
|
||||||
SERVER_LOG_FORMAT = '%(asctime)s - %(pathname)s:%(lineno)d - %(name)s - %(levelname)s - %(message)s'
|
SERVER_LOG_FORMAT = '%(asctime)s - %(pathname)s:%(lineno)d - %(name)s - %(levelname)s - %(message)s'
|
||||||
SERVER_UPLOAD_ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
|
SERVER_UPLOAD_ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
|
||||||
SERVER_PAGE_UPLOAD = 'Server/upload.html'
|
SERVER_PAGE_UPLOAD = 'upload.html'
|
||||||
SERVER_PAGE_INDEX = 'Server/index.html'
|
SERVER_PAGE_INDEX = 'index.html'
|
||||||
|
|
||||||
RUN_RESULT_SUCCESS = '成功 %ds\n'
|
RUN_RESULT_SUCCESS = '成功 %ds\n'
|
||||||
RUN_RESULT_FAIL = '失败\n[*] 退出程序\n'
|
RUN_RESULT_FAIL = '失败\n[*] 退出程序\n'
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from config import ConfigManager
|
|||||||
from config import Constant
|
from config import Constant
|
||||||
from config import Log
|
from config import Log
|
||||||
#---------------------------------------------------
|
#---------------------------------------------------
|
||||||
import flask
|
from flask import Flask, render_template, send_file, jsonify, request
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
import os
|
import os
|
||||||
@@ -32,7 +32,7 @@ wechat.msg_handler = wechat_msg_processor
|
|||||||
wechat_msg_processor.wechat = wechat
|
wechat_msg_processor.wechat = wechat
|
||||||
|
|
||||||
PORT = int(cm.get('setting', 'server_port'))
|
PORT = int(cm.get('setting', 'server_port'))
|
||||||
app = flask.Flask(__name__)
|
app = Flask(__name__, template_folder='flask_templates')
|
||||||
app.config['UPLOAD_FOLDER'] = cm.getpath('uploaddir')
|
app.config['UPLOAD_FOLDER'] = cm.getpath('uploaddir')
|
||||||
|
|
||||||
logger = logging.getLogger('werkzeug')
|
logger = logging.getLogger('werkzeug')
|
||||||
@@ -47,8 +47,7 @@ app.logger.addHandler(flask_log_handler)
|
|||||||
|
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def index():
|
def index():
|
||||||
with open(Constant.SERVER_PAGE_INDEX, 'r') as f:
|
return render_template(Constant.SERVER_PAGE_INDEX)
|
||||||
return f.read()
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/qrcode')
|
@app.route('/qrcode')
|
||||||
@@ -59,7 +58,7 @@ def qrcode():
|
|||||||
image_path = '%s/%s_%d.png' % (qdir, wechat.uuid, int(time.time()*100))
|
image_path = '%s/%s_%d.png' % (qdir, wechat.uuid, int(time.time()*100))
|
||||||
s = wechat.wx_conf['API_qrcode'] + wechat.uuid
|
s = wechat.wx_conf['API_qrcode'] + wechat.uuid
|
||||||
str2qr_image(s, image_path)
|
str2qr_image(s, image_path)
|
||||||
return flask.send_file(image_path, mimetype='image/png')
|
return send_file(image_path, mimetype='image/png')
|
||||||
|
|
||||||
|
|
||||||
@app.route("/group_list")
|
@app.route("/group_list")
|
||||||
@@ -68,8 +67,7 @@ def group_list():
|
|||||||
@brief list groups
|
@brief list groups
|
||||||
"""
|
"""
|
||||||
result = wechat.db.select(Constant.TABLE_GROUP_LIST())
|
result = wechat.db.select(Constant.TABLE_GROUP_LIST())
|
||||||
j = {'count': len(result), 'group': result}
|
return jsonify({'count': len(result), 'group': result})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/group_member_list/<g_id>')
|
@app.route('/group_member_list/<g_id>')
|
||||||
@@ -79,8 +77,7 @@ def group_member_list(g_id):
|
|||||||
@param g_id String
|
@param g_id String
|
||||||
"""
|
"""
|
||||||
result = wechat.db.select(Constant.TABLE_GROUP_USER_LIST(), 'RoomID', g_id)
|
result = wechat.db.select(Constant.TABLE_GROUP_USER_LIST(), 'RoomID', g_id)
|
||||||
j = {'count': len(result), 'member': result}
|
return jsonify({'count': len(result), 'member': result})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/group_chat_log/<g_name>')
|
@app.route('/group_chat_log/<g_name>')
|
||||||
@@ -90,13 +87,12 @@ def group_chat_log(g_name):
|
|||||||
@param g_name String
|
@param g_name String
|
||||||
"""
|
"""
|
||||||
result = wechat.db.select(Constant.TABLE_GROUP_MSG_LOG, 'RoomName', g_name)
|
result = wechat.db.select(Constant.TABLE_GROUP_MSG_LOG, 'RoomName', g_name)
|
||||||
j = {'count': len(result), 'chats': result}
|
return jsonify({'count': len(result), 'chats': result})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/upload', methods=['GET', 'POST'])
|
@app.route('/upload', methods=['GET', 'POST'])
|
||||||
def upload_file():
|
def upload_file():
|
||||||
if flask.request.method == 'POST':
|
if request.method == 'POST':
|
||||||
def allowed_file(filename):
|
def allowed_file(filename):
|
||||||
return '.' in filename and \
|
return '.' in filename and \
|
||||||
filename.rsplit('.', 1)[1] in Constant.SERVER_UPLOAD_ALLOWED_EXTENSIONS
|
filename.rsplit('.', 1)[1] in Constant.SERVER_UPLOAD_ALLOWED_EXTENSIONS
|
||||||
@@ -104,13 +100,13 @@ def upload_file():
|
|||||||
j = {'ret': 1, 'msg': ''}
|
j = {'ret': 1, 'msg': ''}
|
||||||
|
|
||||||
# check if the post request has the file part
|
# check if the post request has the file part
|
||||||
if 'file' not in flask.request.files:
|
if 'file' not in request.files:
|
||||||
j['msg'] = 'No file part'
|
j['msg'] = 'No file part'
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
|
|
||||||
# if user does not select file, browser also
|
# if user does not select file, browser also
|
||||||
# submit a empty part without filename
|
# submit a empty part without filename
|
||||||
file = flask.request.files['file']
|
file = request.files['file']
|
||||||
if file.filename == '':
|
if file.filename == '':
|
||||||
j['msg'] = 'No selected file'
|
j['msg'] = 'No selected file'
|
||||||
elif file and allowed_file(file.filename):
|
elif file and allowed_file(file.filename):
|
||||||
@@ -121,10 +117,9 @@ def upload_file():
|
|||||||
j['msg'] = filename
|
j['msg'] = filename
|
||||||
else:
|
else:
|
||||||
j['msg'] = 'File type not support'
|
j['msg'] = 'File type not support'
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
else:
|
else:
|
||||||
with open(Constant.SERVER_PAGE_UPLOAD, 'r') as f:
|
return render_template(Constant.SERVER_PAGE_UPLOAD)
|
||||||
return f.read()
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/send_msg/<to>/<msg>')
|
@app.route('/send_msg/<to>/<msg>')
|
||||||
@@ -134,8 +129,7 @@ def send_msg(to, msg):
|
|||||||
@param to: String, user id or group id
|
@param to: String, user id or group id
|
||||||
@param msg: String, words
|
@param msg: String, words
|
||||||
"""
|
"""
|
||||||
j = {'ret': 0 if wechat.send_text(to, msg) else 1}
|
return jsonify({'ret': 0 if wechat.send_text(to, msg) else 1})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/send_img/<to>/<img>')
|
@app.route('/send_img/<to>/<img>')
|
||||||
@@ -146,8 +140,7 @@ def send_img(to, img):
|
|||||||
@param img: String, image file name
|
@param img: String, image file name
|
||||||
"""
|
"""
|
||||||
img_path = os.path.join(app.config['UPLOAD_FOLDER'], img)
|
img_path = os.path.join(app.config['UPLOAD_FOLDER'], img)
|
||||||
j = {'ret': 0 if wechat.send_img(to, img_path) else 1}
|
return jsonify({'ret': 0 if wechat.send_img(to, img_path) else 1})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/send_emot/<to>/<emot>')
|
@app.route('/send_emot/<to>/<emot>')
|
||||||
@@ -158,8 +151,7 @@ def send_emot(to, emot):
|
|||||||
@param emot: String, emotion file name
|
@param emot: String, emotion file name
|
||||||
"""
|
"""
|
||||||
emot_path = os.path.join(app.config['UPLOAD_FOLDER'], emot)
|
emot_path = os.path.join(app.config['UPLOAD_FOLDER'], emot)
|
||||||
j = {'ret': 0 if wechat.send_emot(to, emot_path) else 1}
|
return jsonify({'ret': 0 if wechat.send_emot(to, emot_path) else 1})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/send_file/<to>/<file>')
|
@app.route('/send_file/<to>/<file>')
|
||||||
@@ -170,8 +162,7 @@ def send_file(to, file):
|
|||||||
@param file: String, file name
|
@param file: String, file name
|
||||||
"""
|
"""
|
||||||
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file)
|
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file)
|
||||||
j = {'ret': 0 if wechat.send_file(to, file_path) else 1}
|
return jsonify({'ret': 0 if wechat.send_file(to, file_path) else 1})
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
|
||||||
|
|
||||||
|
|
||||||
def mass_send(method, data, func):
|
def mass_send(method, data, func):
|
||||||
@@ -221,8 +212,8 @@ def mass_send_msg():
|
|||||||
"""
|
"""
|
||||||
@brief send text to mass users or gourps
|
@brief send text to mass users or gourps
|
||||||
"""
|
"""
|
||||||
j = mass_send(flask.request.method, flask.request.json, wechat.send_text)
|
j = mass_send(request.method, request.json, wechat.send_text)
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/mass_send_img', methods=["GET", "POST"])
|
@app.route('/mass_send_img', methods=["GET", "POST"])
|
||||||
@@ -230,8 +221,8 @@ def mass_send_img():
|
|||||||
"""
|
"""
|
||||||
@brief send iamge to mass users or gourps
|
@brief send iamge to mass users or gourps
|
||||||
"""
|
"""
|
||||||
j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendmsgimg)
|
j = mass_send(request.method, request.json, wechat.webwxsendmsgimg)
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/mass_send_emot', methods=["GET", "POST"])
|
@app.route('/mass_send_emot', methods=["GET", "POST"])
|
||||||
@@ -239,8 +230,8 @@ def mass_send_emot():
|
|||||||
"""
|
"""
|
||||||
@brief send emoticon to mass users or gourps
|
@brief send emoticon to mass users or gourps
|
||||||
"""
|
"""
|
||||||
j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendemoticon)
|
j = mass_send(request.method, request.json, wechat.webwxsendemoticon)
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/mass_send_file', methods=["GET", "POST"])
|
@app.route('/mass_send_file', methods=["GET", "POST"])
|
||||||
@@ -248,8 +239,8 @@ def mass_send_file():
|
|||||||
"""
|
"""
|
||||||
@brief send file to mass users or gourps
|
@brief send file to mass users or gourps
|
||||||
"""
|
"""
|
||||||
j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendappmsg)
|
j = mass_send(request.method, request.json, wechat.webwxsendappmsg)
|
||||||
return flask.Response(json.dumps(j), mimetype='application/json')
|
return jsonify(j)
|
||||||
|
|
||||||
|
|
||||||
def run_server():
|
def run_server():
|
||||||
@@ -275,4 +266,3 @@ while True:
|
|||||||
else:
|
else:
|
||||||
# kill process
|
# kill process
|
||||||
os.system(Constant.LOG_MSG_KILL_PROCESS % os.getpid())
|
os.system(Constant.LOG_MSG_KILL_PROCESS % os.getpid())
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user