Untitled

 avatar
unknown
plain_text
2 years ago
2.1 kB
1
Indexable
from fastapi import FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from typing import Optional

app = FastAPI()

# Temporary data store for users and posts
users_db = {}
posts_db = []

# Token authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# User endpoints

@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    username = form_data.username
    password = form_data.password
    
    # Verify user credentials
    if username not in users_db or users_db[username] != password:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password")
    
    # Return bearer token
    return {"access_token": username, "token_type": "bearer"}

@app.get("/users/me")
async def read_user_me(token: str = Depends(oauth2_scheme)):
    return {"username": token}

@app.get("/users/{username}")
async def read_user(username: str):
    if username not in users_db:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
    return {"username": username}

# Post endpoints

@app.post("/posts")
async def create_post(title: str, content: str, token: str = Depends(oauth2_scheme)):
    # Verify token
    if token not in users_db:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    
    # Create post and add to db
    post = {"title": title, "content": content, "author": token}
    posts_db.append(post)
    return post

@app.get("/posts/{post_id}")
async def read_post(post_id: int):
    if post_id < 0 or post_id >= len(posts_db):
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
    return posts_db[post_id]

@app.get("/posts")
async def search_posts(query: Optional[str] = None):
    if query is None:
        return posts_db
    results = []
    for post in posts_db:
        if query.lower() in post["title"].lower() or query.lower() in post["content"].lower():
            results.append(post)
    return results