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