Flask框架基本模型

从Flask切换到FastAPI,备份一下。估计以后不会再用到Flask框架了。主要看中FastAPI的异步编程模型,可以和其它程序如mitmproxy比较好的融合在一个进程中。

主程序

python 复制代码
import os.path
import threading
from importlib import import_module

from flask import Flask
from flask_cors import CORS

import platform
import logging

# if platform.system() == 'Darwin':
#     logging_conf = os.path.join(os.path.dirname(__file__), '..', 'logging-dev.conf')
# else:
#     logging_conf = os.path.join(os.path.dirname(__file__), '..', 'logging-server.conf')
#
# logging.config.fileConfig(logging_conf)
# logger = logging.getLogger(__name__)


from twisted.web import server, wsgi
from twisted.internet import endpoints, reactor
class Main:
    def __init__(self):
        self.app = self.create_app()

        # self.messaging_methods = []
        # logger.info('CMS app initialized successfully.')

    def create_app(self):
        app = Flask(__name__)
        CORS(app, supports_credentials=True)  # 支持跨域请求
        # app.config.from_object('config')
        # self.register_database(app)
        self.register_blueprint(app)
        # init_login(app)
        # init_crawler(app)

        return app



    def register_blueprint(self, app):
        from qmtagent.api import api
        app.register_blueprint(api, url_prefix='/api')


    def start(self):
        root_resource = wsgi.WSGIResource(reactor, reactor.getThreadPool(), self.app)
        factory = server.Site(root_resource)
        # reactor.listenTCP(5000, factory)
        http_server = endpoints.TCP4ServerEndpoint(reactor, 5000)
        http_server.listen(factory)

        print("服务启动,监听端口为5000 ...")
        # start event loop
        reactor.run()

if __name__ == '__main__':
    Main().start()

Controller

python 复制代码
from . import api
from flask import jsonify, request
from playhouse.shortcuts import model_to_dict
from ..qmtclient import QMTClient


@api.route('/version')
def version():
    return 'v0.0.1'

@api.route('/acc_info')
def show_account():
    client = QMTClient()
    client.connect()
    accinfo = client.get_account_info()
    # json_obj = model_to_dict(accinfo.__class__, accinfo, recurse=False, only=['account_id', 'cash', 'market_value', 'total_asset'])
    json_obj = {'account_id': accinfo.account_id, 'cash':accinfo.cash, 'market_value': accinfo.market_value}
    response = jsonify(json_obj)
    return response


@api.route('/position')
def get_positions():
    return 'v0.0.1'

@api.route('/buy', methods=['POST'])
def buy():
    json_data = request.get_json()
    code = json_data['code']
    volume = json_data['volume']
    price = json_data['price']
    client = QMTClient()
    client.connect()
    client.buy(code, int(volume), float(price))


@api.route('/sell', methods=['POST'])
def sell():
    json_data = request.get_json()
    code = json_data['code']
    volume = json_data['volume']
    price = json_data['price']
    client = QMTClient()
    client.connect()
    client.sell(code, int(volume), float(price))


@api.route('/cancel')
def cancel_order():
    json_data = request.get_json()
    order_id = json_data['order_id']
    client = QMTClient()
    client.connect()
    client.cancel_order(order_id)

controller目录下放__init__.py,内容为:

python 复制代码
from flask import Blueprint

api = Blueprint('api', __name__)

from . import qmt_api
# from . import ebook_api
# from . import scrapy_api
相关推荐
龙哥说跨境24 分钟前
如何利用指纹浏览器爬虫绕过Cloudflare的防护?
服务器·网络·python·网络爬虫
monkey_meng25 分钟前
【Rust中的迭代器】
开发语言·后端·rust
余衫马27 分钟前
Rust-Trait 特征编程
开发语言·后端·rust
monkey_meng31 分钟前
【Rust中多线程同步机制】
开发语言·redis·后端·rust
小白学大数据40 分钟前
正则表达式在Kotlin中的应用:提取图片链接
开发语言·python·selenium·正则表达式·kotlin
flashman91141 分钟前
python在word中插入图片
python·microsoft·自动化·word
菜鸟的人工智能之路44 分钟前
桑基图在医学数据分析中的更复杂应用示例
python·数据分析·健康医疗
懒大王爱吃狼2 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
秃头佛爷3 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
深度学习lover4 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别