MVC model structure in Python
I'm having problems structuring classes in the Model part of an MVC pattern in my Python app. No matter how I turn things, I keep running into circular imports. Here's what I have:
Model/__init__p.y
- should hold all Model class names so I can do a "from Model import User" e.g. from a Controller or a unit test case
Model/Database.py
- holds Database class
- needs to import all Model classes to do ORM
- initialization should be performed on first module import, i.e. no extra init calls or instantiations (all methods on Database class are @classmethods)
Model/User.py
- contains User model class
- needs access to Database class to do queries
- should inherit from base class common to all Model classes to share functionality (database persistency methods, parameter validation code etc.)
I have yet to see a real world Python app employing MVC, so my approach is probably un-Pythonic (and possibly a language-agnostic mess on top of that...) - any suggestions on how to solve this?
Thanks, Simon
Asked by: Melissa771 | Posted: 28-01-2022
Answer 1
There is an inconsistency in your specification. You say Database.py needs to import all Model classes to do ORM but then you say the User class need access to the Database to do queries.
Think of these as layers of an API. The Database class provides an API (maybe object-oriented) to some physical persistence layer (such as DB-API 2.0). The Model classes, like User, use the Database layer to load and save their state. There is no reason for the Database.py class to import all the Model classes, and in fact you wouldn't want that because you'd have to modify Database.py each time you created a new Model class - which is a code smell.
Answered by: Leonardo985 | Posted: 01-03-2022Answer 2
Generally, we put it all in one file. This isn't Java or C++.
Start with a single file until you get some more experience with Python. Unless your files are gargantuan, it will work fine.
For example, Django encourages this style, so copy their formula for success. One module for the model. A module for each application; each application imports a common model.
Your Database and superclass stuff can be in your __init__.py
file, since it applies to the entire package. That may reduce some of the circularity.
Answer 3
I think you have one issue that should be straightened. Circular references often result from a failure to achieve separation of concerns. In my opinion, the database and model modules shouldn't know much about each other, working against an API instead. In this case the database shouldn't directly reference any specific model classes but instead provide the functionality the model classes will need to function. The model in turn, should get a database reference (injected or requested) that it would use to query and persist itself.
Answered by: Emily484 | Posted: 01-03-2022Similar questions
python - What is a cyclic data structure good for?
I was just reading through "Learning Python" by Mark Lutz and came across this code sample:
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
It was identified as a cyclic data structure.
So I was wonderi...
python - How is this basic pygame structure?
Closed. This question is opinion-based. It is not c...
Python class structure ... prep() method?
We have a metaclass, a class, and a child class for an alert system:
class AlertMeta(type):
"""
Metaclass for all alerts
Reads attrs and organizes AlertMessageType data
"""
def __new__(cls, base, name, attrs):
new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs)
# do stuff to new_class
return new_class
class BaseAlert(object):
"""
BaseAlert objects should be instantiated
in ord...
linux - Help with Python structure in *nixes
I came from a Windows background whern it comes to development environments. I'm used to run .exe's from everything I need to run and just forget.
I usually code in php, javascript, css, html and python.
Now, I have to use Linux at my work, in a non changeable Ubuntu 8.04, with permissions to upgrade my system using company's repositories only.
I need to install Python 2.4.3 to star...
xml to Python data structure using lxml
How can I convert xml to Python data structure using lxml?
I have searched high and low but can't find anything.
Input example
<ApplicationPack>
<name>Mozilla Firefox</name>
<shortname>firefox</shortname>
<description>Leading Open Source internet browser.</description>
<version>3.6.3-1</version>
<license name="Firefox EULA"&g...
python - Huge Graph Structure
I'm developing an application in which I need a structure to represent a huge graph (between 1000000 and 6000000 nodes and 100 or 600 edges per node) in memory. The edges representation will contain some attributes of the relation.
I have tried a memory map representation, arrays, dictionaries and strings to represent that structure in memory, but these always crash because of the memory limit.
I would lik...
python - C++ Structure within itself?
I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me):
typedef struct huffnode_s
{
struct huffnode_s *zero;
struct huffnode_s *one;
unsigned char val;
float freq;
} huffnode_t;
What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite und...
Looking for a good Python Tree data structure
Closed. This question does not meet Stack Overflow guid...
Python what's the data structure for triple data
I've got a set of data that has three attributes, say A, B, and C, where A is kind of the index (i.e., A is used to look up the other two attributes.) What would be the best data structure for such data?
I used two dictionaries, with A as the index of each. However, there's key errors when the query to the data doesn't match any instance of A.
Is there a structure in Python similar to C++ STL map?
Is there a structure in Python which supports similar operations to C++ STL map and complexity of operations correspond to C++ STL map?
python - What is a cyclic data structure good for?
I was just reading through "Learning Python" by Mark Lutz and came across this code sample:
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
It was identified as a cyclic data structure.
So I was wonderi...
Parsing an unknown data structure in python
I have a file containing lots of data put in a form similar to this:
Group1 {
Entry1 {
Title1 [{Data1:Member1, Data2:Member2}]
Title2 [{Data3:Member3, Data4:Member4}]
}
Entry2 {
...
}
}
Group2 {
DifferentEntry1 {
DiffTitle1 {
...
}
}
}
Thing is, I don't know how many layers of parentheses there are,...
Python gzip folder structure when zipping single file
I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:
import gzip
content = "Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()
If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the ...
python - How is this basic pygame structure?
Closed. This question is opinion-based. It is not c...
python - How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be?
I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has.
For each level, I can call level.children(), if there are no levels below the current one, it returns [], if there are, it returns [object, object, ...], on each of which I can call children() on again.
I need to drill down through the struct...
run unit tests and coverage in certain python structure
I have some funny noob problem.
I try to run unit tests from commandline:
H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
File "src\test\python\test_power_estimator.py", line 2, in <module>
import src.main.python.power_estimator as power
ImportError: No module named src.main.python.power_estimator
this same happens...
php - python for in control structure
I am a php programmer trying to understand python's for in syntax
I get the basic for in
for i in range(0,5):
in php would be
for ($i = 0; $i < 5; $i++){
but what does this do
for x, y in z:
and what would be the tran...
python - Decoding packed data into a structure
What would the best way of unpacking a python string into fields
I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function
It has the following format
uint8 - header
uint8 - length
uint32 - typeID
uint16 -param1
uint16 -param2
uint16 -param3
uint16 -param4
char[24] - name string
uint32 - checksum
asp.net - how to avoid storing different type of objects in the same place when they represent the same but with a different data structure
This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible.
I'm creating some classes to simplify some tasks for some specific requirements we have in some projects at work.
I have a class that creates objects which maps the values from webcontrols ...
Python class structure ... prep() method?
We have a metaclass, a class, and a child class for an alert system:
class AlertMeta(type):
"""
Metaclass for all alerts
Reads attrs and organizes AlertMessageType data
"""
def __new__(cls, base, name, attrs):
new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs)
# do stuff to new_class
return new_class
class BaseAlert(object):
"""
BaseAlert objects should be instantiated
in ord...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python