Skip to content
Snippets Groups Projects
Select Git revision
  • 259b43a04ef15684a6a9c35a3f401a022d921518
  • main default protected
2 results

main.py

Blame
  • Charles Paperman's avatar
    Charles Paperman authored
    259b43a0
    History
    main.py 757 B
    from fastapi import FastAPI
    from pydantic import BaseModel, Field
    from pathlib import Path
    from datetime import datetime
    import json
    
    class Message(BaseModel):
        user: str
        content: str
        ts: datetime = Field(default_factory=datetime.now) # instantiated to now 
    
    
    base_file = Path("salon.json")
    
    if not base_file.exists():
        with open(base_file, "w") as f:
            f.write("[]") # Create an empty list 
            
    app = FastAPI()
    
    
    @app.get("/messages")
    async def get_messages():
        with open(base_file) as f:
            return json.load(f)
    
    @app.post("/publish")
    async def post_message(message: Message):
        with open(base_file) as f:
            d = json.load(f)
        d.append(message)
        with open(base_file, "w") as f:
            json.dump(d, f)