折腾:
【未解决】用蓝图和工厂模式去优化现有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
去改为:
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)