PaperParser/app/blueprints/api/collections/routes.py

66 lines
2.1 KiB
Python
Raw Normal View History

2024-03-12 18:54:20 +10:00
import csv
from datetime import datetime
import io
import os
2024-03-07 02:22:53 +10:00
from flask import Blueprint, render_template, request
2024-03-12 18:54:20 +10:00
from loguru import logger
2024-03-07 02:22:53 +10:00
2024-03-07 02:56:27 +10:00
from app.models.collection import Collection
from app.extensions import db
2024-03-07 02:22:53 +10:00
collections = Blueprint("collections", __name__, url_prefix="/collections", template_folder="templates")
2024-03-07 02:56:27 +10:00
2024-03-08 16:39:04 +10:00
@collections.route('/', methods=["POST"])
def create_collection():
data = request.form
name = data.get('collection_name')
if not name:
return render_template('collections/create_form.j2', collections_error='Введите название базы!')
if Collection.exists(name):
return render_template('collections/create_form.j2', collections_error='База уже существует!')
swap = 'afterbegin' if len(Collection.query.all()) > 0 else 'innerHTML'
collection = Collection(name=name)
db.session.add(collection)
db.session.commit()
return f"<option value=\"{collection.id}\" selected>{ collection.name }</option>", 200, {'Hx-Reswap': swap, 'HX-Retarget': '#collection-select'}
2024-03-07 02:56:27 +10:00
@collections.route("/<int:id>", methods=["DELETE"])
def delete_collection(id: int):
collection: Collection = Collection.query.get_or_404(id)
length = len(Collection.query.all()) - 1
db.session.delete(collection)
db.session.commit()
if length <= 0:
return "<small class=\"form-text\">Здесь ничего нет</small>", 200
2024-03-08 16:39:04 +10:00
return "", 200
2024-03-12 18:54:20 +10:00
@collections.route("/<int:id>/csv", methods=["GET"])
def export_users_to_csv(id: int):
collection: Collection = Collection.query.get_or_404(id)
if len(collection.users) <= 0:
return "", 204
filename = f"{collection.name} - {datetime.now()}.csv"
fieldnames = collection.users[0].to_dict().keys()
si = io.StringIO()
writer = csv.DictWriter(si, fieldnames)
writer.writeheader()
writer.writerows(map(lambda user: user.to_dict(), collection.users))
2024-03-12 19:15:13 +10:00
return si, 200, {'Content-Disposition': f'attachment; filename={filename}', 'Content-type': 'text/csv; charset=utf-8'}