Creating new endpoints

The first thing we will need is the ability to select new messages from our conversation databases. We will need to provide the current user's username and the last time when we checked for messages. Our database will then return all new messages by a different author since the last time we checked for messages.

Open up your conversation.py file and add the following method to it:

def get_new_messages(self, timestamp, username):
sql = "SELECT author, message FROM conversation WHERE date_sent > ? AND author <> ?"
params = (timestamp, username)

conn = sqlite3.connect(self.database)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute(sql, params)
results = [dict(row) for row in cursor.fetchall()]
conn.close()

return results

Our SQL query grabs the author's name and message for any record matching the aforementioned criteria. The <> in SQL is a not equal to operator.

With this in place, we can update our server.py file to add a matching endpoint:

@app.route("/get_new_messages", methods=["POST"])
def get_new_messages():
data = request.form
conversation_db_path = get_conversation_db_path_for_users(data)
conversation_db = Conversation(conversation_db_path)

timestamp = data["timestamp"]
requester_username = data["user_one"]

new_messages = conversation_db.get_new_messages(timestamp, requester_username)

return jsonify({
"messages": new_messages
})

After constructing the path to the relevant conversation database, we pull the author's username and the timestamp of the last check out of the POST parameters, then pass these over to our new method.

Any messages returned from the database are then provided back to the requester in JSON format.

Speaking of which, we will need a matching method in our Requester class to call this new endpoint:

def get_new_messages(self, timestamp, user_one, user_two):
""" user_one is the author's username, and user_two is the friend's """
endpoint = "/get_new_messages"
params = {
"timestamp": timestamp,
"user_one": user_one,
"user_two": user_two,
}

new_messages = self.request("POST", endpoint, params)

return new_messages

This method takes a timestamp of the last request, the author's username (as user_one), and the friend's username (as user_two).

It then sends this data over to the server, via POST request, and returns the response.

Now that the web service work has been done, we can utilize the new endpoints inside a thread. To keep things neat, we will be making a new file to hold our thread class. Go ahead and create a file called listeningthread.py alongside your chatwindow.py file.

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

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