Last active
December 2, 2022 05:06
-
-
Save glinscott/f7fc5e9b2f4a59625483aad2ff3908a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
from flask import Flask, jsonify, request | |
app = Flask(__name__) | |
# Connect to the database | |
conn = sqlite3.connect("twitter.db") | |
cursor = conn.cursor() | |
# Create the tweets table if it doesn't already exist | |
cursor.execute( | |
""" | |
CREATE TABLE IF NOT EXISTS tweets ( | |
id INTEGER PRIMARY KEY, | |
user_id INTEGER, | |
text TEXT | |
) | |
""" | |
) | |
# Create the users table if it doesn't already exist | |
cursor.execute( | |
""" | |
CREATE TABLE IF NOT EXISTS users ( | |
id INTEGER PRIMARY KEY, | |
username TEXT, | |
password TEXT | |
) | |
""" | |
) | |
# Create an endpoint to post a new tweet | |
@app.route("/tweet", methods=["POST"]) | |
def tweet(): | |
# Get the user_id and tweet text from the request body | |
user_id = request.json["user_id"] | |
text = request.json["text"] | |
# Insert the tweet into the database | |
cursor.execute( | |
""" | |
INSERT INTO tweets (user_id, text) | |
VALUES (?, ?) | |
""", | |
(user_id, text), | |
) | |
conn.commit() | |
# Return the id of the newly-created tweet | |
return jsonify({"id": cursor.lastrowid}) | |
# Create an endpoint to get all tweets for a user | |
@app.route("/tweets/<user_id>", methods=["GET"]) | |
def get_tweets(user_id): | |
# Query the database for all tweets by the given user | |
cursor.execute( | |
""" | |
SELECT id, text FROM tweets | |
WHERE user_id = ? | |
""", | |
(user_id,), | |
) | |
# Convert the tweets to a list of dictionaries | |
tweets = [ | |
{"id": row[0], "text": row[1]} | |
for row in cursor.fetchall() | |
] | |
# Return the list of tweets as JSON | |
return jsonify({"tweets": tweets}) | |
# Run the server | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment