Skip to content

Commit 074e22a

Browse files
authored
Merge pull request #7 from jedymatt/v0.4.x
V0.4.x
2 parents e4f398c + 8eaf11a commit 074e22a

File tree

9 files changed

+115
-28
lines changed

9 files changed

+115
-28
lines changed

README.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,29 @@ Sqlalchemy seeder that supports nested relationships.
99

1010
## Installation
1111

12+
Default installation
13+
1214
```commandline
1315
pip install sqlalchemyseed
1416
```
1517

16-
### Dependencies
18+
When using yaml to loading entities from yaml files.
19+
Execute this command to install necessary dependencies
20+
21+
```commandline
22+
pip install sqlalchemyseed[yaml]
23+
```
24+
25+
## Dependencies
26+
27+
Required
1728

1829
- SQAlchemy>=1.4.0
1930

31+
Optional
32+
33+
- PyYAML>=5.4.0
34+
2035
## Getting Started
2136

2237
```python

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
sqlalchemy>=1.4.0
2-
jsonschema>=3.2.0
2+
pyyaml>=5.4.0

setup.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
22

3+
from readme_renderer import markdown
34
from setuptools import setup
45

56
with open("README.md", "r", encoding="utf-8") as fh:
@@ -10,20 +11,27 @@
1011
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
1112
VERSION = re.search(pattern, f.read(), re.MULTILINE).group(1)
1213

14+
15+
extras_require = {
16+
'yaml': ['PyYAML>=5.4.0']
17+
}
18+
19+
1320
setup(
1421
name='sqlalchemyseed',
1522
author='jedymatt',
1623
url='https://github.com/jedymatt/sqlalchemyseed',
17-
long_description=LONG_DESCRIPTION,
24+
long_description=markdown.render(LONG_DESCRIPTION),
1825
long_description_content_type='text/markdown',
1926
description='SQLAlchemy seeder.',
2027
version=VERSION,
2128
license='MIT',
2229
packages=['sqlalchemyseed'],
23-
package_data={'sqlalchemyseed': ['res/*']},
30+
# package_data={'sqlalchemyseed': ['res/*']},
2431
install_requires=['SQLAlchemy>=1.4.0'],
32+
extras_require=extras_require,
2533
python_requires='>=3.6.0',
26-
keywords='sqlalchemy seed seeder json',
34+
keywords='sqlalchemy seed seeder json yaml',
2735
project_urls={
2836
'Source': 'https://github.com/jedymatt/sqlalchemyseed',
2937
'Tracker': 'https://github.com/jedymatt/sqlalchemyseed/issues',

sqlalchemyseed/__init__.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
from .seeder import ClassRegistry
22
from .seeder import HybridSeeder
33
from .seeder import Seeder
4-
from .seeder import load_entities_from_json
4+
from .loader import load_entities_from_json
5+
from .loader import load_entities_from_yaml
56

6-
__version__ = '0.4.1'
7+
__version__ = '0.4.2.dev1'
8+
9+
10+
if __name__ == '__main__':
11+
pass

sqlalchemyseed/loader.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import json
2+
import sys
3+
4+
try:
5+
# relative import
6+
from . import validator
7+
except ImportError:
8+
import validator
9+
10+
11+
try:
12+
import yaml
13+
except ModuleNotFoundError:
14+
pass
15+
16+
17+
def load_entities_from_json(json_filepath):
18+
try:
19+
with open(json_filepath, 'r') as f:
20+
entities = json.loads(f.read())
21+
except FileNotFoundError as error:
22+
raise FileNotFoundError(error)
23+
24+
validator.SchemaValidator.validate(entities)
25+
26+
return entities
27+
28+
29+
def load_entities_from_yaml(yaml_filepath):
30+
if 'yaml' not in sys.modules:
31+
raise ModuleNotFoundError(
32+
'PyYAML is not installed and is required to run this function. '
33+
'To use this function, py -m pip install "sqlalchemyseed[yaml]"'
34+
)
35+
36+
try:
37+
with open(yaml_filepath, 'r') as f:
38+
entities = yaml.load(f.read(), Loader=yaml.SafeLoader)
39+
except FileNotFoundError as error:
40+
raise FileNotFoundError(error)
41+
42+
validator.SchemaValidator.validate(entities)
43+
44+
return entities
45+
46+
47+
if __name__ == '__main__':
48+
load_entities_from_yaml('tests/res/data.yaml')

sqlalchemyseed/seeder.py

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,16 @@
11
import importlib
2-
import json
32
from inspect import isclass
43

54
import sqlalchemy.orm
6-
from sqlalchemy import Table, column, inspect, select, table, text
5+
from sqlalchemy import inspect
76
from sqlalchemy.exc import NoInspectionAvailable
87
from sqlalchemy.orm import ColumnProperty, RelationshipProperty
9-
from sqlalchemy.orm.relationships import foreign
108

11-
from . import validator
12-
13-
14-
def load_entities_from_json(json_filepath):
15-
try:
16-
with open(json_filepath, 'r') as f:
17-
entities = json.loads(f.read())
18-
except FileNotFoundError as error:
19-
raise FileNotFoundError(error)
20-
21-
validator.SchemaValidator.validate(entities)
22-
23-
return entities
9+
try:
10+
# relative import
11+
from . import validator
12+
except ImportError:
13+
import validator
2414

2515

2616
class ClassRegistry:
@@ -218,7 +208,7 @@ def instantiate_obj(self, class_path, kwargs, key_is_data, parent, parent_attr_n
218208
class_attr = getattr(parent.__class__, parent_attr_name)
219209
if isinstance(class_attr.property, ColumnProperty):
220210
raise TypeError('invalid class attribute type')
221-
211+
222212
obj = class_(**filtered_kwargs)
223213
self._session.add(obj)
224214
# self._session.flush()
@@ -229,17 +219,17 @@ def instantiate_obj(self, class_path, kwargs, key_is_data, parent, parent_attr_n
229219
if isinstance(class_attr.property, ColumnProperty):
230220
foreign_key = str(
231221
list(getattr(parent.__class__, parent_attr_name).foreign_keys)[0].column)
232-
foreign_key_id=self._query_instance_id(
222+
foreign_key_id = self._query_instance_id(
233223
class_, filtered_kwargs, foreign_key)
234224
return foreign_key_id
235225

236226
return self._session.query(class_).filter_by(**filtered_kwargs).one()
237227

238228
def _query_instance_id(self, class_, filtered_kwargs, foreign_key):
239229
# .id should be the foreign key
240-
arr=foreign_key.rsplit('.')
241-
column_name=arr[len(arr)-1]
230+
arr = foreign_key.rsplit('.')
231+
column_name = arr[len(arr)-1]
242232

243-
result=self.session.query(
233+
result = self.session.query(
244234
getattr(class_, column_name)).filter_by(**filtered_kwargs).one()
245235
return getattr(result, column_name)
File renamed without changes.

tests/res/data.yaml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
- model: tests.models.Employee
2+
data:
3+
name: Juan Dela Cruz
4+
- model: tests.models.Company
5+
data:
6+
name: Carte

tests/test_loader.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import unittest
2+
3+
from sqlalchemyseed import load_entities_from_json, load_entities_from_yaml
4+
5+
6+
class TestLoader(unittest.TestCase):
7+
def test_load_entities_from_json(self):
8+
entities = load_entities_from_json('tests/res/data.json')
9+
10+
self.assertEqual(len(entities), 6)
11+
12+
def test_load_entities_from_yaml(self):
13+
entities = load_entities_from_yaml('tests/res/data.yaml')
14+
print(entities)
15+
self.assertEqual(len(entities), 2)

0 commit comments

Comments
 (0)