instant-python 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. instant_python/__init__.py +0 -0
  2. instant_python/cli.py +11 -0
  3. instant_python/folder_cli.py +50 -0
  4. instant_python/installer/__init__.py +0 -0
  5. instant_python/installer/dependency_manager.py +15 -0
  6. instant_python/installer/dependency_manager_factory.py +14 -0
  7. instant_python/installer/git_configurer.py +47 -0
  8. instant_python/installer/installer.py +18 -0
  9. instant_python/installer/managers.py +7 -0
  10. instant_python/installer/operating_systems.py +7 -0
  11. instant_python/installer/pdm_manager.py +72 -0
  12. instant_python/installer/uv_manager.py +73 -0
  13. instant_python/project_cli.py +100 -0
  14. instant_python/project_generator/__init__.py +0 -0
  15. instant_python/project_generator/custom_template_manager.py +20 -0
  16. instant_python/project_generator/default_template_manager.py +45 -0
  17. instant_python/project_generator/directory.py +28 -0
  18. instant_python/project_generator/file.py +20 -0
  19. instant_python/project_generator/folder_tree.py +40 -0
  20. instant_python/project_generator/jinja_custom_filters.py +18 -0
  21. instant_python/project_generator/node.py +14 -0
  22. instant_python/project_generator/project_generator.py +31 -0
  23. instant_python/project_generator/template_manager.py +7 -0
  24. instant_python/question_prompter/__init__.py +0 -0
  25. instant_python/question_prompter/question/__init__.py +0 -0
  26. instant_python/question_prompter/question/boolean_question.py +13 -0
  27. instant_python/question_prompter/question/choice_question.py +18 -0
  28. instant_python/question_prompter/question/conditional_question.py +25 -0
  29. instant_python/question_prompter/question/dependencies_question.py +43 -0
  30. instant_python/question_prompter/question/free_text_question.py +13 -0
  31. instant_python/question_prompter/question/multiple_choice_question.py +13 -0
  32. instant_python/question_prompter/question/question.py +15 -0
  33. instant_python/question_prompter/question_wizard.py +15 -0
  34. instant_python/question_prompter/step/__init__.py +0 -0
  35. instant_python/question_prompter/step/dependencies_step.py +20 -0
  36. instant_python/question_prompter/step/general_custom_template_project_step.py +45 -0
  37. instant_python/question_prompter/step/general_project_step.py +50 -0
  38. instant_python/question_prompter/step/git_step.py +23 -0
  39. instant_python/question_prompter/step/steps.py +16 -0
  40. instant_python/question_prompter/step/template_step.py +63 -0
  41. instant_python/question_prompter/template_types.py +7 -0
  42. instant_python/question_prompter/user_requirements.py +39 -0
  43. instant_python/templates/__init__.py +0 -0
  44. instant_python/templates/boilerplate/.gitignore +164 -0
  45. instant_python/templates/boilerplate/.pre-commit-config.yml +33 -0
  46. instant_python/templates/boilerplate/.python-version +1 -0
  47. instant_python/templates/boilerplate/LICENSE +896 -0
  48. instant_python/templates/boilerplate/event_bus/__init__.py +0 -0
  49. instant_python/templates/boilerplate/event_bus/aggregate_root.py +19 -0
  50. instant_python/templates/boilerplate/event_bus/domain_event.py +15 -0
  51. instant_python/templates/boilerplate/event_bus/domain_event_json_deserializer.py +28 -0
  52. instant_python/templates/boilerplate/event_bus/domain_event_json_serializer.py +17 -0
  53. instant_python/templates/boilerplate/event_bus/domain_event_subscriber.py +15 -0
  54. instant_python/templates/boilerplate/event_bus/event_bus.py +10 -0
  55. instant_python/templates/boilerplate/event_bus/exchange_type.py +7 -0
  56. instant_python/templates/boilerplate/event_bus/mock_event_bus.py +18 -0
  57. instant_python/templates/boilerplate/event_bus/rabbit_mq_configurer.py +54 -0
  58. instant_python/templates/boilerplate/event_bus/rabbit_mq_connection.py +77 -0
  59. instant_python/templates/boilerplate/event_bus/rabbit_mq_consumer.py +58 -0
  60. instant_python/templates/boilerplate/event_bus/rabbit_mq_event_bus.py +28 -0
  61. instant_python/templates/boilerplate/event_bus/rabbit_mq_queue_formatter.py +22 -0
  62. instant_python/templates/boilerplate/event_bus/rabbit_mq_settings.py +8 -0
  63. instant_python/templates/boilerplate/exceptions/__init__.py +0 -0
  64. instant_python/templates/boilerplate/exceptions/domain_error.py +17 -0
  65. instant_python/templates/boilerplate/exceptions/domain_event_type_not_found_error.py +17 -0
  66. instant_python/templates/boilerplate/exceptions/incorrect_value_type_error.py +21 -0
  67. instant_python/templates/boilerplate/exceptions/invalid_id_format_error.py +17 -0
  68. instant_python/templates/boilerplate/exceptions/invalid_negative_value_error.py +17 -0
  69. instant_python/templates/boilerplate/exceptions/required_value_error.py +17 -0
  70. instant_python/templates/boilerplate/fastapi/__init__.py +0 -0
  71. instant_python/templates/boilerplate/fastapi/application.py +25 -0
  72. instant_python/templates/boilerplate/fastapi/http_response.py +45 -0
  73. instant_python/templates/boilerplate/fastapi/lifespan.py +14 -0
  74. instant_python/templates/boilerplate/fastapi/status_code.py +9 -0
  75. instant_python/templates/boilerplate/github/action.yml +22 -0
  76. instant_python/templates/boilerplate/github/test_lint.yml +36 -0
  77. instant_python/templates/boilerplate/logger/__init__.py +0 -0
  78. instant_python/templates/boilerplate/logger/json_formatter.py +16 -0
  79. instant_python/templates/boilerplate/logger/logger.py +39 -0
  80. instant_python/templates/boilerplate/mypy.ini +41 -0
  81. instant_python/templates/boilerplate/persistence/__init__.py +0 -0
  82. instant_python/templates/boilerplate/persistence/alembic_migrator.py +20 -0
  83. instant_python/templates/boilerplate/persistence/async/README.md +1 -0
  84. instant_python/templates/boilerplate/persistence/async/__init__.py +0 -0
  85. instant_python/templates/boilerplate/persistence/async/alembic.ini +124 -0
  86. instant_python/templates/boilerplate/persistence/async/async_engine_fixture.py +21 -0
  87. instant_python/templates/boilerplate/persistence/async/env.py +95 -0
  88. instant_python/templates/boilerplate/persistence/async/models_metadata.py +11 -0
  89. instant_python/templates/boilerplate/persistence/async/postgres_settings.py +15 -0
  90. instant_python/templates/boilerplate/persistence/async/script.py.mako +26 -0
  91. instant_python/templates/boilerplate/persistence/async/sqlalchemy_repository.py +30 -0
  92. instant_python/templates/boilerplate/persistence/base.py +4 -0
  93. instant_python/templates/boilerplate/persistence/synchronous/__init__.py +0 -0
  94. instant_python/templates/boilerplate/persistence/synchronous/session_maker.py +22 -0
  95. instant_python/templates/boilerplate/persistence/synchronous/sqlalchemy_repository.py +35 -0
  96. instant_python/templates/boilerplate/pyproject.toml +29 -0
  97. instant_python/templates/boilerplate/pytest.ini +10 -0
  98. instant_python/templates/boilerplate/random_generator.py +9 -0
  99. instant_python/templates/boilerplate/scripts/add_dependency.sh +37 -0
  100. instant_python/templates/boilerplate/scripts/create_aggregate.py +33 -0
  101. instant_python/templates/boilerplate/scripts/insert_template.py +90 -0
  102. instant_python/templates/boilerplate/scripts/integration.sh +39 -0
  103. instant_python/templates/boilerplate/scripts/local_setup.sh +15 -0
  104. instant_python/templates/boilerplate/scripts/makefile +137 -0
  105. instant_python/templates/boilerplate/scripts/post-merge +11 -0
  106. instant_python/templates/boilerplate/scripts/pre-commit +4 -0
  107. instant_python/templates/boilerplate/scripts/pre-push +6 -0
  108. instant_python/templates/boilerplate/scripts/remove_dependency.sh +36 -0
  109. instant_python/templates/boilerplate/scripts/unit.sh +40 -0
  110. instant_python/templates/boilerplate/value_object/__init__.py +0 -0
  111. instant_python/templates/boilerplate/value_object/int_value_object.py +11 -0
  112. instant_python/templates/boilerplate/value_object/string_value_object.py +19 -0
  113. instant_python/templates/boilerplate/value_object/uuid.py +17 -0
  114. instant_python/templates/boilerplate/value_object/value_object.py +21 -0
  115. instant_python/templates/project_structure/alembic_migrator.yml.j2 +3 -0
  116. instant_python/templates/project_structure/async_alembic.yml.j2 +20 -0
  117. instant_python/templates/project_structure/async_sqlalchemy.yml.j2 +17 -0
  118. instant_python/templates/project_structure/clean_architecture/main_structure.yml.j2 +25 -0
  119. instant_python/templates/project_structure/clean_architecture/source.yml.j2 +51 -0
  120. instant_python/templates/project_structure/clean_architecture/test.yml.j2 +23 -0
  121. instant_python/templates/project_structure/domain_driven_design/bounded_context.yml.j2 +20 -0
  122. instant_python/templates/project_structure/domain_driven_design/main_structure.yml.j2 +25 -0
  123. instant_python/templates/project_structure/domain_driven_design/source.yml.j2 +55 -0
  124. instant_python/templates/project_structure/domain_driven_design/test.yml.j2 +26 -0
  125. instant_python/templates/project_structure/event_bus_domain.yml.j2 +26 -0
  126. instant_python/templates/project_structure/event_bus_infra.yml.j2 +32 -0
  127. instant_python/templates/project_structure/fastapi_app.yml.j2 +10 -0
  128. instant_python/templates/project_structure/fastapi_infra.yml.j2 +10 -0
  129. instant_python/templates/project_structure/github_action.yml.j2 +18 -0
  130. instant_python/templates/project_structure/gitignore.yml.j2 +2 -0
  131. instant_python/templates/project_structure/license.yml.j2 +2 -0
  132. instant_python/templates/project_structure/logger.yml.j2 +10 -0
  133. instant_python/templates/project_structure/macros.j2 +6 -0
  134. instant_python/templates/project_structure/makefile.yml.j2 +38 -0
  135. instant_python/templates/project_structure/mypy.yml.j2 +3 -0
  136. instant_python/templates/project_structure/pre_commit.yml.j2 +3 -0
  137. instant_python/templates/project_structure/pyproject.yml.j2 +3 -0
  138. instant_python/templates/project_structure/pytest.yml.j2 +3 -0
  139. instant_python/templates/project_structure/python_version.yml.j2 +2 -0
  140. instant_python/templates/project_structure/standard_project/main_structure.yml.j2 +25 -0
  141. instant_python/templates/project_structure/standard_project/source.yml.j2 +30 -0
  142. instant_python/templates/project_structure/standard_project/test.yml.j2 +16 -0
  143. instant_python/templates/project_structure/synchronous_sqlalchemy.yml.j2 +17 -0
  144. instant_python/templates/project_structure/value_objects.yml.j2 +35 -0
  145. instant_python-0.0.1.dist-info/METADATA +276 -0
  146. instant_python-0.0.1.dist-info/RECORD +149 -0
  147. instant_python-0.0.1.dist-info/WHEEL +4 -0
  148. instant_python-0.0.1.dist-info/entry_points.txt +2 -0
  149. instant_python-0.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,36 @@
1
+ name: Pass checks and tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ lint:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v5
17
+ - uses: ./.github/actions/python_setup
18
+ - run: make check-lint
19
+ format:
20
+ runs-on: ubuntu-latest
21
+ steps:
22
+ - uses: actions/checkout@v5
23
+ - uses: ./.github/actions/python_setup
24
+ - run: make check-format
25
+ typing:
26
+ runs-on: ubuntu-latest
27
+ steps:
28
+ - uses: actions/checkout@v5
29
+ - uses: ./.github/actions/python_setup
30
+ - run: make check-typing
31
+ test:
32
+ runs-on: ubuntu-latest
33
+ steps:
34
+ - uses: actions/checkout@v5
35
+ - uses: ./.github/actions/python_setup
36
+ - run: make test
@@ -0,0 +1,16 @@
1
+ import json
2
+ import logging
3
+
4
+
5
+ class JSONFormatter(logging.Formatter):
6
+ def format(self, record: logging.LogRecord) -> str:
7
+ log_record = {
8
+ "time": self.formatTime(record, self.datefmt),
9
+ "level": record.levelname,
10
+ "name": record.name,
11
+ "message": record.getMessage(),
12
+ }
13
+ if hasattr(record, "extra"):
14
+ log_record["extra"] = record.extra
15
+
16
+ return json.dumps(log_record)
@@ -0,0 +1,39 @@
1
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
2
+ import logging
3
+ from datetime import date
4
+ from logging.handlers import TimedRotatingFileHandler
5
+ from pathlib import Path
6
+
7
+ from {{ source_name }}.{{ template_infra_import }}.log.json_formatter import JSONFormatter
8
+
9
+
10
+ def create_file_handler(file_name: str, level: int) -> TimedRotatingFileHandler:
11
+ root_project_path = Path(__file__).parents[4]
12
+ log_folder = root_project_path / "logs"
13
+ log_folder.mkdir(parents=True, exist_ok=True)
14
+
15
+ file_handler = TimedRotatingFileHandler(
16
+ filename=f"{log_folder}/{file_name}_{date.today().isoformat()}.log",
17
+ when="midnight",
18
+ interval=1,
19
+ backupCount=7,
20
+ encoding="utf-8",
21
+ )
22
+ file_handler.setFormatter(JSONFormatter())
23
+ file_handler.setLevel(level)
24
+
25
+ return file_handler
26
+
27
+
28
+ def create_logger(logger_name: str) -> logging.Logger:
29
+ logger = logging.getLogger(logger_name)
30
+ logger.setLevel(logging.DEBUG)
31
+
32
+ production_handler = create_file_handler(file_name="prod", level=logging.ERROR)
33
+ develop_handler = create_file_handler(file_name="dev", level=logging.DEBUG)
34
+
35
+ if not logger.handlers:
36
+ logger.addHandler(production_handler)
37
+ logger.addHandler(develop_handler)
38
+
39
+ return logger
@@ -0,0 +1,41 @@
1
+ [mypy]
2
+ files = src, tests
3
+ python_version = 3.13
4
+ mypy_path = .
5
+ disable_error_code = override,attr-defined
6
+ check_untyped_defs = true
7
+ disallow_any_explicit = false
8
+
9
+ # None and Optional handling
10
+ no_implicit_optional = true
11
+
12
+ # Configuring warnings
13
+ warn_redundant_casts = true
14
+ warn_unused_ignores = false
15
+ warn_no_return = true
16
+ warn_return_any = true
17
+ warn_unreachable = true
18
+
19
+ # Miscellaneous strictness flags
20
+ implicit_reexport = true
21
+ strict_equality = true
22
+
23
+ # Configuring error messages
24
+ show_error_context = true
25
+ show_column_numbers = true
26
+ show_error_codes = true
27
+ pretty = true
28
+ show_absolute_path = false
29
+
30
+ disallow_untyped_defs = true
31
+
32
+ [mypy-expects.*]
33
+ ignore_missing_imports = True
34
+ [mypy-doublex.*]
35
+ ignore_missing_imports = True
36
+ [mypy-src.*]
37
+ ignore_missing_imports = True
38
+ [mypy-tests.*]
39
+ disallow_untyped_defs = False
40
+ [mypy-doublex_expects.*]
41
+ ignore_missing_imports = True
@@ -0,0 +1,20 @@
1
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
2
+ import asyncio
3
+
4
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.postgres_settings import PostgresSettings
5
+ from alembic import command
6
+ from alembic.config import Config
7
+
8
+
9
+ class AlembicMigrator:
10
+ def __init__(self) -> None:
11
+ self._settings = PostgresSettings() # type: ignore
12
+ self._alembic_config = Config()
13
+
14
+ async def migrate(self) -> None:
15
+ self._alembic_config.set_main_option(
16
+ "sqlalchemy.url", self._settings.postgres_url
17
+ )
18
+ self._alembic_config.set_main_option("script_location", "migrations")
19
+ loop = asyncio.get_event_loop()
20
+ await loop.run_in_executor(None, command.upgrade, self._alembic_config, "head") # type: ignore
@@ -0,0 +1 @@
1
+ Generic single-database configuration with an async dbapi.
@@ -0,0 +1,124 @@
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts
5
+ # Use forward slashes (/) also on windows to provide an os agnostic path
6
+ script_location = migrations
7
+
8
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
9
+ # Uncomment the line below if you want the files to be prepended with date and time
10
+ # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
11
+ # for all available tokens
12
+ file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
13
+
14
+ # sys.path path, will be prepended to sys.path if present.
15
+ # defaults to the current working directory.
16
+ prepend_sys_path = .
17
+
18
+ # timezone to use when rendering the date within the migration file
19
+ # as well as the filename.
20
+ # If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
21
+ # Any required deps can installed by adding `alembic[tz]` to the pip requirements
22
+ # string value is passed to ZoneInfo()
23
+ # leave blank for localtime
24
+ # timezone =
25
+
26
+ # max length of characters to apply to the "slug" field
27
+ # truncate_slug_length = 40
28
+
29
+ # set to 'true' to run the environment during
30
+ # the 'revision' command, regardless of autogenerate
31
+ # revision_environment = false
32
+
33
+ # set to 'true' to allow .pyc and .pyo files without
34
+ # a source .py file to be detected as revisions in the
35
+ # versions/ directory
36
+ # sourceless = false
37
+
38
+ # version location specification; This defaults
39
+ # to migrations/versions. When using multiple version
40
+ # directories, initial revisions must be specified with --version-path.
41
+ # The path separator used here should be the separator specified by "version_path_separator" below.
42
+ # version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
43
+
44
+ # version path separator; As mentioned above, this is the character used to split
45
+ # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46
+ # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47
+ # Valid values for version_path_separator are:
48
+ #
49
+ # version_path_separator = :
50
+ # version_path_separator = ;
51
+ # version_path_separator = space
52
+ # version_path_separator = newline
53
+ #
54
+ # Use os.pathsep. Default configuration used for new projects.
55
+ version_path_separator = os
56
+
57
+ # set to 'true' to search source files recursively
58
+ # in each "version_locations" directory
59
+ # new in Alembic version 1.10
60
+ # recursive_version_locations = false
61
+
62
+ # the output encoding used when revision files
63
+ # are written from script.py.mako
64
+ # output_encoding = utf-8
65
+
66
+ sqlalchemy.url = driver://user:pass@localhost/dbname
67
+
68
+
69
+ [post_write_hooks]
70
+ # post_write_hooks defines scripts or Python functions that are run
71
+ # on newly generated revision scripts. See the documentation for further
72
+ # detail and examples
73
+
74
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
75
+ # hooks = black
76
+ # black.type = console_scripts
77
+ # black.entrypoint = black
78
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
79
+
80
+ # lint with attempts to fix using "ruff" - use the exec runner, execute a binary
81
+ hooks = ruff_lint, ruff_format
82
+ ruff_lint.type = exec
83
+ ruff_lint.executable = %(here)s/.venv/bin/ruff
84
+ ruff_lint.options = check --fix REVISION_SCRIPT_FILENAME
85
+
86
+ # format with attempts to fix using "ruff" - use the exec runner, execute a binary
87
+ ruff_format.type = exec
88
+ ruff_format.executable = %(here)s/.venv/bin/ruff
89
+ ruff_format.options = format REVISION_SCRIPT_FILENAME
90
+
91
+ # Logging configuration
92
+ [loggers]
93
+ keys = root,sqlalchemy,alembic
94
+
95
+ [handlers]
96
+ keys = console
97
+
98
+ [formatters]
99
+ keys = generic
100
+
101
+ [logger_root]
102
+ level = WARNING
103
+ handlers = console
104
+ qualname =
105
+
106
+ [logger_sqlalchemy]
107
+ level = WARNING
108
+ handlers =
109
+ qualname = sqlalchemy.engine
110
+
111
+ [logger_alembic]
112
+ level = INFO
113
+ handlers =
114
+ qualname = alembic
115
+
116
+ [handler_console]
117
+ class = StreamHandler
118
+ args = (sys.stderr,)
119
+ level = NOTSET
120
+ formatter = generic
121
+
122
+ [formatter_generic]
123
+ format = %(levelname)-5.5s [%(name)s] %(message)s
124
+ datefmt = %H:%M:%S
@@ -0,0 +1,21 @@
1
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
2
+ from collections.abc import AsyncGenerator
3
+ import pytest
4
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
5
+
6
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.postgres_settings import PostgresSettings
7
+
8
+
9
+ @pytest.fixture
10
+ async def engine() -> AsyncGenerator[AsyncEngine]:
11
+ settings = PostgresSettings() # type: ignore
12
+ engine = create_async_engine(settings.postgres_url)
13
+
14
+ async with engine.begin() as conn:
15
+ await conn.run_sync(EntityModel.metadata.create_all)
16
+
17
+ yield engine
18
+
19
+ async with engine.begin() as conn:
20
+ await conn.run_sync(EntityModel.metadata.drop_all)
21
+ await engine.dispose()
@@ -0,0 +1,95 @@
1
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
2
+ import asyncio
3
+ from logging.config import fileConfig
4
+
5
+ from alembic import context
6
+ from sqlalchemy import pool
7
+ from sqlalchemy.engine import Connection
8
+ from sqlalchemy.ext.asyncio import async_engine_from_config
9
+
10
+ from migrations.models_metadata import base
11
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.postgres_settings import PostgresSettings
12
+
13
+ # this is the Alembic Config object, which provides
14
+ # access to the values within the .ini file in use.
15
+ config = context.config
16
+
17
+ settings = PostgresSettings() # type: ignore
18
+ config.set_main_option("sqlalchemy.url", settings.postgres_url)
19
+
20
+ # Interpret the config file for Python logging.
21
+ # This line sets up loggers basically.
22
+ if config.config_file_name is not None:
23
+ fileConfig(config.config_file_name)
24
+
25
+ # add your model's MetaData object here
26
+ # for 'autogenerate' support
27
+ # from myapp import mymodel
28
+ # target_metadata = mymodel.Base.metadata
29
+ target_metadata = base.metadata
30
+
31
+ # other values from the config, defined by the needs of env.py,
32
+ # can be acquired:
33
+ # my_important_option = config.get_main_option("my_important_option")
34
+ # ... etc.
35
+
36
+
37
+ def run_migrations_offline() -> None:
38
+ """Run migrations in 'offline' mode.
39
+
40
+ This configures the context with just a URL
41
+ and not an Engine, though an Engine is acceptable
42
+ here as well. By skipping the Engine creation
43
+ we don't even need a DBAPI to be available.
44
+
45
+ Calls to context.execute() here emit the given string to the
46
+ script output.
47
+
48
+ """
49
+ url = config.get_main_option("sqlalchemy.url")
50
+ context.configure(
51
+ url=url,
52
+ target_metadata=target_metadata,
53
+ literal_binds=True,
54
+ dialect_opts={"paramstyle": "named"},
55
+ )
56
+
57
+ with context.begin_transaction():
58
+ context.run_migrations()
59
+
60
+
61
+ def do_run_migrations(connection: Connection) -> None:
62
+ context.configure(connection=connection, target_metadata=target_metadata)
63
+
64
+ with context.begin_transaction():
65
+ context.run_migrations()
66
+
67
+
68
+ async def run_async_migrations() -> None:
69
+ """In this scenario we need to create an Engine
70
+ and associate a connection with the context.
71
+
72
+ """
73
+
74
+ connectable = async_engine_from_config(
75
+ config.get_section(config.config_ini_section, {}),
76
+ prefix="sqlalchemy.",
77
+ poolclass=pool.NullPool,
78
+ )
79
+
80
+ async with connectable.connect() as connection:
81
+ await connection.run_sync(do_run_migrations)
82
+
83
+ await connectable.dispose()
84
+
85
+
86
+ def run_migrations_online() -> None:
87
+ """Run migrations in 'online' mode."""
88
+
89
+ asyncio.run(run_async_migrations())
90
+
91
+
92
+ if context.is_offline_mode():
93
+ run_migrations_offline()
94
+ else:
95
+ run_migrations_online()
@@ -0,0 +1,11 @@
1
+ """
2
+ This module is needed for alembic to detect correctly all models of the project.
3
+
4
+ When we import Base.metadata in the env.py file it will include all the models that inherit from it only if these models
5
+ have already been imported. To keep the env.py file clean, we import the Base.metadata in this file and then import all the
6
+ needed models.
7
+ """
8
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
9
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.base import Base
10
+
11
+ base = Base
@@ -0,0 +1,15 @@
1
+ from pydantic import Field
2
+ from pydantic_settings import BaseSettings, SettingsConfigDict
3
+
4
+
5
+ class PostgresSettings(BaseSettings):
6
+ model_config = SettingsConfigDict(env_file=(".env", ".env.prod"), extra="ignore")
7
+ postgres_user: str = Field(alias="POSTGRES_USER")
8
+ postgres_password: str = Field(alias="POSTGRES_PASSWORD")
9
+ postgres_db: str = Field(alias="POSTGRES_DB")
10
+ postgres_host: str = Field(alias="POSTGRES_HOST")
11
+ postgres_port: str = Field(alias="POSTGRES_PORT")
12
+
13
+ @property
14
+ def postgres_url(self) -> str:
15
+ return f"postgresql+asyncpg://{self.postgres_user}:{self.postgres_password}@{self.postgres_host}:{self.postgres_port}/{self.postgres_db}"
@@ -0,0 +1,26 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ ${imports if imports else ""}
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = ${repr(up_revision)}
16
+ down_revision: Union[str, None] = ${repr(down_revision)}
17
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19
+
20
+
21
+ def upgrade() -> None:
22
+ ${upgrades if upgrades else "pass"}
23
+
24
+
25
+ def downgrade() -> None:
26
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,30 @@
1
+ {% set template_domain_import = "shared.domain"|compute_base_path(template) %}
2
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
3
+ from typing import TypeVar
4
+
5
+ from {{ source_name }}.{{ template_domain_import }}.value_objects.uuid import Uuid
6
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.base import Base
7
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, asynce_sessionmaker
8
+
9
+
10
+ Entity = TypeVar("Entity")
11
+
12
+
13
+ class SqlalchemyRepository[Model: Base]:
14
+ _model_class: type[Model]
15
+ _session_maker: asynce_sessionmaker[AssyncSession]
16
+
17
+ def __init__(self, engine: AsyncEngine, model_class: type[Model]) -> None:
18
+ self._session_maker = async_sessionmaker(bind=engine)
19
+ self._model_class = model_class
20
+
21
+ async def persist(self, entity: Entity) -> None:
22
+ async with self._session_maker() as session:
23
+ entity_model = self._model_class(**entity.to_dict())
24
+ session.add(entity_model)
25
+ await session.commit()
26
+
27
+ async def find(self, entity_id: Uuid) -> Entity:
28
+ async with self._session_maker() as session:
29
+ entity_model = await session.get(self._model_class, entity_id.value)
30
+ return entity_model.to_aggregate() if entity_model else None
@@ -0,0 +1,4 @@
1
+ from sqlalchemy.orm import DeclarativeBase
2
+
3
+
4
+ class Base(DeclarativeBase): ...
@@ -0,0 +1,22 @@
1
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
2
+ from sqlalchemy import create_engine, Engine
3
+ from sqlalchemy.orm import sessionmaker, Session
4
+
5
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.base import (
6
+ Base,
7
+ )
8
+
9
+
10
+ class SessionMaker:
11
+ _session_maker: sessionmaker[Session]
12
+ _engine: Engine
13
+
14
+ def __init__(self, url: str) -> None:
15
+ self._engine = create_engine(url)
16
+ self._session_maker = sessionmaker(bind=self._engine)
17
+
18
+ def get_session(self) -> Session:
19
+ return self._session_maker()
20
+
21
+ def create_tables(self) -> None:
22
+ Base.metadata.create_all(self._engine)
@@ -0,0 +1,35 @@
1
+ {% set template_domain_import = "shared.domain"|compute_base_path(template) %}
2
+ {% set template_infra_import = "shared.infra"|compute_base_path(template) %}
3
+ from typing import Type, TypeVar
4
+
5
+ from {{ source_name }}.{{ template_domain_import }}.value_objects.uuid import Uuid
6
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.base import Base
7
+ from {{ source_name }}.{{ template_infra_import }}.persistence.sqlalchemy.session_maker import (
8
+ SessionMaker,
9
+ )
10
+
11
+ Entity = TypeVar("Entity")
12
+
13
+
14
+ class SqlAlchemyRepository[Model: Base]:
15
+ _model_class: Type[Model]
16
+ _session_maker: SessionMaker
17
+
18
+ def __init__(self, session_maker: SessionMaker, model_class: Type[Model]) -> None:
19
+ self._session_maker = session_maker
20
+ self._model_class = model_class
21
+
22
+ def persist(self, entity: Entity) -> None:
23
+ with self._session_maker.get_session() as session:
24
+ entity_model = self._model_class(**entity.to_dict())
25
+ session.add(entity_model)
26
+ session.commit()
27
+
28
+ def search_by_id(self, entity_id: Uuid) -> Entity | None:
29
+ with self._session_maker.get_session() as session:
30
+ entity_model = (
31
+ session.query(self._model_class)
32
+ .filter(self._model_class.id == entity_id.value)
33
+ .first()
34
+ )
35
+ return entity_model.to_aggregate() if entity_model else None
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "{{ project_slug }}"
3
+ version = "{{ version }}"
4
+ description = "{{ description }}"
5
+ authors = [{name = "{{ author }}", email = "{{ git_email }}"}]
6
+ dependencies = [
7
+ {% if "async_sqlalchemy" in built_in_features %}
8
+ "sqlalchemy",
9
+ "asyncpg",
10
+ "psycopg2-binary",
11
+ {% endif %}
12
+ {% if "async_alembic" in built_in_features %}
13
+ "alembic",
14
+ {% endif %}
15
+ {% if "event_bus" in built_in_features %}
16
+ "pika",
17
+ {% endif %}
18
+ {% if "fastapi_application" in built_in_features %}
19
+ "fastapi[standard]",
20
+ {% endif %}
21
+ ]
22
+ requires-python = "=={{ python_version }}.*"
23
+ readme = "README.md"
24
+ license = { file = "LICENSE" }
25
+
26
+ {% if dependency_manager == "pdm" %}
27
+ [tool.pdm]
28
+ distribution = false
29
+ {% endif %}
@@ -0,0 +1,10 @@
1
+ [pytest]
2
+ markers =
3
+ unit: mark a test as a unit test
4
+ acceptance: mark a test as an acceptance test
5
+ integration: mark a test as an integration test
6
+ testpaths =
7
+ tests
8
+ asyncio_default_fixture_loop_scope =
9
+ function
10
+ asyncio_mode = auto
@@ -0,0 +1,9 @@
1
+ from faker import Faker
2
+
3
+
4
+ class RandomGenerator:
5
+ faker = Faker()
6
+
7
+ @classmethod
8
+ def uuid(cls) -> str:
9
+ return cls.faker.uuid4()
@@ -0,0 +1,37 @@
1
+ #!/bin/bash
2
+
3
+ read -p "Dependency to install: " dependency
4
+ read -p "Do you want to install $dependency as a dev dependency? (y/n): " is_dev
5
+ read -p "Do you want to install the $dependency inside a group? (y/n): " add_to_group
6
+
7
+ {% if dependency_manager == "pdm" -%}
8
+ dev_flag=""
9
+ group_flag=""
10
+
11
+ if [ "$is_dev" == "y" ]; then
12
+ flag="--dev"
13
+ fi
14
+
15
+ if [ "$add_to_group" == "y" ]; then
16
+ read -p "Group name: " group_name
17
+ flag="--group $group_name"
18
+ fi
19
+
20
+ pdm add $dev_flag $group_flag $dependency
21
+
22
+ {%- elif dependency_manager == "uv" -%}
23
+ flag=""
24
+
25
+ if [ "$is_dev" == "y" ]; then
26
+ flag="--dev"
27
+ fi
28
+
29
+ if [ "$add_to_group" == "y" ]; then
30
+ read -p "Group name: " group_name
31
+ flag="--group $group_name"
32
+ fi
33
+
34
+ uv add $flag $dependency
35
+
36
+ {%- endif %}
37
+