Flask-Uploads : how to use with application factory
我正在尝试在我的项目中实现Flask-Upload。但是,我遇到了麻烦,因为我正在使用应用程序工厂功能,并且无法从应用程序中的其他文件访问UploadSet!
文件:app / __ init __。py
1 2 3 4 5 6 | from flask_uploads import UploadSet, configure_uploads, IMAGES def create_app(object_name): ... images = UploadSet('images', IMAGES) configure_uploads(app, images) |
文件:app / controllers / editions.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from flask_uploads import UploadNotAllowed # this is one of my route files, registered in a blueprint editions = Blueprint('editions', __name__) ... # inside one of the routes poster = request.files.get('poster') try: filename = images.save(poster) except UploadNotAllowed: flash('The upload was not allowed.', category='warning') else: # add to db... |
这当然是行不通的,因为未定义
我尝试过:
1 2 3 4 5 6 7 | import app app.images.save(...) from flask import current_app current_app.images.save(...) from app import images |
均无效。
有什么想法吗?
PS:除此以外,我的应用程序中的所有其他东西都工作正常。
我在这里发布后马上就知道了。它很简单,但是找不到它的解释:
在控制器/视图文件上,路径为:
1 2 3 4 5 6 7 8 9 10 11 12 | from flask_upload import UploadSet, IMAGES my_upload_set = UploadSet('my_upload_set', IMAGES) # (...) routes where you can use: image = request.files.get('image') # or whatever your form field name is try: filename = my_upload_set.save(image) except UploadNotAllowed: flash('The upload was not allowed.', category='warning') else: # add to db |
在
1 2 3 4 5 6 | from app.controllers.my_view import my_upload_set from flask_uploads import configure_uploads def create_app(object): (...) configure_uploads(app, my_upload_set) |
这应该像一种魅力!
任何问题都让我知道...