Flask-Uploads:如何与应用程序工厂一起使用
Flask-Uploads : how to use with application factory
我正在尝试在我的项目中实施 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
None 有效。
有什么想法吗???
PS:除此之外,我的应用程序中的其他所有内容都运行良好。
我在这里发帖后就明白了。很简单,但是找不到解释:
在您的 controller/view 文件中,路径是:
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 import my_upload_set
from flask_uploads import configure_uploads
def create_app(object):
(...)
configure_uploads(app, my_upload_set)
这应该很有魅力!
任何问题让我知道...
我正在尝试在我的项目中实施 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
None 有效。 有什么想法吗???
PS:除此之外,我的应用程序中的其他所有内容都运行良好。
我在这里发帖后就明白了。很简单,但是找不到解释:
在您的 controller/view 文件中,路径是:
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 import my_upload_set
from flask_uploads import configure_uploads
def create_app(object):
(...)
configure_uploads(app, my_upload_set)
这应该很有魅力! 任何问题让我知道...