From 9ff0eac50ed1872d8c135528d2b3519037cb100c Mon Sep 17 00:00:00 2001 From: spikey Date: Sat, 24 Feb 2024 11:36:01 -0500 Subject: [PATCH] added basic user api --- main.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 7 deletions(-) diff --git a/main.py b/main.py index ec8e60d..f55d06d 100755 --- a/main.py +++ b/main.py @@ -1,12 +1,56 @@ #!/usr/bin/env python3 -from flask import Flask -from flask import render_template +import sqlite3 +from flask import Flask, request, jsonify app = Flask(__name__) -@app.route("/") -def hello_world(): - return render_template('index.html') +def get_db(): + db = sqlite3.connect("example.db") + return db -if __name__ == '__main__': - app.run(port=8080, debug=True) +@app.route("/users", methods=["GET"]) +def get_users(): + db = get_db() + cursor = db.cursor() + cursor.execute("SELECT * FROM users") + users = cursor.fetchall() + return jsonify(users) + +@app.route("/users", methods=["POST"]) +def create_user(): + db = get_db() + cursor = db.cursor() + name = request.form["name"] + email = request.form["email"] + cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email)) + db.commit() + return jsonify({"message": "User created successfully"}) + +@app.route("/users/", methods=["GET"]) +def get_user(user_id): + db = get_db() + cursor = db.cursor() + cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) + user = cursor.fetchone() + return jsonify(user) + +@app.route("/users/", methods=["PUT"]) +def update_user(user_id): + db = get_db() + cursor = db.cursor() + name = request.form["name"] + email = request.form["email"] + cursor.execute("UPDATE users SET name = ?, email = ? WHERE id = ?", (name, email, user_id)) + db.commit() + return jsonify({"message": "User updated successfully"}) + +@app.route("/users/", methods=["DELETE"]) +def delete_user(user_id): + db = get_db() + cursor = db.cursor() + cursor.execute("DELETE FROM users WHERE id = ?", (user_id,)) + db.commit() + return jsonify({"message": "User deleted successfully"}) + +if __name__ == "__main__": + app.run(debug=True)