73 lines
1.8 KiB
Python
73 lines
1.8 KiB
Python
|
import os
|
||
|
from typing import List
|
||
|
|
||
|
import fastapi
|
||
|
import uvicorn
|
||
|
from ics import Calendar, Event
|
||
|
import pydantic
|
||
|
from datetime import datetime
|
||
|
from fastapi.responses import FileResponse
|
||
|
|
||
|
|
||
|
# pydantic model for icalendar events
|
||
|
class EventData(pydantic.BaseModel):
|
||
|
name: str
|
||
|
description: str
|
||
|
location: str
|
||
|
start: datetime
|
||
|
end: datetime
|
||
|
recurrence: str
|
||
|
attendees: List[str]
|
||
|
organizer: str
|
||
|
uid: str
|
||
|
url: str
|
||
|
|
||
|
|
||
|
app = fastapi.FastAPI()
|
||
|
|
||
|
|
||
|
@app.get("/")
|
||
|
def read_root():
|
||
|
return {"Application": "ICalendar Maker"}
|
||
|
|
||
|
|
||
|
# this function returns an icalendar file
|
||
|
@app.get("/generer/icalendar")
|
||
|
async def generer_icalendar(event_data: EventData):
|
||
|
cal = Calendar()
|
||
|
event = Event()
|
||
|
event.name = event_data.name
|
||
|
event.begin = event_data.start
|
||
|
event.end = event_data.end
|
||
|
event.description = event_data.description
|
||
|
event.location = event_data.location
|
||
|
event.recurrence = event_data.recurrence
|
||
|
event.uid = event_data.uid
|
||
|
event.attendees = event_data.attendees
|
||
|
event.organizer = event_data.organizer
|
||
|
event.url = event_data.url
|
||
|
cal.events.add(event)
|
||
|
|
||
|
# filename is uid and current timestamp
|
||
|
filename = event.uid + datetime.now().strftime("%Y%m%dT%H%M%S") + ".ics"
|
||
|
|
||
|
# create a tmp folder if it doesn't exist
|
||
|
if not os.path.exists("/tmp"):
|
||
|
os.mkdir("/tmp")
|
||
|
print("tmp folder created")
|
||
|
|
||
|
# write a file named calendar.ics containing file_content
|
||
|
with open(f"/tmp/{filename}", "w") as f:
|
||
|
f.write(cal.serialize())
|
||
|
f.close()
|
||
|
print(f"file {filename} created")
|
||
|
|
||
|
# return a pydantic FileResponse
|
||
|
return FileResponse(filename=f"{filename}",
|
||
|
path=f"/tmp/{filename}",
|
||
|
media_type="text/calendar")
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|