app-MAIL-temp/app/dashboard/views/batch_import.py

52 lines
1.7 KiB
Python
Raw Normal View History

2020-09-10 20:14:55 +02:00
import arrow
from flask import render_template, flash, request, redirect, url_for
from flask_login import login_required, current_user
from app import s3
from app.config import JOB_BATCH_IMPORT
from app.dashboard.base import dashboard_bp
from app.db import Session
2020-09-10 20:14:55 +02:00
from app.log import LOG
2020-10-15 16:45:28 +02:00
from app.models import File, BatchImport, Job
2020-09-10 20:14:55 +02:00
from app.utils import random_string
@dashboard_bp.route("/batch_import", methods=["GET", "POST"])
@login_required
def batch_import_route():
# only for users who have custom domains
if not current_user.verified_custom_domains():
flash("Alias batch import is only available for custom domains", "warning")
batch_imports = BatchImport.filter_by(user_id=current_user.id).all()
2020-09-10 20:14:55 +02:00
if request.method == "POST":
alias_file = request.files["alias-file"]
file_path = random_string(20) + ".csv"
file = File.create(user_id=current_user.id, path=file_path)
s3.upload_from_bytesio(file_path, alias_file)
Session.flush()
2020-09-10 20:14:55 +02:00
LOG.d("upload file %s to s3 at %s", file, file_path)
bi = BatchImport.create(user_id=current_user.id, file_id=file.id)
Session.flush()
2021-09-08 11:29:55 +02:00
LOG.d("Add a batch import job %s for %s", bi, current_user)
2020-09-10 20:14:55 +02:00
# Schedule batch import job
Job.create(
name=JOB_BATCH_IMPORT,
payload={"batch_import_id": bi.id},
run_at=arrow.now(),
)
Session.commit()
2020-09-10 20:14:55 +02:00
flash(
"The file has been uploaded successfully and the import will start shortly",
"success",
)
return redirect(url_for("dashboard.batch_import_route"))
return render_template("dashboard/batch_import.html", batch_imports=batch_imports)