Deleting/moving 文件与 Flask

Deleting/moving file with Flask

我设置了使用 wtforms、flask_wtf 和 flask_uploads 库上传个人资料图片,这会将文件上传到 Flask 的 static 文件夹中的服务器。 我想阻止用户上传多张个人资料图片,并想删除他们的旧照片。我已使用 IF 语句成功检测到服务器上的文件,但无法弄清楚如何删除该文件或只是将文件移动到另一个我可以手动删除的文件夹。

我试过 Python 函数 os.remove(),但总是收到指定文件不存在的错误。根据我的阅读,您不能在 Flask 中使用这样的功能,因为服务器处于活动状态 运行 并且它会扰乱活动进程。

处理这个问题的最佳办法是什么? 我希望有一个库函数可以首先检查文件名是否正在使用,然后覆盖文件,但在库文档中找不到任何内容。 我知道我可以将个人资料图片上传到 SQL table 到 BLOB 中,但读到这不是最佳解决方案。

让我知道您的建议是什么来解决防止用户上传过多文件的问题!

我目前有:

import os, sys
from flask import Flask, render_template, flash, request, url_for, redirect, session, send_file, send_from_directory
# WTForms
from wtforms import Form, BooleanField, TextField, PasswordField, SelectField, RadioField, TextAreaField, DateField, DateTimeField, StringField, validators
from wtforms.widgets import TextArea
from wtforms.validators import DataRequired
from flask_wtf import FlaskForm, RecaptchaField
from flask_wtf.file import FileField, FileRequired, FileAllowed
from werkzeug.utils import secure_filename
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from MySQLdb import escape_string as thwart

app = Flask(__name__)
#### PROFILE PIC UPLOAD ####
# Based after https://gist.github.com/greyli/81d7e5ae6c9baf7f6cdfbf64e8a7c037
# For uploading files
PROF_PIC_UPLOAD_FOLDER = 'static/user_info/prof_pic'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB

class ProfilePictureForm(FlaskForm):
    prof_pic = FileField(validators=[FileAllowed(photos, u'Image only!')])

@app.route('/profile_picture_upload/', methods=['GET','POST'])
def profile_picture_upload():
    form = ProfilePictureForm()
    cid = str(session['clientcid'])
    first_name = session['first_name']
    static_url = url_for('static', filename='user_info/prof_pic/')
    default_prof_pic = 'http://localhost:5000/_uploads/photos/static/user_info/prof_pic/default.jpg'
    user_prof_pic = cid+first_name+'.png'
    if form.validate_on_submit():
        filename = photos.save(form.prof_pic.data, folder=PROF_PIC_UPLOAD_FOLDER,name=cid+first_name+'.png')
        file_url = photos.url(filename)
        # Checks if the prof_pic is set yet. if set, then dont need to delete the old picture on the server
        if session['prof_pic'] != 'http://localhost:5000/_uploads/photos/static/user_info/prof_pic/default.jpg':
            #need to delete or move the old prof_pic if it was set! Prevents users from adding too many pictures
            flash("You already have a file on the server!")
        #If the user_prof_pic is there, then  
        session['prof_pic'] = file_url
        c, conn = connection()
        c.execute("UPDATE cpersonals SET prof_pic = %s WHERE cid = (%s)", (file_url, cid))
        conn.commit()
        c.close()
        conn.close()
    else:
        file_url = None

    return render_template('profile_picture_upload.html', form=form, file_url=file_url)

首先您要确保该文件存在于您的位置

import os.path

os.path.exists(file_path)

同时检查调试模式 - chmod 文件夹有问题。