From be4c1c547e0f6a76ab26ff992a486964acb230c1 Mon Sep 17 00:00:00 2001 From: Prits Date: Sun, 1 Oct 2023 01:22:11 +0300 Subject: [PATCH] release --- README.MD | 2 ++ database.py | 44 +++++++++++++++++++++++++++++++++++++++++++- main.py | 26 +++++++++++++++++++++++--- 3 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 README.MD diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..6660612 --- /dev/null +++ b/README.MD @@ -0,0 +1,2 @@ +# Example of a message API system on FastAPI with a backend Sqlite3 Database +## Documentation of pathes can be read on /docs \ No newline at end of file diff --git a/database.py b/database.py index b4e5337..af4e49a 100644 --- a/database.py +++ b/database.py @@ -4,5 +4,47 @@ con = sqlite3.connect("data.db") cur = con.cursor() -cur.execute('CREATE TABLE IF NOT EXISTS data_table (key, value)') +cur.execute( + """CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, + author TEXT NOT NULL, + recipient TEXT NOT NULL, + content TEXT + ); + """ +) +cur.close() +con.close() + +def DB_get_msg(id: int = None): + con = sqlite3.connect("data.db") + cur = con.cursor() + cur.execute("SELECT * FROM messages WHERE id=?", (id,)) + row = cur.fetchone() + cur.close() + con.close() + return row + + +def DB_new_msg( + author: str = "Unknown", recipient: str = "Unknown", content: str = "N/A" +): + con = sqlite3.connect("data.db") + cur = con.cursor() + data = (author, recipient, content) + cur.execute( + "INSERT INTO messages (author, recipient, content) VALUES(?, ?, ?)", (data) + ) + con.commit() + cur.close() + con.close() + + +def DB_get_recent_msgs(last: int = 10): + con = sqlite3.connect("data.db") + cur = con.cursor() + cur.execute("SELECT * FROM messages ORDER BY id DESC") + rows = cur.fetchmany(last) + con.close() + print(rows) + return rows diff --git a/main.py b/main.py index d8145eb..1126a61 100644 --- a/main.py +++ b/main.py @@ -1,9 +1,29 @@ from fastapi import FastAPI +from pydantic import BaseModel import database + app = FastAPI() -@app.get("/") -def read_root(): - return {"Hello": "World"} +class Message(BaseModel): + author: str + recipient: str + content: str + +@app.get("/") +def read_recents(history: int = 10): + rs = database.DB_get_recent_msgs(history) + return rs + + +@app.post("/msg") +def post_msg(msg: Message): + database.DB_new_msg(author=msg.author, recipient=msg.recipient, content=msg.content) + return f"Message sent to {msg.recipient}" + + +@app.get("/msg/{msg_id}") +def get_msg(msg_id: int): + r = database.DB_get_msg(msg_id) + return r