FastAPI - Run a function after POST method



  1. End result. Receive an email from server.

  2. Create a virtual environment and activate it.

    $ python3 -m venv venv
    $ source venv/bin/activate
  3. Install dependencies.

    (venv) $ pip install fastapi uvicorn[standard] python-dotenv
    (venv) clone .
  4. Rename .env_sample to .env and update environment variables with your credentials.
    EMAIL_PASSWORD=app password 16 characters;
  5. Create a new python file and paste below code. eg)

    import os
    from datetime import datetime
    from glob import glob
    from typing import Optional
    from fastapi import FastAPI
    from pydantic import BaseModel, validator
    import uvicorn
    from gmail import email_with_attachment
    app = FastAPI()
    class DateTimeModeMixin(BaseModel):
        # To add timestamp script executed,
        created_at: datetime = None
        @validator("created_at", pre=True, always=True)
        def default_datetime(cls, value:datetime) -> datetime:
            return value or
    class Job(DateTimeModeMixin):
        name: str
        description: Optional[str]
    jobs = []
    def job_email_with_attachment():
        to_email = os.getenv("TO_EMAIL").split(';')
        attachments = glob('data/*.csv')
        email_with_attachment(header='header...', recipient=to_email, body='body...', attachments=attachments)
    async def get_jobs():
        return jobs'/jobs', status_code=201)
    async def add_job(job: Job):
        return jobs
    if __name__ == '__main__':
  6. Run Ctrl + F5 or Right click >> "Run Python File in Terminal" within VS Code.

  7. Install VS extension "REST Client."

  8. Click "Send Request" on test.http file.



taeheechoi © 2023