Added csv export of collection users

This commit is contained in:
Анатолий Богомолов 2024-03-12 18:54:20 +10:00
parent 1ce84db59c
commit a605795578
3 changed files with 57 additions and 13 deletions

View File

@ -1,4 +1,10 @@
import csv
from datetime import datetime
import io
import os
from flask import Blueprint, render_template, request
from loguru import logger
from app.models.collection import Collection
from app.extensions import db
@ -39,3 +45,22 @@ def delete_collection(id: int):
return "<small class=\"form-text\">Здесь ничего нет</small>", 200
return "", 200
@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))
return si.getvalue(), 200, {'Content-Disposition': f'attachment; filename={filename}', 'Content-type': 'text/csv'}

View File

@ -4,17 +4,27 @@
<ul class="list-group list-group-flush">
<li class="list-group-item">Кол-во пользрвателей: {{ collection.users|length }}</li>
</ul>
<form action="/api/collections/{{ collection.id }}" method="DELETE" class="card-footer px-2 pt-2">
<button
type="submit"
hx-delete="/api/collections/{{ collection.id }}"
hx-swap="outerHTML"
hx-target='[data-collection-id="{{ collection.id }}"]'
hx-confirm="Вы уверены, что хотите удалить коллекцию?"
class="btn btn-outline-danger"
>
Удалить
</button>
</form>
<div class="card-footer px-2 pt-2">
<div class="d-flex gap-2" role="group">
<form action="/api/collections/{{ collection.id }}" method="DELETE">
<button
type="submit"
hx-delete="/api/collections/{{ collection.id }}"
hx-swap="outerHTML"
hx-target='[data-collection-id="{{ collection.id }}"]'
hx-confirm="Вы уверены, что хотите удалить коллекцию?"
class="btn btn-outline-danger"
>
Удалить
</button>
</form>
<a
href="/api/collections/{{ collection.id }}/csv"
class="btn btn-outline-success"
>
Экспорт
</a>
</div>
</div>
</div>
</div>

View File

@ -19,4 +19,13 @@ class User(db.Model):
collection: Mapped["Collection"] = relationship("Collection", back_populates="users")
def exist(username: str, collection):
return not User.query.filter_by(username=username, collection=collection).first() is None
return not User.query.filter_by(username=username, collection=collection).first() is None
def to_dict(self):
return {
'id': self.id,
'first_name': self.first_name,
'last_name': self.last_name,
'phone': self.phone,
'username': self.username,
}