nwon_django_seeding 1.0.1__tar.gz

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.
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.1
2
+ Name: nwon_django_seeding
3
+ Version: 1.0.1
4
+ Summary: A Django seeding solution build on top of fixtures
5
+ Home-page: https://nwon.de
6
+ License: MIT
7
+ Author: Reik Stiebeling
8
+ Author-email: reik.stiebeling@nwon.de
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Dist: boto3 (>=1.34.128,<2.0.0)
18
+ Requires-Dist: django (>=3.0)
19
+ Requires-Dist: nwon-baseline (>=0.2.15,<0.3.0)
20
+ Requires-Dist: nwon-django-toolbox (>=0.6.7,<0.7.0)
21
+ Requires-Dist: pydantic (>=2.1.0)
22
+ Project-URL: Repository, https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding.git
23
+ Description-Content-Type: text/markdown
24
+
25
+ # NWON Django seeding
26
+
27
+
28
+
29
+ ## Getting started
30
+
31
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
32
+
33
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
34
+
35
+ ## Add your files
36
+
37
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
38
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
39
+
40
+ ```
41
+ cd existing_repo
42
+ git remote add origin https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding.git
43
+ git branch -M main
44
+ git push -uf origin main
45
+ ```
46
+
47
+ ## Integrate with your tools
48
+
49
+ - [ ] [Set up project integrations](https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding/-/settings/integrations)
50
+
51
+ ## Collaborate with your team
52
+
53
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
54
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
55
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
56
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
57
+ - [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
58
+
59
+ ## Test and Deploy
60
+
61
+ Use the built-in continuous integration in GitLab.
62
+
63
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
64
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
65
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
66
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
67
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
68
+
69
+ ***
70
+
71
+ # Editing this README
72
+
73
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
74
+
75
+ ## Suggestions for a good README
76
+
77
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
78
+
79
+ ## Name
80
+ Choose a self-explaining name for your project.
81
+
82
+ ## Description
83
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
84
+
85
+ ## Badges
86
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
87
+
88
+ ## Visuals
89
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
90
+
91
+ ## Installation
92
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
93
+
94
+ ## Usage
95
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
96
+
97
+ ## Support
98
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
99
+
100
+ ## Roadmap
101
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
102
+
103
+ ## Contributing
104
+ State if you are open to contributions and what your requirements are for accepting them.
105
+
106
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
107
+
108
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
109
+
110
+ ## Authors and acknowledgment
111
+ Show your appreciation to those who have contributed to the project.
112
+
113
+ ## License
114
+ For open source projects, say how it is licensed.
115
+
116
+ ## Project status
117
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
118
+
@@ -0,0 +1,93 @@
1
+ # NWON Django seeding
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+
53
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
54
+
55
+ ## Name
56
+ Choose a self-explaining name for your project.
57
+
58
+ ## Description
59
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60
+
61
+ ## Badges
62
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
63
+
64
+ ## Visuals
65
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
66
+
67
+ ## Installation
68
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
69
+
70
+ ## Usage
71
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
72
+
73
+ ## Support
74
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
75
+
76
+ ## Roadmap
77
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
78
+
79
+ ## Contributing
80
+ State if you are open to contributions and what your requirements are for accepting them.
81
+
82
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
83
+
84
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
85
+
86
+ ## Authors and acknowledgment
87
+ Show your appreciation to those who have contributed to the project.
88
+
89
+ ## License
90
+ For open source projects, say how it is licensed.
91
+
92
+ ## Project status
93
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,66 @@
1
+ import re
2
+ from os.path import basename, exists
3
+ from typing import List
4
+
5
+ from django.core.files.base import File as DjangoFile
6
+ from django.db.models.signals import post_delete, post_save, pre_save
7
+ from nwon_baseline import print_helper
8
+ from nwon_baseline.directory_helper import file_paths_in_directory
9
+ from nwon_django_toolbox.signals import disable_signals, enable_signals
10
+
11
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
12
+
13
+
14
+ def load_seed_media_files(environment: str):
15
+ print_helper.print_green(f"Loading seed files for {environment} environment")
16
+
17
+ disable_signals([post_delete, post_save, pre_save])
18
+
19
+ for file_folder in NWON_DJANGO_SEED_SETTINGS.file_directories_for_environment(
20
+ environment
21
+ ):
22
+ if exists(file_folder.path):
23
+ paths = file_paths_in_directory(file_folder.path)
24
+ for path in paths:
25
+ file_name = basename(path)
26
+
27
+ if file_name == ".keep":
28
+ continue
29
+
30
+ primary_keys: List[str] = re.findall(r"(\d+)", file_name)
31
+
32
+ if len(primary_keys) < 1:
33
+ raise Exception(
34
+ f"Path {path} does not contain a number in order to tie a "
35
+ + "file to an instance of {file_folder.model}"
36
+ )
37
+
38
+ primary_key = primary_keys[0]
39
+
40
+ try:
41
+ instance = file_folder.model.objects.get(pk=primary_key)
42
+ except file_folder.model.DoesNotExist:
43
+ print_helper.print_error(
44
+ f"Could not find {file_folder.model} with "
45
+ + f"{primary_key} for seeding {path}"
46
+ )
47
+ continue
48
+
49
+ with open(path, "rb") as file:
50
+ setattr(
51
+ instance, file_folder.file_key, DjangoFile(file, name=file_name)
52
+ )
53
+ instance.save()
54
+
55
+ class_name = instance.__class__.__name__
56
+ print_helper.print_blue(
57
+ f"Loaded media file from {path} to {class_name} "
58
+ + "with pk {instance.pk} for "
59
+ )
60
+ else:
61
+ print_helper.print_warning(
62
+ f"Could not load seed files from {file_folder.path} "
63
+ + "as the directory does not exist."
64
+ )
65
+
66
+ enable_signals([post_delete, post_save, pre_save])
@@ -0,0 +1,148 @@
1
+ import concurrent.futures
2
+ import inspect
3
+ from os import path
4
+ from typing import Callable, List, Optional, Type, Union
5
+
6
+ from django.db.models import Model
7
+ from django.db.models.base import ModelBase
8
+ from nwon_baseline import print_helper
9
+ from pydantic import BaseModel
10
+
11
+ from nwon_django_seeding.actions.write_database_seeds import write_database_seeds
12
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
13
+ from nwon_django_seeding.typings import ModelSeed, SeedSet
14
+
15
+
16
+ class SeedParameters(BaseModel):
17
+ model: Union[Type[ModelBase], Type[Model]]
18
+ path_to_write: str
19
+ post_json_processing: Optional[Callable[[str], None]]
20
+
21
+
22
+ def write_database_seed_sets(
23
+ environment: str,
24
+ seed_sets: List[SeedSet],
25
+ print_debug=False,
26
+ only_write_for_models: Optional[List[Type[Model]]] = None,
27
+ ):
28
+ """
29
+ Write JSON files for a list of seed sets.
30
+
31
+ We write them in parallel.
32
+ """
33
+
34
+ parameters = __prepare_parameters_for_parallel_execution(
35
+ environment, seed_sets, only_write_for_models
36
+ )
37
+
38
+ with concurrent.futures.ThreadPoolExecutor() as executor:
39
+ executor.map(
40
+ __write_seeds_parallel, parameters, [print_debug] * len(parameters)
41
+ )
42
+
43
+
44
+ def __prepare_parameters_for_parallel_execution(
45
+ environment: str,
46
+ seed_sets: List[SeedSet],
47
+ only_write_for_models: Optional[List[Type[Model]]] = None,
48
+ ) -> List[SeedParameters]:
49
+ """
50
+ Prepare the parameters for parallel execution.
51
+
52
+ They are returned as a list of tuples with:
53
+ - the model
54
+ - the path to write the file
55
+ - optionally a function for post processing the JSON file
56
+ """
57
+ directories = NWON_DJANGO_SEED_SETTINGS.directories_for_environment(environment)
58
+ default_seed_index = 1
59
+ environment_seed_index = 1
60
+
61
+ parameters: List[SeedParameters] = []
62
+
63
+ for seed_set in seed_sets:
64
+ directory = (
65
+ directories.default_directory
66
+ if seed_set.is_default_seed
67
+ else directories.environment_directory
68
+ )
69
+
70
+ for model_seed in seed_set.models:
71
+ file_name_prefix = (
72
+ default_seed_index
73
+ if seed_set.is_default_seed
74
+ else environment_seed_index
75
+ )
76
+
77
+ if seed_set.is_default_seed:
78
+ default_seed_index += 1
79
+ else:
80
+ environment_seed_index += 1
81
+
82
+ if isinstance(model_seed, ModelSeed):
83
+ post_json_processing = model_seed.post_json_processing
84
+ django_model = model_seed.model
85
+ else:
86
+ post_json_processing = None
87
+ django_model = model_seed
88
+
89
+ # If we only want to write specific models, we skip the others
90
+ if only_write_for_models and django_model not in only_write_for_models:
91
+ continue
92
+
93
+ app_name = __app_name_for_model(django_model)
94
+ prefix = f"{file_name_prefix:03d}"
95
+ model_name = __model_name(django_model)
96
+
97
+ if app_name != NWON_DJANGO_SEED_SETTINGS.default_app_name:
98
+ file_name = f"{prefix}_{model_name}__{app_name}.json"
99
+ else:
100
+ file_name = f"{prefix}_{model_name}.json"
101
+
102
+ path_to_write = path.join(directory, file_name)
103
+
104
+ parameters.append(
105
+ SeedParameters(
106
+ model=django_model,
107
+ path_to_write=path_to_write,
108
+ post_json_processing=post_json_processing,
109
+ )
110
+ )
111
+
112
+ return parameters
113
+
114
+
115
+ def __write_seeds_parallel(parameters: SeedParameters, print_debug: bool):
116
+ write_database_seeds(
117
+ parameters.path_to_write,
118
+ __model_identifiers([parameters.model]),
119
+ parameters.post_json_processing,
120
+ )
121
+
122
+ if print_debug:
123
+ print_helper.print_green(f"Created seed file in {parameters.path_to_write}")
124
+
125
+
126
+ def __model_name(model: Union[Type[Model], Type[ModelBase]]):
127
+ return model.__name__.lower()
128
+
129
+
130
+ def __app_name_for_model(model: Union[Type[Model], Type[ModelBase]]) -> str:
131
+ if issubclass(model, Model):
132
+ return model._meta.app_label
133
+
134
+ return NWON_DJANGO_SEED_SETTINGS.default_app_name
135
+
136
+
137
+ def __model_identifier(model: Union[Type[Model], Type[ModelBase]]):
138
+ app_name = __app_name_for_model(model)
139
+
140
+ return (
141
+ f"{app_name}.{model._meta.model_name}"
142
+ if issubclass(model, Model)
143
+ else f"{app_name}.{model.__name__.lower()}"
144
+ )
145
+
146
+
147
+ def __model_identifiers(models: List[Union[Type[Model], Type[ModelBase]]]):
148
+ return [__model_identifier(model) for model in models]
@@ -0,0 +1,26 @@
1
+ import subprocess
2
+ from typing import Callable, List, Optional
3
+
4
+
5
+ def write_database_seeds(
6
+ target_file: str,
7
+ model_or_apps_to_dump: List[str],
8
+ post_json_processing: Optional[Callable[[str], None]] = None,
9
+ ):
10
+ """
11
+ Write seed to file via console output as passing the proper
12
+ arguments was not possible.
13
+ """
14
+
15
+ arguments: List[str] = model_or_apps_to_dump + [
16
+ "--natural-foreign",
17
+ "--indent",
18
+ "2",
19
+ ]
20
+
21
+ with open(target_file, "w", encoding="utf-8") as outfile:
22
+ subprocess.run(["python", "manage.py", "dumpdata"] + arguments, stdout=outfile)
23
+
24
+ # Post process the JSON file when defined
25
+ if post_json_processing is not None:
26
+ post_json_processing(target_file)
@@ -0,0 +1,68 @@
1
+ import sys
2
+ from os import mkdir
3
+ from os.path import basename, exists, join
4
+
5
+ from botocore.exceptions import EndpointConnectionError
6
+ from nwon_baseline import directory_helper, print_helper
7
+
8
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
9
+
10
+
11
+ def write_storage_data_for_seeding(environment: str):
12
+ """
13
+ Copy files stored in the storage for all defined models into a folder. From there
14
+ we take them during seeding.
15
+ """
16
+
17
+ print_helper.print_green(f"Writing seed files for {environment} environment")
18
+
19
+ for mapped in NWON_DJANGO_SEED_SETTINGS.file_directories_for_environment(
20
+ environment
21
+ ):
22
+ clean_directory = False
23
+
24
+ if not exists(mapped.path):
25
+ mkdir(mapped.path)
26
+ else:
27
+ clean_directory = True
28
+
29
+ for model_instance in mapped.model.objects.all():
30
+ file = getattr(model_instance, mapped.file_key)
31
+
32
+ if file:
33
+ try:
34
+ file_content = file.read()
35
+
36
+ """
37
+ We delay cleaning directory until we are sure that we have a
38
+ connection to the S3
39
+ """
40
+ if clean_directory:
41
+ directory_helper.clean_directory(mapped.path)
42
+ clean_directory = False
43
+
44
+ file_name: str = basename(file.name)
45
+ target_file_name = (
46
+ file_name
47
+ if file_name.startswith(str(model_instance.pk))
48
+ else f"{model_instance.pk}_{file_name}"
49
+ )
50
+
51
+ target_file_path = join(mapped.path, target_file_name)
52
+
53
+ with open(target_file_path, "wb+") as target_file:
54
+ target_file.write(file_content)
55
+
56
+ print_helper.print_blue(
57
+ f"Wrote file for {mapped.model.__name__} with pk "
58
+ + f"{model_instance.pk} to {target_file_path}."
59
+ )
60
+ except EndpointConnectionError:
61
+ print_helper.print_error("Could not connect to S3. Exiting 💣")
62
+ sys.exit()
63
+ except FileNotFoundError:
64
+ print_helper.print_error(
65
+ f"Could not read file {file.name} in "
66
+ + f"{mapped.model.__name__} with pk "
67
+ + str(model_instance.pk)
68
+ )
@@ -0,0 +1,31 @@
1
+ from typing import Optional, Type
2
+
3
+ from django.db.models import Model
4
+ from nwon_baseline import directory_helper
5
+
6
+ from nwon_django_seeding.helper.parse_info_from_seed_file_name import (
7
+ parse_info_from_seed_file_name,
8
+ )
9
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
10
+
11
+
12
+ def file_for_model_class(
13
+ model_class: Type[Model], environment: str, app_name: Optional[str] = None
14
+ ) -> str | None:
15
+ """
16
+ Get the seed file path for a model class
17
+ """
18
+
19
+ if not app_name:
20
+ app_name = NWON_DJANGO_SEED_SETTINGS.default_app_name
21
+
22
+ directories = NWON_DJANGO_SEED_SETTINGS.directories_for_environment(environment)
23
+ for directory in [directories.default_directory, directories.environment_directory]:
24
+ file_paths = directory_helper.file_paths_in_directory(directory, ["json"])
25
+
26
+ for file in file_paths:
27
+ model_name, _, _ = parse_info_from_seed_file_name(file, app_name)
28
+ if model_name == model_class.__name__.lower():
29
+ return file
30
+
31
+ return None
@@ -0,0 +1,108 @@
1
+ import copy
2
+ from typing import Any, Dict, Type
3
+
4
+ from django.core.management import call_command
5
+ from django.db import transaction
6
+ from django.db.models import Model
7
+ from django.db.models.signals import post_save
8
+ from nwon_baseline import directory_helper, print_helper
9
+ from nwon_django_toolbox.signals import disable_signals, enable_signals
10
+
11
+ from nwon_django_seeding.helper.load_seeds_from_file import load_seeds_from_file
12
+ from nwon_django_seeding.helper.parse_info_from_seed_file_name import (
13
+ parse_info_from_seed_file_name,
14
+ )
15
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
16
+
17
+ """
18
+ This map configures our custom seeding logic for specific models.
19
+
20
+ It maps a model class to a dictionary that contains the field names in the database
21
+ and maps them to the field names in the seed file.
22
+ """
23
+ CUSTOM_SEED_MODEL_MAP: Dict[Type[Model], Dict[str, str]] = {}
24
+
25
+
26
+ def load_seed_data(environment: str, app_name: str = "nwon"):
27
+ """
28
+ Loads seed files for a specific environment.
29
+
30
+ We always load the default seed files first and then the environment specific ones.
31
+ """
32
+
33
+ directories = NWON_DJANGO_SEED_SETTINGS.directories_for_environment(environment)
34
+
35
+ """ Disable signals for the following models in order to prevent
36
+ race conditions between seeding and signals """
37
+ disable_signals_for_models = (
38
+ NWON_DJANGO_SEED_SETTINGS.disable_signals_before_seeding_model
39
+ )
40
+
41
+ for directory in [directories.default_directory, directories.environment_directory]:
42
+ print_helper.print_green(f"Loading seed files from {directory}")
43
+
44
+ file_paths = directory_helper.file_paths_in_directory(directory, ["json"])
45
+ file_paths.sort()
46
+
47
+ for file in file_paths:
48
+ print_helper.print_green(f"Loading seed from {file}")
49
+
50
+ # Make sure to commit all pending transactions before loading the seed
51
+ if transaction.get_autocommit():
52
+ transaction.commit()
53
+
54
+ model_name, app_name_to_use, _ = parse_info_from_seed_file_name(
55
+ file, app_name
56
+ )
57
+ disable_signal = model_name in [
58
+ m.__name__.lower() for m in disable_signals_for_models
59
+ ]
60
+
61
+ if disable_signal:
62
+ disable_signals([post_save])
63
+
64
+ __load_seed_file(file, app_name_to_use)
65
+
66
+ # Commit all pending transactions stemming from the seed file
67
+ if transaction.get_autocommit():
68
+ transaction.commit()
69
+
70
+ # reenable signals if they were disabled
71
+ if disable_signal:
72
+ enable_signals([post_save])
73
+
74
+
75
+ def __load_seed_file(file: str, app: str):
76
+ """
77
+ For most seed files we just use the builtin Django mechanism to load the data.
78
+
79
+ But for some models we create/update the data manually by using get_or_create in
80
+ order to prevent constraint clashes.
81
+ """
82
+
83
+ _, app_name_to_use, model_class = parse_info_from_seed_file_name(file, app)
84
+
85
+ if model_class in NWON_DJANGO_SEED_SETTINGS.custom_seed_map:
86
+ seed_model_map = NWON_DJANGO_SEED_SETTINGS.custom_seed_map[model_class]
87
+ seeds = load_seeds_from_file(file)
88
+
89
+ for seed in seeds:
90
+ fields = copy.deepcopy(seed.fields)
91
+
92
+ for key_in_seed_file in seed_model_map.values():
93
+ del fields[key_in_seed_file]
94
+
95
+ find_by_keys: Dict[str, Any] = {}
96
+ for database_field_name, key_in_seed_file in seed_model_map.items():
97
+ find_by_keys = {
98
+ **find_by_keys,
99
+ database_field_name: seed.fields[key_in_seed_file],
100
+ }
101
+
102
+ model_class.objects.update_or_create(**find_by_keys, defaults={**fields})
103
+ else:
104
+ call_command(
105
+ "loaddata",
106
+ file,
107
+ app_label=app_name_to_use,
108
+ )
@@ -0,0 +1,18 @@
1
+ import json
2
+ from typing import List
3
+
4
+ from nwon_django_seeding.typings import DjangoSeed
5
+
6
+
7
+ def load_seeds_from_file(json_path: str) -> List[DjangoSeed]:
8
+ return_value: List[DjangoSeed] = []
9
+
10
+ with open(json_path, "r", encoding="utf-8") as file:
11
+ json_string = file.read()
12
+ json_data = json.loads(json_string)
13
+
14
+ if isinstance(json_data, list):
15
+ for data in json_data:
16
+ return_value.append(DjangoSeed.model_validate(data))
17
+
18
+ return return_value
@@ -0,0 +1,42 @@
1
+ import os
2
+ from typing import Optional, Tuple, Type
3
+
4
+ from django.apps import apps
5
+ from django.db.models import Model
6
+
7
+ from nwon_django_seeding.settings import NWON_DJANGO_SEED_SETTINGS
8
+
9
+
10
+ def parse_info_from_seed_file_name(
11
+ file_path: str, default_app_label: Optional[str] = None
12
+ ) -> Tuple[str, str, Type[Model]]:
13
+ """
14
+ Get some information the file name of a seed file.
15
+
16
+ The file name structure is:
17
+ <index>_<model_name>.json or <index>_<model_name>__<app_name>.json
18
+
19
+ If the app_name is not specified the default_app_label is used.
20
+ """
21
+
22
+ if not default_app_label:
23
+ default_app_label = NWON_DJANGO_SEED_SETTINGS.default_app_name
24
+
25
+ base_name = os.path.basename(file_path)
26
+ base_name_without_suffix = base_name.split(".")[0]
27
+ model_name = (
28
+ "_".join(base_name_without_suffix.split("_")[1:])
29
+ if "_" in base_name_without_suffix
30
+ else base_name_without_suffix
31
+ )
32
+
33
+ if "__" in model_name:
34
+ splitted_model_name = model_name.split("__")
35
+ model_name = splitted_model_name[0]
36
+ app_name_to_use = splitted_model_name[1]
37
+ else:
38
+ app_name_to_use = default_app_label
39
+
40
+ model_class = apps.get_model(app_name_to_use.lower(), model_name)
41
+
42
+ return (model_name.lower(), app_name_to_use.lower(), model_class)
@@ -0,0 +1,21 @@
1
+ import json
2
+
3
+ from nwon_django_seeding.helper.load_seeds_from_file import load_seeds_from_file
4
+
5
+
6
+ def set_key_to_none_in_seed_file(json_path: str, key: str):
7
+ """
8
+ Sets a key to None (aka. null in JSON) in the given seed file.
9
+ """
10
+
11
+ return_value = []
12
+ seeds = load_seeds_from_file(json_path)
13
+
14
+ for seed in seeds:
15
+ if key in seed.fields:
16
+ seed.fields[key] = None
17
+
18
+ return_value.append(seed.model_dump())
19
+
20
+ with open(json_path, "w", encoding="utf-8") as file:
21
+ file.write(json.dumps(return_value, indent=2))
@@ -0,0 +1,30 @@
1
+ """
2
+ Not exactly a solution we want to use for disabling our validation in the context of
3
+ seeding.
4
+
5
+ Despite some effort I could not make it work in any other way 😔
6
+ """
7
+
8
+ from os import environ, getenv
9
+
10
+ KEY = "SEEDING_RUNNING"
11
+ VALUE_IS_RUNNING = "yes"
12
+
13
+
14
+ def set_seeding_is_running() -> None:
15
+ """Set seeding is running to True"""
16
+
17
+ environ[KEY] = VALUE_IS_RUNNING
18
+
19
+
20
+ def set_seeding_is_not_running() -> None:
21
+ """Set seeding is running to False"""
22
+
23
+ if KEY in environ:
24
+ del environ[KEY]
25
+
26
+
27
+ def is_seeding_running() -> bool:
28
+ """Is a seeding operation ongoing?"""
29
+
30
+ return getenv(KEY) == VALUE_IS_RUNNING
@@ -0,0 +1,56 @@
1
+ from typing import List
2
+
3
+ from django.conf import settings
4
+ from pydantic import ValidationError
5
+
6
+ from nwon_django_seeding.typings import (
7
+ ModelFolderMapping,
8
+ NWONDjangoSeedingSettings,
9
+ SeedDirectories,
10
+ )
11
+
12
+
13
+ def dummy(environment: str) -> SeedDirectories:
14
+ return SeedDirectories(default_directory="", environment_directory="")
15
+
16
+
17
+ def dummy_files(environment: str) -> List[ModelFolderMapping]:
18
+ return []
19
+
20
+
21
+ def set_settings() -> NWONDjangoSeedingSettings:
22
+ """
23
+ Parse Settings from Django settings
24
+ """
25
+
26
+ if not hasattr(settings, "NWON_DJANGO_SEEDING"):
27
+ return NWONDjangoSeedingSettings(
28
+ disable_signals_before_seeding_model=[],
29
+ custom_seed_map={},
30
+ directories_for_environment=dummy,
31
+ file_directories_for_environment=dummy_files,
32
+ default_app_name="nwon",
33
+ )
34
+
35
+ if isinstance(settings.NWON_DJANGO, NWONDjangoSeedingSettings):
36
+ return settings.NWON_DJANGO
37
+
38
+ if not isinstance(settings.NWON_DJANGO, dict):
39
+ raise Exception(
40
+ "The NWON_DJANGO_SEEDING settings need to be of type dict or NWONDjangoSeedingSettings"
41
+ )
42
+
43
+ try:
44
+ return NWONDjangoSeedingSettings.model_validate(settings.NWON_DJANGO)
45
+ except ValidationError as exception:
46
+ raise Exception(
47
+ f"Could not parse the NWON_DJANGO settings: {str(exception)}"
48
+ ) from exception
49
+
50
+
51
+ NWON_DJANGO_SEED_SETTINGS = set_settings()
52
+ """
53
+ Settings used withing the NWON-django-seeding package
54
+ """
55
+
56
+ __all__ = ["NWON_DJANGO_SEED_SETTINGS"]
@@ -0,0 +1,83 @@
1
+ from typing import Callable, Dict, List, Optional, Type, Union
2
+
3
+ from django.db.models import Model
4
+ from django.db.models.base import ModelBase
5
+ from nwon_baseline.typings import AnyDict
6
+ from pydantic import AliasGenerator, BaseModel, ConfigDict, Field
7
+ from pydantic.alias_generators import to_camel
8
+
9
+
10
+ class ModelFolderMapping(BaseModel):
11
+ """Defines how the files for a model will be saved for usage in seeding"""
12
+
13
+ model: Type[Model]
14
+ path: str
15
+ """ Path to the directory where the files gonna be saved """
16
+ file_key: str
17
+ """ Model field where the file is stored """
18
+
19
+
20
+ class SeedDirectories(BaseModel):
21
+ default_directory: str
22
+ environment_directory: str
23
+
24
+
25
+ class NWONDjangoSeedingSettings(BaseModel):
26
+ disable_signals_before_seeding_model: List[Type[Model]] = Field(
27
+ description="Model for which signals should be disabled before seeding. Reenabled after"
28
+ )
29
+ custom_seed_map: Dict[Type[Model], Dict[str, str]] = Field(
30
+ description="This map configures our custom seeding logic for specific models. It maps a model class to a dictionary that contains the field names in the database and maps them to the field names in the seed file."
31
+ )
32
+ directories_for_environment: Callable[[str], SeedDirectories] = Field(
33
+ description=""
34
+ )
35
+ file_directories_for_environment: Callable[[str], List[ModelFolderMapping]] = Field(
36
+ description=""
37
+ )
38
+ default_app_name: str = Field(description="The default app name for the seed files")
39
+
40
+ model_config = ConfigDict(
41
+ alias_generator=AliasGenerator(validation_alias=to_camel),
42
+ populate_by_name=True,
43
+ extra="forbid",
44
+ )
45
+
46
+
47
+ class DjangoSeed(BaseModel):
48
+ """This is the structure of the Django seed data."""
49
+
50
+ model: str
51
+ pk: int
52
+ fields: AnyDict
53
+
54
+
55
+ class ModelSeed(BaseModel):
56
+ """
57
+ This is a model that should be seeded and needs some extra JSON post processing.
58
+
59
+ This was necessary to cover seeds that have circular dependencies. This makes
60
+ it possible to seed this model first without the reference to another model and
61
+ only after creating the other model the full model with the relation.
62
+ """
63
+
64
+ model: Union[Type[Model], Type[ModelBase]]
65
+ post_json_processing: Callable[[str], None]
66
+
67
+ model_config = ConfigDict(
68
+ arbitrary_types_allowed=True,
69
+ )
70
+
71
+
72
+ class SeedSet(BaseModel):
73
+ """
74
+ A set of models that logically belong together. This is mainly used to group models.
75
+ """
76
+
77
+ models: List[Union[Type[Model], Type[ModelBase], ModelSeed]]
78
+ is_default_seed: Optional[bool] = Field(default=False)
79
+ """ If true this models will always be put in the default folder """
80
+
81
+ model_config = ConfigDict(
82
+ arbitrary_types_allowed=True,
83
+ )
@@ -0,0 +1,38 @@
1
+ [tool.poetry]
2
+ authors = ["Reik Stiebeling <reik.stiebeling@nwon.de>"]
3
+ description = "A Django seeding solution build on top of fixtures"
4
+ homepage = "https://nwon.de"
5
+ include = ["README.md"]
6
+ license = "MIT"
7
+ name = "nwon_django_seeding"
8
+ readme = "README.md"
9
+ repository = "https://gitlab.com/nwon-group/nwon-tooling/pypi-packages/nwon-django-seeding.git"
10
+ version = "1.0.1"
11
+
12
+ [tool.poetry.dependencies]
13
+ python = ">=3.8,<4.0"
14
+
15
+ django = ">=3.0"
16
+ nwon-baseline = "^0.2.15"
17
+ pydantic = ">=2.1.0"
18
+ nwon-django-toolbox = "^0.6.7"
19
+ boto3 = "^1.34.128"
20
+
21
+ [tool.poetry.dev-dependencies]
22
+ mypy = "^1.2.0"
23
+ rope = "^1.7.0" # refactoring
24
+ ruff = "^0.4.4"
25
+
26
+ # Tests
27
+ pytest = "^7.2.2"
28
+
29
+ # Stubs for typing
30
+ django-stubs = "^1.16.0"
31
+
32
+
33
+ [tool.poetry.scripts]
34
+ publish = "scripts.publish:publish"
35
+
36
+ [build-system]
37
+ build-backend = "poetry.core.masonry.api"
38
+ requires = ["poetry-core>=1.0.0"]