Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 27 additions & 32 deletions index.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,53 @@
from __future__ import print_function

import time
from typing import Any, Dict, Optional

from fastapi import FastAPI

from typing import Optional
from typing import Any, Optional

from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlmodel import Field, Session, SQLModel, create_engine, select


class User(SQLModel, table=True):
# TODO change the default value to the timestamp that the user is created
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[str] = None
age: Optional[int] = None


engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)
# Create an instance of the API class
app = FastAPI()
security = HTTPBasic(auto_error=False)

# NOTE: This authentication implementation is not complete nor robust. It
# is only meant to be used as an example.
@app.get("/")
async def root():
# TODO include the user's name if they are logged in
return {"message": "Hello {}".format("World")}

async def root(credentials: HTTPBasicCredentials = Depends(security)):
username = credentials.username if credentials else "World"
return {"message": "Hello {}".format(username)}

@app.post("/user")
async def create_new_user(*, user: User):
# TODO: Should handle the case where the user already exists
with Session(engine) as session:
session.add(user)
session.commit()
# TODO return the User ID
return {"message": "User created"}
if user.id is None:
user.id = int(time.time())
session.add(user)
session.commit()
return {"message": "User with ID {} created".format(user.id)}

@app.get("/user/{id}")
async def get_user(id: int):
with Session(engine) as session:
# TODO return the user based on the ID (and an error if not)
statement = select(User).where(User.name == id)
user = session.exec(statement).first()
return {"user": user}

with Session(engine) as session:
statement = select(User).where(User.id == id)
user = session.exec(statement).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return {"user": user}

# TODO: The purpose of this webhook is unclear and its implementation is
# incomplete
@app.get("/api/webhooks")
async def handle_hook(*, event: Any):
id = event.payload.conversation.id
return {"message": "Hello World"}