Cover Page

Backend Page

Python with Starlette

handlers.py

Change to your chatterd folder and edit the file handlers.py:

server$ cd ~/reactive/chatterd 
server$ vi handlers.py

Add one new property to the Chatt class:

class Chatt:
    # . . .
    audio: Optional[str] = None

To the back-end database, audio is just a string.

To handle audio data uploads, make a copy of your postchatt() function inside your handlers.py file and name the copy postaudio(). Replace the call to cursor.execute() with:

                await cursor.execute('INSERT INTO chatts (username, message, id, audio) VALUES '
                                 '(%s, %s, gen_random_uuid(), %s);', (chatt.username, chatt.message, chatt.audio))

which extracts the audio entry from the JSON object and insert it into the chatts table, along with the rest of its associated chatt.

Next, make a copy of your getchatts() function inside your handlers.py file and name the copy getaudio(). Replace the SELECT statement with: 'SELECT username, message, id, time, audio FROM chatts;'. This will retrieve all data, including our new audio string from the PostgreSQL database. In addition to the original columns, we added reading the audio column and included it in the chatt data returned to the front end.

We’re done with handlers.py. Save and exit the file.

main.py

Edit the file main.py:

server$ vi main.py

Find the routes array and add the following new routes for the new API endpoints /getaudio and /postaudio:

    Route('/getaudio', handlers.getaudio, methods=['GET']),
    Route('/postaudio', handlers.postaudio, methods=['POST']),

We’re done with main.py. Save and exit the file.

Test run

To test run your server, launch it from the command line:

server$ sudo su
# You are now root, note the command-line prompt changed from '$' or '%' to '#'.
# You can do a lot of harm with all of root's privileges, so be very careful what you do.
server# source .venv/bin/activate
(chattterd) ubuntu@server:/home/ubuntu/reactive/chatterd# granian --host 0.0.0.0 --port 443 --interface asgi --ssl-certificate /home/ubuntu/reactive/chatterd.crt --ssl-keyfile /home/ubuntu/reactive/chatterd.key --access-log --workers-kill-timeout 1 main:server
# Hit ^C to end the test
(chattterd) ubuntu@server:/home/ubuntu/reactive/chatterd# exit
# So that you're no longer root.
server$

The cover backend spec provides instructions for Testing audio upload.


Prepared by Wendan Jiang, Ollie Elmgren, Benjamin Brengman, Mark Wassink, Alexander Wu, Yibo Pi, and Sugih Jamin Last updated August 11th, 2025