実現
- Python+Flaskでwebアプリケーションを作りたい
- 機能が増えてきたので、Blueprintでviewを分割したい
- DBはDynamoDBと連携しており、pynamodbというpythonでDBを操作できるライブラリを利用。この中では、application.configを読み込みたい。
困っていること・状況
- Blueprintで分割した時、DBテーブル設定におけるコンフィグを読めない
- 実行結果より、current_appがapplication context外で読まれていることが原因であることはわかるが、具体的にうまく読ませる方法がわかりません。
- 例えば、class Metaの内部をwith application.app_context()で囲むことも行ったが、「AttributeError: As of v1.0 PynamoDB Models must have a table_name」とエラーが返ってくる(クラス変数を適切に取得できていない?)
- 関数(obtain_data)の中でclassを定義すると問題なく読み込むが、コードが重複するので避けたい
質問
- Blueprintでモジュール分割した場合にapplication context外で設定を読み込む方法を教えていただきたい
動いているコード
Python
1from flask import Flask, current_app 2from pynamodb.models import Model 3from pynamodb.attributes import UnicodeAttribute 4 5application = Flask(__name__) 6 7class DB(Model): 8 class Meta: 9 table_name = application.config.get('TABLE') 10 region = application.config.get('AWS_REGION') 11 aws_access_key_id = application.config.get('AWS_ACCESS_KEY_ID') 12 aws_secret_access_key = application.config.get('AWS_SECRET_ACCESS_KEY') 13 14 partition_key = UnicodeAttribute(hash_key=True, null=False) 15 data = UnicodeAttribute(null=True) 16 17@application.route('/obtain_dada/<partition_key>') 18def obtain_data(partition_key): 19 entries = DB.scan(partition_key) 20 entries = sorted(entries, key=lambda x: x.partition_key, reverse=True) 21 return entries
動かないコード
Python
1from flask import Flask, current_app 2from pynamodb.models import Model 3from pynamodb.attributes import UnicodeAttribute 4 5application = Flask(__name__) 6sub = Blueprint('sub', __name__) 7application.register_blueprint(sub) 8 9class DB(Model): 10 class Meta: 11 table_name = current_app.config.get('TABLE') 12 region = current_app.config.get('AWS_REGION') 13 aws_access_key_id = current_app.config.get('AWS_ACCESS_KEY_ID') 14 aws_secret_access_key = current_app.config.get('AWS_SECRET_ACCESS_KEY') 15 16 partition_key = UnicodeAttribute(hash_key=True, null=False) 17 data = UnicodeAttribute(null=True) 18 19@sub.route('/obtain_dada/<partition_key>') 20def obtain_data(partition_key): 21 entries = DB.scan(partition_key) 22 entries = sorted(entries, key=lambda x: x.partition_key, reverse=True) 23 return entries
実行結果
flask runして/obtain_dataにアクセスした結果
"This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the documentation for more information."
回答1件
あなたの回答
tips
プレビュー