最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask中如何用工厂模式初始化flask-restful的api

Flask crifan 299浏览 0评论
折腾:
【未解决】用蓝图和工厂模式去优化现有Flask项目代码结构
期间,需要去搞清楚,对于Flask-restful的api,之前是:
class RobotQaAPI(Resource):

    def processResponse(self,
                        respDict,
                        voiceName=MS_TTS_VOICE_NAME,
                        voiceRate=MS_TTS_VOICE_RATE,
                        voiceVolume=MS_TTS_VOICE_VOLUME):
        """
            process response dict before return
                generate audio for response text part
        """
        global log, gTempAudioFolder

        unicodeText = respDict["data"]["response"]["text"]
        log.info("unicodeText=%s")
......

api.add_resource(RobotQaAPI, '/qa', endpoint='qa')
如果要改为工厂模式去初始化,如何改造。
flask-restful api factory
Delayed initialization — init_app() not working · Issue #203 · flask-restful/flask-restful
rest – python flask-restful blueprint and factory pattern work together? – Stack Overflow
python – 404 when accessing resource Flask-Restful – Stack Overflow
去改为:
from factory import create_app, mongo, fsCollection, log

from resources.tts import testAudioSynthesis, initAudioService
from resources.qa import RobotQaAPI
from resources.asr import RobotAsrAPI, initASR
from resources.files import GridfsAPI, TmpAudioAPI

# api = Api(app)
api = Api()
log.info("api=%s", api)
api.add_resource(RobotQaAPI, '/qa', endpoint='qa')
api.add_resource(RobotAsrAPI, '/asr/language/<string:language>', endpoint='asr')
api.add_resource(GridfsAPI, '/files/<fileId>', '/files/<fileId>/<fileName>', endpoint='gridfs')
api.add_resource(TmpAudioAPI, '/tmp/audio/<filename>', endpoint='TmpAudio')

api.init_app(app)
待后续调试,看看是否正常。
【总结】
最终代码是:
app.py
import os

from conf.app import settings
from factory import create_app
app = create_app(settings)
app.app_context().push()
if __name__ == "__main__":
    app.run(
        host=settings.FLASK_HOST,
        port=settings.FLASK_PORT,
        debug=settings.DEBUG,
        use_reloader=False
    )
factory.py
import os
from flask import Flask
...
from flask_restful import Api
...
from conf.app import settings
...
from flask import g
################################################################################
# Global Function
################################################################################

def create_app(config_object, init_extensions=True):

    ...
    app.config.from_object(config_object)
    with app.app_context():
    
    ...
        if init_extensions:
            register_extensions(app)
    return app


def register_extensions(app):

    # api = Api(app)
    api = create_rest_api(app)
    log.debug("api=%s", api)
    g.api = api

    return app


def create_rest_api(app):
    from resources.qa import RobotQaAPI
    from resources.asr import RobotAsrAPI
    from resources.files import GridfsAPI, TmpAudioAPI

    rest_api = Api()
    rest_api.add_resource(RobotQaAPI, '/qa', endpoint='qa')
    rest_api.add_resource(RobotAsrAPI, '/asr/language/<string:language>', endpoint='asr')
    rest_api.add_resource(GridfsAPI, '/files/<fileId>', '/files/<fileId>/<fileName>', endpoint='gridfs')
    rest_api.add_resource(TmpAudioAPI, '/tmp/audio/<filename>', endpoint='TmpAudio')

    rest_api.init_app(app)
    return rest_api

...
而不同模块中是:
resources/qa.py
from flask_restful import reqparse
from conf.app import settings
from flask import g

app = g.app
log = g.log
fsCollection = g.fsCollection


class RobotQaAPI(Resource):

    def get(self):


        ...
        log.info("parser=%s", parser)

转载请注明:在路上 » 【已解决】Flask中如何用工厂模式初始化flask-restful的api

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
86 queries in 0.108 seconds, using 20.69MB memory