release
This commit is contained in:
2
README.MD
Normal file
2
README.MD
Normal file
@ -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
|
||||||
44
database.py
44
database.py
@ -4,5 +4,47 @@ con = sqlite3.connect("data.db")
|
|||||||
|
|
||||||
cur = con.cursor()
|
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
|
||||||
|
|||||||
26
main.py
26
main.py
@ -1,9 +1,29 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
from pydantic import BaseModel
|
||||||
import database
|
import database
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
class Message(BaseModel):
|
||||||
def read_root():
|
author: str
|
||||||
return {"Hello": "World"}
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user