Python 参考烧瓶蓝图中的应用程序位置
我有一个蓝图,我有一个上传表单。我正在尝试保存文件,但我无法确定如何引用正确的目录。当我使用app.instance_path时,它会给出错误消息: NameError:未定义名称“app” 如何声明用于存储烧瓶蓝图中文件的正确文件夹位置 这是我的init.py文件:Python 参考烧瓶蓝图中的应用程序位置,python,flask,Python,Flask,我有一个蓝图,我有一个上传表单。我正在尝试保存文件,但我无法确定如何引用正确的目录。当我使用app.instance_path时,它会给出错误消息: NameError:未定义名称“app” 如何声明用于存储烧瓶蓝图中文件的正确文件夹位置 这是我的init.py文件: # External libraries from flask import Flask # Import the resources from . import students def create_app(config
# External libraries
from flask import Flask
# Import the resources
from . import students
def create_app(configfile=None):
app = Flask(__name__)
app.register_blueprint(students.bp)
return app
这是我的students.py蓝图文件:
import os
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.utils import secure_filename
from SIMPLE.forms import ImportStudentsForm
bp = Blueprint('students', __name__, url_prefix='/students')
@bp.route('/import', methods=('GET', 'POST'))
def import_students():
# Load the register form
form = ImportStudentsForm(request.form)
if form.validate_on_submit():
f = request.files['file']
filename = secure_filename(f.filename)
f.save(os.path.join(
app.instance_path, 'uploads', filename
))
# Flash success
flash('Sucessfully registered.', 'success')
return render_template('students/batch_import_students.html', form=form)
任何指导都将不胜感激。谢谢。您收到错误,因为您没有在
students.py
中导入app
。您可以导入它(并承担循环导入的风险),但更优雅的方法是通过flask.current\u app
获取应用程序实例
将
从flask import current_app
添加到students.py
顶部,并将app.instance_path
替换为current_app.instance_path您会收到错误,因为您没有在students.py
中导入app
。您可以导入它(并承担循环导入的风险),但更优雅的方法是通过flask.current\u app
获取应用程序实例
将从flask import current_app
添加到students.py
顶部,并将app.instance_path
替换为current_app.instance_path尝试以下操作:
from flask import current_app
及
您正在使用应用程序工厂。所以这里没有“app”对象。可以使用current\u app
获取flask当前使用的任何应用程序,然后您就可以使用它了
此外,如果实例路径
不起作用,请尝试当前应用程序根路径
尝试以下操作:
from flask import current_app
及
您正在使用应用程序工厂。所以这里没有“app”对象。可以使用current\u app
获取flask当前使用的任何应用程序,然后您就可以使用它了
另外,如果实例路径
不起作用,请尝试当前应用程序根路径