В настоящее время я реализовал обработку сеансов с загрузкой файлов, где каждый пользователь входит в систему с именем пользователя и может загружать файлы. Я хочу создать подпапку в app.config ['UPLOAD_FOLDER'] с именем пользователя или некоторым уникальным идентификатором, в котором хранятся все загрузки.
app.py:
from flask_dropzone import Dropzone
from flask import Flask, redirect, url_for, render_template, request, session,flash,g,send_from_directory
from datetime import timedelta
import subprocess
from werkzeug.utils import secure_filename
import os
import datetime
import urllib.request
app = Flask(__name__,template_folder=r'C:\Users\Pawan\Desktop\Flask\env\Scripts\static')
app.permanent_session_lifetime = timedelta(minutes=1)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]iasdfffsd/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'csv'])
app.config['UPLOAD_FOLDER'] = r'C:\Users\Pawan\Desktop\Flask\filename'
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def home():
return render_template('try.html')
@app.route('/login' , methods = ["POST", "GET"])
def login():
if request.method == "POST":
session.permanent = True
user = request.form["name"]
session["pawan"] = user
return redirect(url_for("user"))
return render_template('login.html')
@app.before_request
def before_request():
g.user = None
if "pawan" in session:
g.user = session["pawan"]
@app.route('/user' )
def user():
if g.user:
user = g.user
return f"<h1> Welcome {user}</h1>"'<br>' + \
"<b><a href = '/uploader'> Click here to uploads the files </a></b>"
return redirect(url_for("login"))
@app.route('/uploader')
def uploader():
return render_template('upload1.html')
@app.route('/upload',methods=['POST'])
def upload():
uploaded_files = request.files.getlist("file[]")
filenames = []
for file in uploaded_files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
filenames.append(filename)
return render_template('upload2.html', filenames=filenames)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],filename)
@app.route("/logout")
def logout():
session.pop("pawan", None)#pops out the key value of the session , if the is not present then it will print none
return redirect(url_for("login"))
if __name__ == "__main__":
app.run(debug=True)
login. html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<form method = "POST" >
<table>
<tr><td>name</td><td><input type = 'username' name = 'name'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>
upload1. html:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Upload a File</h3>
</div>
<hr/>
<div>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" multiple="" name="file[]" class="span3" /><br />
<input type="submit" value="Upload" class="span2">
</form>
</div>
</div>
</body>
</html>
upload2. html:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Uploaded files</h3>
</div>
<hr/>
<div>
This is a list of the files you just uploaded, click on them to load/download them
<ul>
{% for file in filenames %}
<li><a href="{{url_for('uploaded_file', filename=file)}}">{{file}}</a></li>
{% endfor %}
</ul>
</div>
<div class="header">
<h3 class="text-muted">Logout</h3> <b><a href = '/logout'> Logout</a></b>
</div>
<hr/>
</div>
</div>
</body>
</html>
Мне нужна реализация для создание папки для каждого уникального пользователя, позднее добавление модульности удаления папки после определенных дней / периодов. Буду признателен, если кто-то может подсказать