我正在尝试在我的项目中实现Flask-Uploads。但是,我遇到了麻烦,因为我正在使用应用程序工厂功能,无法从应用程序中的其他文件访问UploadSets!
文件:app / __ init __。py
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
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...
当然,这不会起作用,因为images
没有定义。但是如何从应用程序导入它?
我试过了:
import app
app.images.save(...)
from flask import current_app
current_app.images.save(...)
from app import images
无效。 任何想法???
PS:我的应用程序中的其他所有内容都正常工作,除此之外。
答案 0 :(得分:1)
我在这里发布后就知道了。它很简单,但无法解释它无处解释:
在控制器/视图文件中,路径为:
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
在app/__init__.py
文件上:
from app.controllers.my_view my_upload_set
from flask_uploads import configure_uploads
def create_app(object):
(...)
configure_uploads(app, my_upload_set)
这应该像魅力一样! 有任何问题让我知道......