|
| 1 | +import json |
| 2 | +import os |
| 3 | +from typing import Dict, List, Callable, Union |
| 4 | + |
| 5 | +from loguru import logger |
| 6 | +from sqlalchemy.orm import Session |
| 7 | + |
| 8 | +from app.database.database import Base |
| 9 | +from app.database.models import Quote, Zodiac |
| 10 | +from app.internal import daily_quotes, zodiac |
| 11 | + |
| 12 | + |
| 13 | +def get_data_from_json(path: str) -> List[Dict[str, Union[str, int, None]]]: |
| 14 | + """This function reads all of the data from a specific JSON file. |
| 15 | + The json file consists of list of dictionaries""" |
| 16 | + try: |
| 17 | + with open(path, 'r') as f: |
| 18 | + json_content_list = json.load(f) |
| 19 | + except (IOError, ValueError): |
| 20 | + file_name = os.path.basename(path) |
| 21 | + logger.exception( |
| 22 | + f"An error occurred during reading of json file: {file_name}") |
| 23 | + return [] |
| 24 | + return json_content_list |
| 25 | + |
| 26 | + |
| 27 | +def is_table_empty(session: Session, table: Base) -> bool: |
| 28 | + return session.query(table).count() == 0 |
| 29 | + |
| 30 | + |
| 31 | +def load_data( |
| 32 | + session: Session, path: str, |
| 33 | + table: Base, object_creator_function: Callable) -> None: |
| 34 | + """This function loads the specific data to the db, |
| 35 | + if it wasn't already loaded""" |
| 36 | + if not is_table_empty(session, table): |
| 37 | + return None |
| 38 | + json_objects_list = get_data_from_json(path) |
| 39 | + objects = [ |
| 40 | + object_creator_function(json_object) |
| 41 | + for json_object in json_objects_list] |
| 42 | + session.add_all(objects) |
| 43 | + session.commit() |
| 44 | + |
| 45 | + |
| 46 | +def load_to_db(session) -> None: |
| 47 | + """This function loads all the data for features |
| 48 | + based on pre-defind json data""" |
| 49 | + load_data( |
| 50 | + session, 'app/resources/zodiac.json', |
| 51 | + Zodiac, zodiac.create_zodiac_object) |
| 52 | + load_data( |
| 53 | + session, 'app/resources/quotes.json', |
| 54 | + Quote, daily_quotes.create_quote_object) |
| 55 | + """The quotes JSON file content is copied from the free API: |
| 56 | + 'https://type.fit/api/quotes'. I saved the content so the API won't be |
| 57 | + called every time the app is initialized.""" |
0 commit comments