RODY/app/run.py

131 lines
3.5 KiB
Python
Raw Normal View History

2022-11-04 17:37:08 +08:00
import datetime
import importlib
import json
import logging
from typing import List, Dict, Union
from flask import Flask, request
from flask.helpers import get_env
from flask_sockets import Sockets
import sys
#sys.path.append("/mnt/sdc/algorithm/AICheck-MaskRCNN")
from app.core.common_utils import logger
from app.core.err_handler import page_not_found, method_not_allowed, exception_500, exception_400
from app.exts import db, migrate, ma
from app.utils.redis_config import redis_client
from app.utils.websocket_tool import manager
def register_extensions(app):
db.init_app(app)
migrate.init_app(app, db)
ma.init_app(app)
def register_blueprints(app):
from app import controller
for name in controller.__all__:
bp = getattr(importlib.import_module(f'app.controller.{name}'), 'bp', None)
if bp is not None:
app.register_blueprint(
bp, url_prefix=f"/api{bp.url_prefix if bp.url_prefix else ''}")
def register_error_handler(app):
app.register_error_handler(404, page_not_found)
app.register_error_handler(405, method_not_allowed)
app.register_error_handler(400, exception_400)
# app.register_error_handler(500, exception_500)
def register_cmds(app):
pass
def register_log(app):
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO, filename='ex.log')
# set up logging to console
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)
# logging.debug('debug')
# logging.info('info')
# logging.warning('warning')
# logging.error('error')
# logging.exception('exp')
def register_redis(app):
redis_client.init_redis_connect()
# socketio = SocketIO()
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('app.configs.{}'.format(get_env()))
app.debug = False
# app.json_encoder = CustomJSONEncoder
with app.app_context():
register_extensions(app)
register_blueprints(app)
register_error_handler(app)
db.create_all()
register_cmds(app)
register_log(app)
register_redis(app)
@app.before_request
def log_request_info():
logger = logging.getLogger('werkzeug')
if request.method in ['POST', 'PUT']:
logger.info('Request Body: %s', request.get_data())
return app
app = create_app()
sockets = Sockets(app)
@sockets.route('/echo/<id>')
def echo_socket(ws, id: str):
# 保存ws对象根据
manager.connect(ws=ws, id=id)
logger.info('------进入websocket')
while not ws.closed:
msg = ws.receive()
print(msg)
res = {'code': 1, 'type': 'init', 'msg': '建立连接成功', 'data': '1'}
try:
ws.send(json.dumps(res), callable(success())) # 发送数据
except:
manager.disconnect(ws=ws, id=id)
# ws.send(now) # 发送数据
def success():
logger.info('-----------回调消息成功------------')
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
#8080 6913 '192.168.0.20'
server = pywsgi.WSGIServer(('192.168.2.118', 6914), app, handler_class=WebSocketHandler)
server.serve_forever()