Adjusting the database

To store an avatar against a particular user, we will need to add a column to our users database. We can do this via the Python REPL from our server folder, as follows:

Python 3.6.4 (default, Jan 03 2018, 13:52:55) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import database
>>> d = database.Database()
>>> sql = "ALTER TABLE users ADD avatar text"
>>> params = []
>>> d.perform_insert(sql, params)
>>>

In order to add a column to an existing table, we use an alter table command. We then specify the table name, new column name, and new column type.

With the preceding statement, we have added a column named avatar of the text type. This is the column which we will use to hold our avatar image.

We can now add some methods to the Database class which will allow us to both store and retrieve avatar data for a particular user:

def update_avatar(self, username, img_b64):
sql = "UPDATE users SET avatar=? WHERE username=?"
params = (img_b64, username)

return self.perform_insert(sql, params)

In order to alter an existing record without creating a new one, we can use an update statement. We supply this statement with the table name, the columns to update, and the where condition on which to filter the relevant records.

Since we want to update the avatar column for a record matching a supplied username, we use SET avatar=? to mark the avatar column for updating and provide WHERE username=? to say that we only want to update records which match a given username value.

This handles updating the avatars, but we will also want to be able to retrieve an avatar for a given user:

def get_user_avatar(self, username):
sql = "SELECT avatar FROM users WHERE username=?"
params = (username,)

return self.perform_select(sql, params)

Selecting a user's avatar requires just a simple select statement, featuring a where clause to specify the provided username.

Now that we have taken care of the database, we can create some server endpoints to allow the use of this new column.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset