Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
python-patterns/patterns/structural/mvc.py at master · faif/python-patterns · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
See all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
faif
python-patterns
Repository navigation
Code
Issues
9
(9)
Pull requests
4
(4)
Actions
Projects
Wiki
Security and quality
Insights
More
items
Files
Expand file tree
master
Breadcrumbs
python-patterns
/
patterns
/
structural
/
mvc.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
216 lines (167 loc) · 5.98 KB
master
Breadcrumbs
python-patterns
/
patterns
/
structural
/
mvc.py
Copy path
Top
File metadata and controls
Code
Blame
216 lines (167 loc) · 5.98 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
*TL;DR
Separates data in GUIs from the ways it is presented, and accepted.
"""
from
abc
import
ABC
,
abstractmethod
from
inspect
import
signature
from
sys
import
argv
from
typing
import
Any
class
Model
(
ABC
):
"""The Model is the data layer of the application."""
@
abstractmethod
def
__iter__
(
self
)
->
Any
:
pass
@
abstractmethod
def
get
(
self
,
item
:
str
)
->
dict
:
"""Returns an object with a .items() call method
that iterates over key,value pairs of its information."""
pass
@
property
@
abstractmethod
def
item_type
(
self
)
->
str
:
pass
class
ProductModel
(
Model
):
"""The Model is the data layer of the application."""
class
Price
(
float
):
"""A polymorphic way to pass a float with a particular
__str__ functionality."""
def
__str__
(
self
)
->
str
:
return
f"
{
self
:.2f
}
"
products
=
{
"milk"
: {
"price"
:
Price
(
1.50
),
"quantity"
:
10
},
"eggs"
: {
"price"
:
Price
(
0.20
),
"quantity"
:
100
},
"cheese"
: {
"price"
:
Price
(
2.00
),
"quantity"
:
10
},
}
item_type
=
"product"
def
__iter__
(
self
)
->
Any
:
yield
from
self
.
products
def
get
(
self
,
product
:
str
)
->
dict
:
try
:
return
self
.
products
[
product
]
except
KeyError
as
e
:
raise
KeyError
(
str
(
e
)
+
" not in the model's item list."
)
class
View
(
ABC
):
"""The View is the presentation layer of the application."""
@
abstractmethod
def
show_item_list
(
self
,
item_type
:
str
,
item_list
:
list
)
->
None
:
pass
@
abstractmethod
def
show_item_information
(
self
,
item_type
:
str
,
item_name
:
str
,
item_info
:
dict
)
->
None
:
"""Will look for item information by iterating over key,value pairs
yielded by item_info.items()"""
pass
@
abstractmethod
def
item_not_found
(
self
,
item_type
:
str
,
item_name
:
str
)
->
None
:
pass
class
ConsoleView
(
View
):
"""The View is the presentation layer of the application."""
def
show_item_list
(
self
,
item_type
:
str
,
item_list
:
list
)
->
None
:
print
(
item_type
.
upper
()
+
" LIST:"
)
for
item
in
item_list
:
print
(
item
)
print
(
""
)
@
staticmethod
def
capitalizer
(
string
:
str
)
->
str
:
"""Capitalizes the first letter of a string and lowercases the rest."""
return
string
[
0
].
upper
()
+
string
[
1
:].
lower
()
def
show_item_information
(
self
,
item_type
:
str
,
item_name
:
str
,
item_info
:
dict
)
->
None
:
"""Will look for item information by iterating over key,value pairs"""
print
(
item_type
.
upper
()
+
" INFORMATION:"
)
printout
=
"Name: %s"
%
item_name
for
key
,
value
in
item_info
.
items
():
printout
+=
", "
+
self
.
capitalizer
(
str
(
key
))
+
": "
+
str
(
value
)
printout
+=
"
\n
"
print
(
printout
)
def
item_not_found
(
self
,
item_type
:
str
,
item_name
:
str
)
->
None
:
print
(
f'That
{
item_type
}
"
{
item_name
}
" does not exist in the records'
)
class
Controller
:
"""The Controller is the intermediary between the Model and the View."""
def
__init__
(
self
,
model_class
:
Model
,
view_class
:
View
)
->
None
:
self
.
model
:
Model
=
model_class
self
.
view
:
View
=
view_class
def
show_items
(
self
)
->
None
:
items
=
list
(
self
.
model
)
item_type
=
self
.
model
.
item_type
self
.
view
.
show_item_list
(
item_type
,
items
)
def
show_item_information
(
self
,
item_name
:
str
)
->
None
:
"""
Show information about a {item_type} item.
:param str item_name: the name of the {item_type} item to show information about
"""
item_type
:
str
=
self
.
model
.
item_type
try
:
item_info
:
dict
=
self
.
model
.
get
(
item_name
)
except
Exception
:
self
.
view
.
item_not_found
(
item_type
,
item_name
)
else
:
self
.
view
.
show_item_information
(
item_type
,
item_name
,
item_info
)
class
Router
:
"""The Router is the entry point of the application."""
def
__init__
(
self
):
self
.
routes
=
{}
def
register
(
self
,
path
:
str
,
controller_class
:
type
[
Controller
],
model_class
:
type
[
Model
],
view_class
:
type
[
View
],
)
->
None
:
model_instance
:
Model
=
model_class
()
view_instance
:
View
=
view_class
()
self
.
routes
[
path
]
=
controller_class
(
model_instance
,
view_instance
)
def
resolve
(
self
,
path
:
str
)
->
Controller
:
if
self
.
routes
.
get
(
path
):
controller
:
Controller
=
self
.
routes
[
path
]
return
controller
else
:
raise
KeyError
(
f"No controller registered for path '
{
path
}
'"
)
def
main
():
"""
>>> model = ProductModel()
>>> view = ConsoleView()
>>> controller = Controller(model, view)
>>> controller.show_items()
PRODUCT LIST:
milk
eggs
cheese
<BLANKLINE>
>>> controller.show_item_information("cheese")
PRODUCT INFORMATION:
Name: cheese, Price: 2.00, Quantity: 10
<BLANKLINE>
>>> controller.show_item_information("eggs")
PRODUCT INFORMATION:
Name: eggs, Price: 0.20, Quantity: 100
<BLANKLINE>
>>> controller.show_item_information("milk")
PRODUCT INFORMATION:
Name: milk, Price: 1.50, Quantity: 10
<BLANKLINE>
>>> controller.show_item_information("arepas")
That product "arepas" does not exist in the records
"""
if
__name__
==
"__main__"
:
router
=
Router
()
router
.
register
(
"products"
,
Controller
,
ProductModel
,
ConsoleView
)
controller
:
Controller
=
router
.
resolve
(
argv
[
1
])
action
:
str
=
str
(
argv
[
2
])
if
len
(
argv
)
>
2
else
""
args
:
str
=
" "
.
join
(
map
(
str
,
argv
[
3
:]))
if
len
(
argv
)
>
3
else
""
if
hasattr
(
controller
,
action
):
command
=
getattr
(
controller
,
action
)
sig
=
signature
(
command
)
if
len
(
sig
.
parameters
)
>
0
:
if
args
:
command
(
args
)
else
:
print
(
"Command requires arguments."
)
else
:
command
()
else
:
print
(
f"Command
{
action
}
not found in the controller."
)
import
doctest
doctest
.
testmod
()
You can’t perform that action at this time.