The last thing we’ll do is create a route that returns the data from the database in CSV format, bringing us full circle back to the Python workshop, where you loaded banned book data from a CSV file and posted it to Tumblr. In theory, you could take the data from this web application, and feed it back into that script to post it to Tumblr.
You are probably used to the routine by now - to add this functionality, we need to create a new route. Uncomment this block from app.py:
# Retrieve all books similarly to the above route, but return as a CSV list instead of HTML page.
@app.route('/books_csv')
def book_csv():
# Instantiate a StringIO object to capture the data we'll pass to the CSV writer.
si = io.StringIO()
# Instantiate a CSV writer that uses the above StringIO object
cw = csv.writer(si)
# Query the database for all books, ordering by the book ID in descending order
all_books = Book.select().order_by(Book.id.desc())
# The CSV writer knows how to write Python "tuples", so pass the data we got from the database in tuples format.
# The resulting data from the CSVWriter will end up in our StringIO object called "si"
cw.writerows(all_books.tuples())
# Return the value of "si", which will be the database data converted into CSV format
return si.getvalue()
There are only a few lines to make this happen, but we’re using a couple new Python libraries. The first thing we do is create a new StringIO object. This is a stream, which is kind of like a container where our data will be converted from the format the database returns to CSV.
Next, we create a new CSVWriter, and tell it we’re going to use the StringIO stream we just defined. We then do a database query to get the data, and this is the exact same one we did for the “books” route earlier.
Now that we have the data and the CSVWriter ready, we tell the CSV writer to convert our database data into CSV. The CSVWriter knows how to convert data in the “tuple” format (which is like a list, but is immutable - the data can’t change), and our ORM knows how to return our database data in this format. Finally, we return the value of our StringIO stream, which now contains our converted CSV data.
Try hitting http://localhost:3000/books_csv to see what is returned. Notice that we didn’t need to create a template for this, since we’re not returning HTML.