Skip to content

Commit

Permalink
rebase fabrics coordinators
Browse files Browse the repository at this point in the history
  • Loading branch information
KonstantinRaikhert committed Jul 12, 2023
1 parent e9ceb80 commit b707a92
Show file tree
Hide file tree
Showing 7 changed files with 110 additions and 181 deletions.
6 changes: 0 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
# To generate factories with coordinators info use command:
# 'make generate_contacts amount=5', where 'amount' is <int> value
# of factories you want to generate, e.g. 5.
generate_contacts:
python src/db_fixtures/factories/contact_factories.py ${amount}

# for start mySQL container:
rundb:
docker compose -f infra/dev/docker-compose.local.yaml up -d
Expand Down
12 changes: 12 additions & 0 deletions src/db_fixtures/factories/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
__all__ = [
"generate_dict_factory",
"START_COMMON_TEMPLATE",
"MAIN_COORDINATORS_TEMPLATE",
"END_COMMON_TEMPLATE",
]
from .service import generate_dict_factory
from .templates import (
END_COMMON_TEMPLATE,
MAIN_COORDINATORS_TEMPLATE,
START_COMMON_TEMPLATE,
)
138 changes: 39 additions & 99 deletions src/db_fixtures/factories/contact_factories.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,32 @@
import sys

from factory import Factory, Faker, SubFactory
from service import (
create_html_file,
factory_to_html_text,
generate_dict_factory,
from factories.service import generate_dict_factory
from factories.templates import (
END_COMMON_TEMPLATE,
MAIN_COORDINATORS_TEMPLATE,
START_COMMON_TEMPLATE,
)
from factory import Factory, Faker, LazyAttribute, SubFactory


class Region:
"""Model to make Region factories."""
class Contacts:
"""Model to make contacts factories."""

def __init__(self, city, coordinator):
def __init__(self, email: str, phone_number: str, telegram: str) -> None:
"""To initialize."""
self.city = city
self.coordinator = coordinator
self.email = email
self.phone_number = phone_number
self.telegram = telegram


class Coordinator:
"""Model to make Coordinator factories."""

def __init__(self, name, contacts):
def __init__(self, name: str, region: str, contacts: Contacts) -> None:
"""To initialize."""
self.name = name
self.region = region
self.contacts = contacts


class Contacts:
"""Model to make contacts factories."""

def __init__(self, email, phone_number):
"""To initialize."""
self.email = email
self.phone_number = phone_number


class RegionCoordinator:
"""Class-helper to make nested dict."""

pass


class ContactsFactory(Factory):
"""Creating Contacts factory."""

Expand All @@ -51,7 +37,7 @@ class Meta:

email = Faker("email", locale="ru_RU")
phone_number = Faker("phone_number", locale="ru_RU")
telegram = Faker("first_name")
telegram = LazyAttribute(lambda obj: f'@{obj.email.split("@")[0]}')


class CoordinatorFactory(Factory):
Expand All @@ -63,79 +49,33 @@ class Meta:
model = Coordinator

name = Faker("name", locale="ru_RU")
region = Faker("region", locale="ru_RU")
contacts = SubFactory(ContactsFactory)


class RegionFactory(Factory):
"""Creating Regions factory."""

class Meta:
"""Connection to Region Model."""

model = Region

city = Faker("region", locale="ru_RU")
coordinator = SubFactory(CoordinatorFactory)
def generate_coordinators(count: int) -> str:
"""Generate html string of coordinators."""
coordinators_data = {}
for i in range(count):
coordinators_data[i] = generate_dict_factory(CoordinatorFactory)()

list_of_main_templates = []
for coordinator in coordinators_data.values():
contacts = coordinator.get("contacts")
list_of_main_templates.append(
MAIN_COORDINATORS_TEMPLATE.format(
region=coordinator.get("region"),
name=coordinator.get("name"),
email=contacts.get("email"),
phone=contacts.get("phone_number"),
telegram=contacts.get("telegram"),
)
)
result = f"{START_COMMON_TEMPLATE}{''.join(list_of_main_templates)}{END_COMMON_TEMPLATE}"
return result


if __name__ == "__main__":
NUMBER = int(sys.argv[1])

class RegionCoordinatorFactory(Factory):
"""Creating nested factories."""

class Meta:
"""Connection to RegionCoordinator Model."""

model = RegionCoordinator

for i in range(1, NUMBER + 1):
locals()[f"region_{i}"] = SubFactory(RegionFactory)
del i

factory_to_dict = generate_dict_factory(RegionCoordinatorFactory)
data_text = factory_to_html_text(factory_to_dict())

create_html_file(filename="coordinator_contacts.html", data=data_text)

def factory_to_html(data):
"""Create HTML template with coordinator's info."""
filename = "coordinator_contacts.html"
start_template = (
'<table style="border-collapse: collapse;'
' width: 100.303%; height: 112px;">\n'
" <tbody>\n"
)
main_template = (
' <tr style="height: 16px;">\n'
' <td style="width: 20%;'
' height: 16px;">{region}</td>\n'
' <td style="width: 20%;'
' height: 16px;">{coord_name}</td>\n'
' <td style="width: 20%;'
' height: 16px;">{email}</td>\n'
' <td style="width: 20%;'
' height: 16px;">{phone}</td>\n'
' <td style="width: 20%;'
' height: 16px;">@{telegram}</td>\n'
" </tr>\n"
)
end_template = " </tbody>\n" "</table>\n"

with open(filename, "w", encoding="utf-8") as tags:
tags.write(start_template)
for contact in data.values():
coordinator = contact.get("coordinator")
contacts = coordinator.get("contacts")
tags.write(
main_template.format(
region=contact.get("city"),
coord_name=coordinator.get("name"),
email=contacts.get("email"),
phone=contacts.get("phone_number"),
telegram=contacts.get("telegram").lower(),
)
)
tags.write(end_template)

factory_to_html(factory_to_dict())
count = int(input("Необходимое количество координаторов: "))
coordinators = generate_coordinators(count=count)
print(coordinators)
62 changes: 14 additions & 48 deletions src/db_fixtures/factories/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,24 @@
def generate_dict_factory(factory):
"""To transform Factory objects into dict."""

def stub_is_list(stub: StubObject) -> bool:
try:
return all(k.isdigit() for k in stub.__dict__.keys())
except AttributeError:
return False

def convert_dict_from_stub(stub: StubObject) -> Dict[str, Any]:
stub_dict = stub.__dict__
for key, value in stub_dict.items():
if isinstance(value, StubObject):
stub_dict[key] = convert_dict_from_stub(value)
stub_dict[key] = (
[
convert_dict_from_stub(v)
for v in value.__dict__.values()
]
if stub_is_list(value)
else convert_dict_from_stub(value)
)
return stub_dict

def dict_factory(factory, **kwargs):
Expand All @@ -20,50 +33,3 @@ def dict_factory(factory, **kwargs):
return stub_dict

return partial(dict_factory, factory)


# def factory_to_html_text(data) -> str:
# """Create HTML template with coordinator's info."""
# filename = "coordinator_contacts.html"
# start_template = (
# '<table style="border-collapse: collapse;'
# ' width: 100.303%; height: 112px;">\n'
# " <tbody>\n"
# )
# main_template = (
# ' <tr style="height: 16px;">\n'
# ' <td style="width: 20%;'
# ' height: 16px;">{region}</td>\n'
# ' <td style="width: 20%;'
# ' height: 16px;">{coord_name}</td>\n'
# ' <td style="width: 20%;'
# ' height: 16px;">{email}</td>\n'
# ' <td style="width: 20%;'
# ' height: 16px;">{phone}</td>\n'
# ' <td style="width: 20%;'
# ' height: 16px;">@{telegram}</td>\n'
# " </tr>\n"
# )
# end_template = " </tbody>\n" "</table>\n"

# middle = []

# for contact in data.values():
# coordinator = contact.get("coordinator")
# contacts = coordinator.get("contacts")
# middle.append(
# main_template.format(
# region=contact.get("city"),
# coord_name=coordinator.get("name"),
# email=contacts.get("email"),
# phone=contacts.get("phone_number"),
# telegram=contacts.get("telegram").lower(),
# )
# )

# return start_template + "".join(middle) + end_template


# def create_html_file(filename: str, data: str) -> None:
# with open(filename, "w", encoding="utf-8") as tags:
# tags.write(data)
20 changes: 20 additions & 0 deletions src/db_fixtures/factories/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
START_COMMON_TEMPLATE = (
"<table style='border-collapse: collapse;"
" width: 100.303%; height: 112px;'>\n"
" <tbody>\n"
)
END_COMMON_TEMPLATE = " </tbody>\n" "</table>\n"
MAIN_COORDINATORS_TEMPLATE = (
" <tr style='height: 16px;'>\n"
" <td style='width: 20%;"
" height: 16px;'>{region}</td>\n"
" <td style='width: 20%;"
" height: 16px;'>{name}</td>\n"
" <td style='width: 20%;"
" height: 16px;'>{email}</td>\n"
" <td style='width: 20%;"
" height: 16px;'>{phone}</td>\n"
" <td style='width: 20%;"
" height: 16px;'>{telegram}</td>\n"
" </tr>\n"
)
12 changes: 10 additions & 2 deletions src/db_fixtures/filldb.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,14 @@ def create_database_tables(cursor: MySQLCursor) -> None:

def insert_into_db(cursor: MySQLCursor) -> None:
"""Insert data in table."""
cursor.execute(USE_DB)
cursor.execute(INSERT_COORDINATORS_QUERY)
try:
print("Наполнение таблицы тестовыми данными: ", end="")
cursor.execute(USE_DB)
cursor.execute(INSERT_COORDINATORS_QUERY)
except MySQLError as err:
print(err)
else:
print("OK")


def main():
Expand All @@ -83,6 +89,8 @@ def main():
create_database(cursor=cursor)
create_database_tables(cursor=cursor)
insert_into_db(cursor=cursor)
cursor.close()
conn.commit()


if __name__ == "__main__":
Expand Down
41 changes: 15 additions & 26 deletions src/db_fixtures/queries.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from factories.contact_factories import generate_coordinators

# To create a database and configure it:
DB_NAME = "krilya_dets1"
CREATE_DB = "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8mb4'".format(
Expand Down Expand Up @@ -37,29 +39,16 @@
") "
)

# INSERT_COORDINATORS_QUERY = f"INSERT INTO customers (ID, post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status) VALUES (%s, %s)"


ID = 17014
post_author = 1
post_date = "2023-06-28 17:00:18"
post_date_gmt = "2023-06-28 14:00:18"
post_content = "html"
post_title = "Бот контакты координаторов"
post_excerpt = None
post_status = "publish"
comment_status = "closed"
ping_status = "closed"
post_password = None
post_name = "bot-kontakty-koordinatorov"
to_ping = None
pinged = None
post_modified = "2023-07-02 22:31:45"
post_modified_gmt = "2023-07-02 19:31:45"
post_content_filtered = None
post_parent = 0
guid = "http://jetrai.online/?page_id=17014"
menu_order = 0
post_type = "page"
post_mime_type = None
comment_count = 0
# To insert test data into detfond_posts table
html_data = generate_coordinators(count=10)
INSERT_COORDINATORS_QUERY = (
"insert into detfond_posts ( `ID`, post_author, post_date, post_date_gmt, "
"post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, "
"post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, "
'guid, menu_order, post_type, post_mime_type, comment_count) values ( 2, 1, "2023-06-28 17:00:18", '
'"2023-06-28 14:00:18", "{}", "Бот контакты координаторов", 0, "publish", "closed", "closed", '
'0, "bot-kontakty-koordinatorov", 0, 0, "2023-07-02 22:31:4", "2023-07-02 19:31:45", 0, 0, '
'"http://jetrai.online/?page_id=17014", 0, "page", 0, 0); '.format(
html_data
)
)

0 comments on commit b707a92

Please sign in to comment.