2

我正在尝试在我的项目中实现 Flask-Uploads。但是,我遇到了麻烦,因为我正在使用应用程序工厂功能并且无法从应用程序中的其他文件访问 UploadSets!

文件:应用程序/__init__.py

from flask_uploads import UploadSet, configure_uploads, IMAGES

def create_app(object_name):
    ...
    images = UploadSet('images', IMAGES)
    configure_uploads(app, images)

文件:应用程序/控制器/版本.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:除此之外,我的应用程序中的其他所有内容都运行良好。

4

1 回答 1

3

我在这里发帖后马上想通了。这很简单,但找不到任何解释:

在您的控制器/视图文件中,路由位于:

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)

这应该像一个魅力!有什么问题可以告诉我...

于 2018-03-26T12:55:34.907 回答