added basic user api

This commit is contained in:
spikey 2024-02-24 11:36:01 -05:00
parent 15081d0409
commit 9ff0eac50e
1 changed files with 51 additions and 7 deletions

58
main.py
View File

@ -1,12 +1,56 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask import Flask import sqlite3
from flask import render_template from flask import Flask, request, jsonify
app = Flask(__name__) app = Flask(__name__)
@app.route("/") def get_db():
def hello_world(): db = sqlite3.connect("example.db")
return render_template('index.html') return db
if __name__ == '__main__': @app.route("/users", methods=["GET"])
app.run(port=8080, debug=True) 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/<int:user_id>", 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/<int:user_id>", 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/<int:user_id>", 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)