From a605795578488e2077954cac4a15c4d293267050 Mon Sep 17 00:00:00 2001 From: winet Date: Tue, 12 Mar 2024 18:54:20 +1000 Subject: [PATCH] Added csv export of collection users --- app/blueprints/api/collections/routes.py | 25 ++++++++++++++ .../collections/templates/collections/card.j2 | 34 ++++++++++++------- app/models/user.py | 11 +++++- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/app/blueprints/api/collections/routes.py b/app/blueprints/api/collections/routes.py index a64b20b..3581276 100644 --- a/app/blueprints/api/collections/routes.py +++ b/app/blueprints/api/collections/routes.py @@ -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 "Здесь ничего нет", 200 return "", 200 + +@collections.route("//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'} \ No newline at end of file diff --git a/app/blueprints/api/collections/templates/collections/card.j2 b/app/blueprints/api/collections/templates/collections/card.j2 index aa7ed66..cc66d88 100644 --- a/app/blueprints/api/collections/templates/collections/card.j2 +++ b/app/blueprints/api/collections/templates/collections/card.j2 @@ -4,17 +4,27 @@ - + \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py index a26a8fa..ea9356b 100644 --- a/app/models/user.py +++ b/app/models/user.py @@ -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 \ No newline at end of file + 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, + } \ No newline at end of file