From c06667a44801a8cf2e680ff60ade2e206d2d0895 Mon Sep 17 00:00:00 2001 From: Jolly23 Date: Thu, 20 Apr 2017 12:41:43 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20dev:=20=E4=BC=98=E5=8C=96Flask=E8=AF=AD?= =?UTF-8?q?=E6=B3=95=20&=20=E4=BF=AE=E6=AD=A3Flask=E6=89=BE=E4=B8=8D?= =?UTF-8?q?=E5=88=B0templates=E6=96=87=E4=BB=B6=E5=A4=B9=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 优化Flask语法,使用flask自带的jsonify进行json回复;使用flask自带的render_template进行html模版回复; 简化Flask书写语法 2. 将server文件夹更名flask_templates,在Flask初始化时将模版文件夹路径指向此文件夹 --- wxbot_project_py2.7/config/constant.py | 4 +- .../{server => flask_templates}/index.html | 0 .../{server => flask_templates}/upload.html | 0 wxbot_project_py2.7/weixin_bot.py | 60 ++++++++----------- 4 files changed, 27 insertions(+), 37 deletions(-) rename wxbot_project_py2.7/{server => flask_templates}/index.html (100%) rename wxbot_project_py2.7/{server => flask_templates}/upload.html (100%) diff --git a/wxbot_project_py2.7/config/constant.py b/wxbot_project_py2.7/config/constant.py index f3aa544..30f3839 100644 --- a/wxbot_project_py2.7/config/constant.py +++ b/wxbot_project_py2.7/config/constant.py @@ -23,8 +23,8 @@ class Constant(object): 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_PAGE_UPLOAD = 'Server/upload.html' - SERVER_PAGE_INDEX = 'Server/index.html' + SERVER_PAGE_UPLOAD = 'upload.html' + SERVER_PAGE_INDEX = 'index.html' RUN_RESULT_SUCCESS = '成功 %ds\n' RUN_RESULT_FAIL = '失败\n[*] 退出程序\n' diff --git a/wxbot_project_py2.7/server/index.html b/wxbot_project_py2.7/flask_templates/index.html similarity index 100% rename from wxbot_project_py2.7/server/index.html rename to wxbot_project_py2.7/flask_templates/index.html diff --git a/wxbot_project_py2.7/server/upload.html b/wxbot_project_py2.7/flask_templates/upload.html similarity index 100% rename from wxbot_project_py2.7/server/upload.html rename to wxbot_project_py2.7/flask_templates/upload.html diff --git a/wxbot_project_py2.7/weixin_bot.py b/wxbot_project_py2.7/weixin_bot.py index 96bb745..88a489b 100755 --- a/wxbot_project_py2.7/weixin_bot.py +++ b/wxbot_project_py2.7/weixin_bot.py @@ -12,7 +12,7 @@ from config import ConfigManager from config import Constant from config import Log #--------------------------------------------------- -import flask +from flask import Flask, render_template, send_file, jsonify, request import threading import traceback import os @@ -32,7 +32,7 @@ wechat.msg_handler = wechat_msg_processor wechat_msg_processor.wechat = wechat 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') logger = logging.getLogger('werkzeug') @@ -47,8 +47,7 @@ app.logger.addHandler(flask_log_handler) @app.route('/') def index(): - with open(Constant.SERVER_PAGE_INDEX, 'r') as f: - return f.read() + return render_template(Constant.SERVER_PAGE_INDEX) @app.route('/qrcode') @@ -59,7 +58,7 @@ def qrcode(): image_path = '%s/%s_%d.png' % (qdir, wechat.uuid, int(time.time()*100)) s = wechat.wx_conf['API_qrcode'] + wechat.uuid 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") @@ -68,8 +67,7 @@ def group_list(): @brief list groups """ result = wechat.db.select(Constant.TABLE_GROUP_LIST()) - j = {'count': len(result), 'group': result} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'count': len(result), 'group': result}) @app.route('/group_member_list/') @@ -79,8 +77,7 @@ def group_member_list(g_id): @param g_id String """ result = wechat.db.select(Constant.TABLE_GROUP_USER_LIST(), 'RoomID', g_id) - j = {'count': len(result), 'member': result} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'count': len(result), 'member': result}) @app.route('/group_chat_log/') @@ -90,13 +87,12 @@ def group_chat_log(g_name): @param g_name String """ result = wechat.db.select(Constant.TABLE_GROUP_MSG_LOG, 'RoomName', g_name) - j = {'count': len(result), 'chats': result} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'count': len(result), 'chats': result}) @app.route('/upload', methods=['GET', 'POST']) def upload_file(): - if flask.request.method == 'POST': + if request.method == 'POST': def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in Constant.SERVER_UPLOAD_ALLOWED_EXTENSIONS @@ -104,13 +100,13 @@ def upload_file(): j = {'ret': 1, 'msg': ''} # 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' - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify(j) # if user does not select file, browser also # submit a empty part without filename - file = flask.request.files['file'] + file = request.files['file'] if file.filename == '': j['msg'] = 'No selected file' elif file and allowed_file(file.filename): @@ -121,10 +117,9 @@ def upload_file(): j['msg'] = filename else: j['msg'] = 'File type not support' - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify(j) else: - with open(Constant.SERVER_PAGE_UPLOAD, 'r') as f: - return f.read() + return render_template(Constant.SERVER_PAGE_UPLOAD) @app.route('/send_msg//') @@ -134,8 +129,7 @@ def send_msg(to, msg): @param to: String, user id or group id @param msg: String, words """ - j = {'ret': 0 if wechat.send_text(to, msg) else 1} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'ret': 0 if wechat.send_text(to, msg) else 1}) @app.route('/send_img//') @@ -146,8 +140,7 @@ def send_img(to, img): @param img: String, image file name """ img_path = os.path.join(app.config['UPLOAD_FOLDER'], img) - j = {'ret': 0 if wechat.send_img(to, img_path) else 1} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'ret': 0 if wechat.send_img(to, img_path) else 1}) @app.route('/send_emot//') @@ -158,8 +151,7 @@ def send_emot(to, emot): @param emot: String, emotion file name """ emot_path = os.path.join(app.config['UPLOAD_FOLDER'], emot) - j = {'ret': 0 if wechat.send_emot(to, emot_path) else 1} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'ret': 0 if wechat.send_emot(to, emot_path) else 1}) @app.route('/send_file//') @@ -170,8 +162,7 @@ def send_file(to, file): @param file: String, file name """ file_path = os.path.join(app.config['UPLOAD_FOLDER'], file) - j = {'ret': 0 if wechat.send_file(to, file_path) else 1} - return flask.Response(json.dumps(j), mimetype='application/json') + return jsonify({'ret': 0 if wechat.send_file(to, file_path) else 1}) def mass_send(method, data, func): @@ -221,8 +212,8 @@ def mass_send_msg(): """ @brief send text to mass users or gourps """ - j = mass_send(flask.request.method, flask.request.json, wechat.send_text) - return flask.Response(json.dumps(j), mimetype='application/json') + j = mass_send(request.method, request.json, wechat.send_text) + return jsonify(j) @app.route('/mass_send_img', methods=["GET", "POST"]) @@ -230,8 +221,8 @@ def mass_send_img(): """ @brief send iamge to mass users or gourps """ - j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendmsgimg) - return flask.Response(json.dumps(j), mimetype='application/json') + j = mass_send(request.method, request.json, wechat.webwxsendmsgimg) + return jsonify(j) @app.route('/mass_send_emot', methods=["GET", "POST"]) @@ -239,8 +230,8 @@ def mass_send_emot(): """ @brief send emoticon to mass users or gourps """ - j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendemoticon) - return flask.Response(json.dumps(j), mimetype='application/json') + j = mass_send(request.method, request.json, wechat.webwxsendemoticon) + return jsonify(j) @app.route('/mass_send_file', methods=["GET", "POST"]) @@ -248,8 +239,8 @@ def mass_send_file(): """ @brief send file to mass users or gourps """ - j = mass_send(flask.request.method, flask.request.json, wechat.webwxsendappmsg) - return flask.Response(json.dumps(j), mimetype='application/json') + j = mass_send(request.method, request.json, wechat.webwxsendappmsg) + return jsonify(j) def run_server(): @@ -275,4 +266,3 @@ while True: else: # kill process os.system(Constant.LOG_MSG_KILL_PROCESS % os.getpid()) -