Skip to content

Commit d20a72c

Browse files
committed
docs/feat: add models and views in MVC
1 parent 96a5c13 commit d20a72c

File tree

7 files changed

+148
-3
lines changed

7 files changed

+148
-3
lines changed

docs/en/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
4. [Request/Response](./requests_responses.md)
99
5. [i18n](./i18n_locales.md)
1010
6. [Security](./security.md)
11+
7. [MVC](./mvc.md)
1112

1213
## Additional materials
1314

docs/en/mvc.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# pyEchoNext / MVC Architecture
2+
3+
---
4+
5+
MVC stands for Model-View-Controller, an architectural pattern that divides an application into three logical components: the model, the View, and the controller.
6+
7+
The main idea of the MVC pattern is that each section of code has its own purpose. Part of the code contains application data, the other is responsible for how the user sees it, the latter controls its operation.
8+
9+
+ Model code **Model** stores data and associated logic, and anchors the structure of the application. That is, the programmer will determine the main components of the application using the template.
10+
+ The application's appearance code, **View**, consists of functions that are responsible for the interface and how the user interacts with it. Views are created based on data collected from the model.
11+
+ The controller code, **Controller**, links the model and view. It receives user input, interprets it and informs about the necessary changes. For example, sends commands to update state, such as saving a document.
12+
13+
---
14+
15+
[Contents](./index.md)
16+
17+

docs/ru/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
4. [Request/Response](./requests_responses.md)
99
5. [i18n](./i18n_locales.md)
1010
6. [Безопасность](./security.md)
11+
7. [MVC](./mvc.md)
1112

1213
## Дополнительные материалы
1314

docs/ru/mvc.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# pyEchoNext / MVC Architecture
2+
3+
---
4+
5+
MVC - Model-View-Controller, архитектурный паттерн, который разделяет приложение на три логических компонента: модель, View (представление) и контроллер.
6+
7+
Основная идея паттерна MVC в том, что у каждого раздела кода есть своя цель. Часть кода содержит данные приложения, друга отвечает за то, каким видит его пользователь, последняя управлеяет его работой.
8+
9+
+ Код модели **Model** хранит данные и связанную с ними логику, а также закрепляет структуру приложения. То есть программист по шаблону будет определять основные компоненты приложения.
10+
+ Код внешнего вида приложения, **View**, состоит из функций, которые отвечают за интерфейс и способы взаимодействия пользователя с ним. Представления создают на основе данных, собранных из модели.
11+
+ Код контроллера, **Controller**, связывает модель и представление. Он получает на вход пользовательский ввод, интепретирует его и информирует о необходимых изменениях. Например, отправляет команды для обновления состояния, таких как сохранение документа.
12+
13+
---
14+
15+
[Содержание](./index.md)
16+
17+

pyechonext/mvc/controllers.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# TODO: make controllers

pyechonext/mvc/models.py

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,86 @@
1-
from abc import ABC, abstractmethod
21
from typing import Any, Union
2+
from abc import ABC, abstractmethod
3+
from pyechonext.request import Request
4+
from pyechonext.response import Response
5+
6+
7+
class BaseModel(ABC):
8+
"""
9+
This class describes a base model.
10+
"""
11+
12+
@abstractmethod
13+
def create_response(self, *args, **kwargs) -> Response:
14+
"""
15+
Creates a response.
16+
17+
:param args: The arguments
18+
:type args: list
19+
:param kwargs: The keywords arguments
20+
:type kwargs: dictionary
21+
22+
:returns: response object
23+
:rtype: Response
24+
"""
25+
raise NotImplementedError
26+
27+
@abstractmethod
28+
def create_request(self, *args, **kwargs) -> Request:
29+
"""
30+
Creates a request.
31+
32+
:param args: The arguments
33+
:type args: list
34+
:param kwargs: The keywords arguments
35+
:type kwargs: dictionary
36+
37+
:returns: request object
38+
:rtype: Request
39+
"""
40+
raise NotImplementedError
41+
42+
43+
class PageModel(BaseView):
44+
"""
45+
This class describes a page model.
46+
"""
47+
48+
def __init__(self, request: Request, response: Response):
49+
"""
50+
Constructs a new instance.
51+
52+
:param request: The request
53+
:type request: Request
54+
:param response: The response
55+
:type response: Response
56+
"""
57+
self.request = request
58+
self.response = response
59+
60+
def create_response(self, *args, **kwargs) -> Response:
61+
"""
62+
Creates a response.
63+
64+
:param args: The arguments
65+
:type args: list
66+
:param kwargs: The keywords arguments
67+
:type kwargs: dictionary
68+
69+
:returns: response object
70+
:rtype: Response
71+
"""
72+
return Response(*args, **kwargs)
73+
74+
def create_request(self, *args, **kwargs) -> Request:
75+
"""
76+
Creates a request.
377
78+
:param args: The arguments
79+
:type args: list
80+
:param kwargs: The keywords arguments
81+
:type kwargs: dictionary
482
5-
class BaseView(ABC):
6-
def __init__(self)
83+
:returns: request object
84+
:rtype: Request
85+
"""
86+
return Request(*args, **kwargs)

pyechonext/mvc/views.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from abc import ABC, abstractmethod
2+
from typing import Union, Any, Optional
3+
from pyechonext.response import Response
4+
from pyechonext.request import Request
5+
from pyechonext.i18n_l10n import JSONi18nLoader
6+
7+
8+
class BaseView(ABC):
9+
@abstractmethod
10+
def render(self, request: Request, response: Response, *args, **kwargs):
11+
raise NotImplementedError
12+
13+
14+
class i18nView(BaseView):
15+
def render(self, data: str, i18n_loader: JSONi18nLoader, **kwargs):
16+
return i18n_loader.get_string(data, **kwargs)
17+
18+
19+
class PageView(BaseView):
20+
def render(self, data: Union[Response, Any], *args, **kwargs):
21+
if self.use_i18n:
22+
data = self.i18n_loader.get_string(data)
23+
24+
if isinstance(data, Response):
25+
return data
26+
else:
27+
response = Response(body=str(data), *args, **kwargs)
28+
return response

0 commit comments

Comments
 (0)