Python with Starlette

Cover Page

Back-end Page

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, as the last property in the list:

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 (name, message, id, audio) VALUES '
                                 '(%s, %s, gen_random_uuid(), %s);', (chatt.name, 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 name, message, id, time, audio FROM chatts ORDER BY time ASC;. 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$

Unfortunately there’s no practical way to include a base64-encoded sample audio string, nor a way to play it back without a front-end to decode it. The simplest way to test is to use your front end to record an audio message and post it to your back end, and then retrieve the chatt from the back end for play back.


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