如何为flask Blueprint()配置上传文件夹?

luy*_*ngl 5 python filepath flask

我想设法将文件上传并保存到 ./project/client/static 中,但每当我尝试保存文件时,它总是以 ./project/server/ 结束。

我想将默认上传文件夹配置为 ./project/client/static 或临时文件夹。

# project/server/main/views.py

@main_blueprint.route("/tasks", methods=["POST"])
def run_task():
    file = request.files.get('file')
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    print('downloading', file.filename)
    filename = file.filename
    file = request.files.get('file')
    filepath = filename
    print('downloading file', filename)
    file.save(filepath)
    print('download complete')
    print('starting task to predict file')
    info = { 'file': filepath }
    task = create_task.delay(info)
    print(task.id)
    return jsonify({"task_id": task.id}), 200


Run Code Online (Sandbox Code Playgroud)

这总是导致下载的文件保存到 ./project/server

我也在使用烧瓶蓝图

# project/server/main/views.py
import os
from flask import render_template, Blueprint, jsonify, request, Response, send_file, redirect, url_for
from celery.result import AsyncResult
from project.server.tasks import create_task
from project.machine_learning import app as machine_learning
main_blueprint = Blueprint("main", __name__, static_folder='static')
upload_folder = './project/client/static/'

Run Code Online (Sandbox Code Playgroud)

文件结构

| - root
  | - readme_files
  | - project
  |  | - machine_learning
  |  |  | - labelled_comments
  |  |  | - models
  |  |  | - notebooks
  |  |  | - src
  |  |  |  | - text_preprocessing
  |  |  |  | - csv_file_modifier
  |  |  |  |  | - pyunittest
  |  |  |  | - keyword_filter
  |  |  |  |  | - pyunittest
  |  |  |  |  |  | - keyword-dictionaries
  |  |  |  |  | - keyword-dictionaries
  |  | - tests
  |  | - server
  |  |  | - main
  |  | - client
  |  |  | - static
  |  |  |  | - archive
  |  |  | - templates

Run Code Online (Sandbox Code Playgroud)

Git*_*son 3

您可以指定文件应保存在upload_folder. 我采取的方法是添加一个环境变量来定义上传文件夹的路径。

# .env file
UPLOAD_PATH=project/client/static/
Run Code Online (Sandbox Code Playgroud)

然后,设置访问配置UPLOAD_PATH:

# config.py

import os

class Config(object):
    UPLOAD_PATH = os.environ.get("UPLOAD_PATH")
Run Code Online (Sandbox Code Playgroud)

该扩展python-dotenv在这里很有用,所以安装它。在您的应用程序实例中加载此配置(您已定义的位置app):

# __init__.py

from config import Config

app = Flask(__name__)
app.config.from_object(Config)
Run Code Online (Sandbox Code Playgroud)

更新save()路由中的函数,如下所示:

import os


@main_blueprint.route("/tasks", methods=["POST"])
def run_task():
   # ...
   file.save(os.path.join(app.config["UPLOAD_PATH"], filepath)
# ...
Run Code Online (Sandbox Code Playgroud)