|
| 1 | +import random |
| 2 | +from typing import Annotated |
| 3 | +from datetime import datetime |
| 4 | + |
| 5 | +import dagger |
| 6 | +from dagger import Container, dag, Directory, DefaultPath, Doc, File, Secret, function, object_type, ReturnType |
| 7 | + |
| 8 | + |
| 9 | +@object_type |
| 10 | +class Book: |
| 11 | + |
| 12 | + source: Annotated[dagger.Directory, DefaultPath(".")] |
| 13 | + |
| 14 | + @function |
| 15 | + def env(self) -> dagger.Container: |
| 16 | + """Returns a container with the Python environment and the source code mounted""" |
| 17 | + return ( |
| 18 | + dag.container() |
| 19 | + .from_("python:3.11") |
| 20 | + .with_directory("/app", self.source) |
| 21 | + .with_workdir("/app") |
| 22 | + .with_mounted_cache("/root/.cache/pip", dag.cache_volume("python-pip")) |
| 23 | + .with_exec(["pip", "install", "-r", "requirements.txt"]) |
| 24 | + ) |
| 25 | + |
| 26 | + @function |
| 27 | + async def test(self) -> str: |
| 28 | + """Runs the tests in the source code and returns the output""" |
| 29 | + postgresdb = ( |
| 30 | + dag.container() |
| 31 | + .from_("postgres:alpine") |
| 32 | + .with_env_variable("POSTGRES_DB", "app_test") |
| 33 | + .with_env_variable("POSTGRES_PASSWORD", "secret") |
| 34 | + .with_exposed_port(5432) |
| 35 | + .as_service(args=[], use_entrypoint=True) |
| 36 | + ) |
| 37 | + |
| 38 | + cmd = ( |
| 39 | + self.env() |
| 40 | + .with_service_binding("db", postgresdb) |
| 41 | + .with_env_variable("DATABASE_URL", "postgresql://postgres:secret@db/app_test") |
| 42 | + .with_exec(["pytest"]) |
| 43 | + ) |
| 44 | + return await cmd.stdout() |
| 45 | + |
| 46 | + @function |
| 47 | + async def publish(self) -> str: |
| 48 | + """Builds and publishes the application container to a registry""" |
| 49 | + await self.test() |
| 50 | + return await ( |
| 51 | + self.env() |
| 52 | + .with_exposed_port(8000) |
| 53 | + .with_entrypoint(["fastapi", "run", "main.py"]) |
| 54 | + .publish(f"ttl.sh/my-fastapi-app-{random.randrange(10**8)}") |
| 55 | + ) |
0 commit comments