Reader small image

You're reading from  Web Development with Django

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781839212505
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Ben Shaw
Ben Shaw
author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

Saurabh Badhwar
Saurabh Badhwar
author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Bharath Chandra K S
Bharath Chandra K S
author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

Chris Guest
Chris Guest
author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest

View More author details
Right arrow

13. Generating CSV, PDF, and Other Binary Files

Overview

This chapter teaches you how to generate files in different data formats, such as CSV, PDF, and other binary file formats (for example, Excel-compatible files) using some of the common libraries that are available inside Python. This knowledge will help you build web projects that let your users export and download records from your site into familiar CSV or Excel-based formats. You will also learn how to generate graph plots inside Python and render them as HTML and display them inside your web applications. Moreover, you will be able to build features that let users export your data in PDF format.

Introduction

So far, we have learned the various aspects of the Django framework and explored how we can build web applications using Django with all the features and customizations we want.

Let's say that while building a web application, we need to do some analysis and prepare some reports. We may need to analyze user demographics about how the platform is being used or generate data that can be fed into machine learning systems to find patterns. We want our website to display some of the results of our analysis in a tabular format and other results as detailed graphs and charts. Furthermore, we also want to allow our users to export the reports and peruse them further in applications such as Jupyter Notebook and Excel.

As we work our way through this chapter, we will learn how to bring these ideas to fruition and implement functionality in our web application that allows us to export records into structured formats such as tables through the use of Comma-Separated Value...

Working with Python's CSV Module

The csv module from Python provides us with the ability to interact with files that are in CSV format, which is nothing but a text file format. That is, the data stored inside the CSV files is human-readable.

The csv module requires that the file is opened before the methods supplied by the csv module can be applied. Let's take a look at how we can start with the very basic operation of reading data from CSV files.

Reading Data from a CSV File

Reading data from CSV files is quite easy and consists of the following steps:

  1. First, we open the file:
    csv_file = open('path to csv file')

    Here, we are reading the file using the Python open() method and then passing it the name of the file from which the data is to be read.

  2. Then, we read the data from the file object using the csv module's reader method:
    import csv
    csv_data = csv.reader(csv_file)

    In the first line, we imported the csv module, which contains the...

Working with Excel Files in Python

Microsoft Excel is a world-renowned software in the field of book-keeping and tabular record management. Similarly, the XLSX file format that was introduced with Excel has seen rapid and widespread adoption and is now supported by all the major product vendors.

You will find that Microsoft Excel and its XLSX format are used quite a lot in the marketing and sales departments of many companies. Let's say, for one such company's marketing department, you are building a web portal in Django that keeps track of the products purchased by users. It also displays data about the purchases, such as the time of purchase and the location where the purchase was made. The marketing and sales teams are planning to use this data to generate leads or to create relevant advertisements.

Since the marketing and sales teams use Excel quite a lot, we might want to export the data available inside our web application in XLSX format, which is native to Excel...

Working with PDF Files in Python

Portable Document Format or PDF is one of the most common file formats in the world. You must have encountered PDF documents at some point. These documents can include business reports, digital books, and more.

Also, do you remember ever having encountered websites that have a button that reads Print page as PDF? A lot of websites for government agencies readily provide this option, which allows you to print the web page directly as a PDF. So, the question arises, how can we do this for our web app? How should we add the option to export certain content as a PDF?

Over the years, a huge community of developers has contributed a lot of useful packages to the Python ecosystem. One of those packages can help us achieve PDF file generation.

Converting Web Pages to PDFs

Sometimes, we may run into situations where we want to convert a web page into a PDF. For example, we may want to print a web page to store it as a local copy. This also comes...

Playing with Graphs in Python

Graphs are a great way to visually represent data that changes within a specific dimension. We come across graphs quite frequently in our day-to-day lives, be it weather charts for a week, stock market movements, or student performance report cards.

Similarly, graphs can come in quite handy when we are working with our web applications. For Bookr, we can use graphs as a visual medium to show the user information about the number of books they read each week. Alternatively, we can show them the popularity of a book over time based on how many readers were reading the given book at a specific time. Now, let's look at how we can generate plots with Python and have them show up on our web pages.

Generating Graphs with plotly

Graphs can come in quite handy when trying to visualize patterns in the data maintained by our applications. There are a lot of Python libraries that help developers in generating static or interactive graphs.

For...

Integrating Visualizations with Django

In the preceding sections, you have learned how data can be read and written in different formats that cater to the different needs of users. But how can we use what we've learned to integrate with Django?

For example, in Bookr, we might want to allow the user to export a list of books that they have read or visualize their book reading activity over a year. How can that be done? The next exercise in this chapter focuses on that aspect, where you will learn how the components we have seen so far can be integrated into Django web applications.

Exercise 13.06: Visualizing a User's Reading History on the User Profile Page

In this exercise, you will aim to modify the user's profile page such that the user can visualize their book reading history when they visit their profile page on Bookr.

Let's look at how this can be done:

  1. To get started with integrating the ability to visualize the reading history of...

Summary

In this chapter, we looked at how we can deal with binary files and how Python's standard library, which comes pre-loaded with the necessary tools, can allow us to handle commonly used file formats such as CSV. We then moved on to learning how to read and write CSV files in Python using Python's CSV module. Later, we worked with the XlsxWriter package, which provides us with the ability to generate Microsoft Excel-compatible files right from our Python environment without worrying about the internal formatting of the file.

The second half of the chapter was dedicated to learning how to use the weasyprint library to generate PDF versions of HTML pages. This skill can come in handy when we want to provide our users with an easy option to print the HTML version of our page with any added CSS styling of our choosing. The last section of the chapter discussed how we can generate interactive graphs in Python and render them as HTML pages that can be viewed inside the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web Development with Django
Published in: Feb 2021Publisher: PacktISBN-13: 9781839212505
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest