Generating a report CSV and send it to an email - Python / Django Rest Framework

Overview

Generating a report in CSV format and sending it to a email

Resulto of report

How to start project.

  • Create a folder in your machine
  • Create a virtual environment
    • python3 -m venv venv
  • Start the virtual environment
    • . venv/bin/activate (Linux)
    • venv/Scripts/Activate (Windows)
  • Inside your venv folder clone the project
    • git clone https://github.com/alexlopesbr/forgot-password.git
  • In your-new-folder/venv/forgot-password
    • pip install -r requirements.txt to install the project's dependencies
    • python manage.py migrate to generate your database
    • python3 manage.py createsuperuser to create the admin
    • python3 manage.py runserver to start the server
  • Open your browser and go to http://127.0.0.1:8000/admin/
  • Login with the admin credentials
    • Now you can see you user and some info in admin panel

Using the functionality

POST {{localhost}}/core/log-generator

body of the request:

{
    "product_id": 1,
    "seller_id": 4,
    "date_from": "2021-01-14",
    "date_to": "2021-01-14"
}

header: Must be passed the key Authorization and the value Token


You can pass the following parameters to filter your results, note that all parameters are optional and in this case you will get all the logs:

If you pass only date_from, you will get the logs from that date.

If you pass both date_from and date_to, you will get the logs between those dates.

You can use Postman or Insomnia to test the requests.
Note: When you start your server the localhost generaly is http://127.0.0.1:8000/.


Some instructions and informations

root

setings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

BASE_URL = 'sandbox.com'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your-key'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

First step, set some configures in settings.py. Don't forget to set the EMAIL_HOST_USER and the EMAIL_HOST_PASSWORD.


core

models.py

class ProductSold(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '{} - {} - {}'.format(self.product.name, self.seller.user.email, self.client.user.email)

This model will be the base of the CSV file

views.py

@csrf_exempt
@api_view(['POST'])
@permission_classes([IsAdminUser])
def log_generator_view(request):
    return Response(log_generator(request))

This function view will generate the CSV file with the data from the request, look his ulr bellow.

urls.py

router = DefaultRouter()
router.register(r'user', UserViewSet)
router.register(r'client', ClientViewSet)
router.register(r'seller', SellerViewSet)
router.register(r'product', ProductViewSet)
router.register(r'product-sold', ProductSoldViewSet)

urlpatterns = [
    path('auth/', CustomAuthToken.as_view()),
    path('', include(router.urls)),
    url(r'^log-generator/?$', log_generator_view),

]

Just pay attention to the url of the log-generator, it will be used to generate the CSV file.

services.py

Products sold:
', to=[email, ], from_email=settings.EMAIL_HOST_USER, attachments=[(file, report)] ) msg.content_subtype = 'html' msg.send() ">
from django.core.mail import EmailMessage
from django.conf import settings

import io
import csv

from .models import ProductSold

def log_generator(request):
    email = request.user.email
    data = request.data

    product_id = data.get('product_id', None)
    seller = data.get('seller', None)
    date_from = data.get('date_from', None)
    date_to = data.get('date_to', None)

    producs_sold = ProductSold.objects.all()

    if product_id:
        producs_sold = producs_sold.filter(product__id=product_id)

    if seller:
        producs_sold = producs_sold.filter(seller__id=seller)

    if date_from:
        producs_sold = producs_sold.filter(created_at__exact=date_from)

    if date_from and date_to:
        producs_sold = producs_sold.filter(created_at__range=[date_from, date_to])

    create_log_report(producs_sold, email)


def create_log_report(producs_sold, email):
    filename = 'report.csv'

    data = io.StringIO()
    spamwriter = csv.writer(data)
    spamwriter.writerow(('Product', 'Price', 'Seller', 'Client', 'date', 'time'))

    for product_sold in producs_sold:
        Product = product_sold.product.name
        Price = product_sold.product.price
        Seller = product_sold.seller.user.name
        Client = product_sold.client.user.name
        date = product_sold.created_at.strftime("%Y/%m/%d")
        time = product_sold.created_at.strftime("%H:%M:%S")

        spamwriter.writerow((Product, Price, Seller, Client, date, time))

    if email:
        send_email_report(email, data.getvalue(), filename)


def send_email_report(email, report, file):
    msg = EmailMessage(
        u'Logs',
        '
Products sold:
'
, to=[email, ], from_email=settings.EMAIL_HOST_USER, attachments=[(file, report)] ) msg.content_subtype = 'html' msg.send()

The first function log_generator will take the parameters of the request that will serve as a basis for generating the log.

The second function create_log_report will create the CSV file. Note the spamwriter.writerow, to set the columns of the CSV file.

The last function send_email_report will send the email (logged in person's email) with the CSV file attached.


More information about sending emails in Sending email - Django documentation

More information about CSV files in How to create CSV output - Django documentation

Owner
alexandre Lopes
Graduated in Biological Sciences and now back end developer, I build API's in Python / Django Rest Framework but I confess that I love front end too.
alexandre Lopes
Compare two CSV files for differences. Colorize the differences and align the columns.

pretty-csv-diff Compare two CSV files for differences. Colorize the differences and align the columns. Command-Line Example Command-Line Usage usage:

Devon 6 Dec 29, 2022
Pyoccur - Python package to operate on occurrences (duplicates) of elements in lists

pyoccur Python Occurrence Operations on Lists About Package A simple python package with 3 functions has_dup() get_dup() remove_dup() Currently the du

Ahamed Musthafa 6 Jan 07, 2023
OpenTelemetry Python API and SDK

Getting Started • API Documentation • Getting In Touch (GitHub Discussions) Contributing • Examples OpenTelemetry Python This page describes the Pytho

OpenTelemetry - CNCF 1.1k Jan 08, 2023
Code for our SIGIR 2022 accepted paper : P3 Ranker: Mitigating the Gaps between Pre-training and Ranking Fine-tuning with Prompt-based Learning and Pre-finetuning

P3 Ranker Implementation for our SIGIR2022 accepted paper: P3 Ranker: Mitigating the Gaps between Pre-training and Ranking Fine-tuning with Prompt-bas

14 Jan 04, 2023
Portfolio project for Code Institute Full Stack software development course.

Comic Sales tracker This project is the third milestone project for the Code Institute Diploma in Full Stack Software Development. You can see the fin

1 Jan 10, 2022
Parser manager for parsing DOC, DOCX, PDF or HTML files

Parser manager Description Parser gets PDF, DOC, DOCX or HTML file via API and saves parsed data to the database. Implemented in Ruby 3.0.1 using Acti

Эдем 4 Dec 04, 2021
Read write method - Read files in various types of formats

一个关于所有格式文件读取的方法 1。 问题描述: 各种各样的文件格式,读写操作非常的麻烦,能够有一种方法,可以整合所有格式的文件,方便用户进行读取和写入。 2

2 Jan 26, 2022
OpenAPI (f.k.a Swagger) Specification code generator. Supports C#, PowerShell, Go, Java, Node.js, TypeScript, Python

AutoRest The AutoRest tool generates client libraries for accessing RESTful web services. Input to AutoRest is a spec that describes the REST API usin

Microsoft Azure 4.1k Jan 06, 2023
charcade is a string manipulation library that can animate, color, and bruteforce strings

charcade charcade is a string manipulation library that can animate, color, and bruteforce strings. Features Animating text for CLI applications with

Aaron 8 May 23, 2022
100 numpy exercises (with solutions)

100 numpy exercises This is a collection of numpy exercises from numpy mailing list, stack overflow, and numpy documentation. I've also created some p

Nicolas P. Rougier 9.5k Dec 30, 2022
Openapi-core is a Python library that adds client-side and server-side support for the OpenAPI Specification v3.

Openapi-core is a Python library that adds client-side and server-side support for the OpenAPI Specification v3.

A 186 Dec 30, 2022
Visualizacao-dados-dell - Repositório com as atividades desenvolvidas no curso de Visualização de Dados

📚 Descrição Neste curso da Dell trabalhamos com a visualização de dados. 🖥️ Aulas 1.1 - Explorando conjuntos de dados 1.2 - Fundamentos de visualiza

Claudia dos Anjos 1 Dec 28, 2021
Build documentation in multiple repos into one site.

mkdocs-multirepo-plugin Build documentation in multiple repos into one site. Setup Install plugin using pip: pip install git+https://github.com/jdoiro

Joseph Doiron 47 Dec 28, 2022
Show Rubygems description and annotate your code right from Sublime Text.

Gem Description for Sublime Text Show Rubygems description and annotate your code. Just mouse over your Gemfile's gem definitions to show the popup. s

Nando Vieira 2 Dec 19, 2022
Plover jyutping - Plover plugin for Jyutping input

Plover plugin for Jyutping Installation Navigate to the repo directory: cd plove

Samuel Lo 1 Mar 17, 2022
A website for courses of Major Computer Science, NKU

A website for courses of Major Computer Science, NKU

Sakura 0 Oct 06, 2022
Canonical source repository for PyYAML

PyYAML - The next generation YAML parser and emitter for Python. To install, type 'python setup.py install'. By default, the setup.py script checks

The YAML Project 2k Jan 01, 2023
freeCodeCamp Scientific Computing with Python Project for Certification.

Polygon_Area_Calculator freeCodeCamp Python Project freeCodeCamp Scientific Computing with Python Project for Certification. In this project you will

Rajdeep Mondal 1 Dec 23, 2021
Quickly download, clean up, and install public datasets into a database management system

Finding data is one thing. Getting it ready for analysis is another. Acquiring, cleaning, standardizing and importing publicly available data is time

Weecology 274 Jan 04, 2023
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 361 Nov 16, 2022