I am a beginner in Web2Py. I wish to develop a simple application, where the user should log in with a username and a password (no fancy stuff like login with facebook or OpenID etc.). Upon successful login, the user sees some interface, and performs certain operations. I imagined a User class and a JobStore class (which has certain methods defined, which the user should be able to call). There will be only one JobStore object for all users and sessions. When a user logs in, an User object gets created with a reference to the JobStore. The User class has methods like GetRights(), RequestJob(), MarkAsFinished(), etc. and JobStore has methods like GetUnfinished(), RemoveJobs(), etc. Structurally speaking, where am I supposed to have these classes, so that based on certain actions the user performs on the view, certain methods get called? Are these classes supposed to inherit from some standard classes used in Web2Py? I am trying to find an example, where some kind of object oriented approach is used in the controller, but have not found any so far. Also, is this the wrong approach in Web2Py app development? I am not trying to implement any complex business logic through these functions as of now; I am just trying to understand how traditional programming approach would map to Web2Py approach somehow.
You can define classes in model or controller files, but it would probably make most sense to put them in the app's /modules folder and import them where needed in your models and controllers. There is no need for your classes to inherit from web2py classes, though they can do so if desired. For more on using modules and importing, see here and here.
For an example of a heavily object-oriented approach, see the Movuca CMS. Most of the code is in the /modules folder.
Related
When building a Django application, is it dangerous from a framework or namespace perspective to create a Python class that has the same name as one of your Django models? My application uses a Python class called "Photo" to store temporary information about photos when my application is uploading them. But after I process a photo, I want to store other permanent information about the photo to my database via a Photo model. I know there's potential confusion from a programmer perspective. But aside from that risk, if the class and model are in separate modules, am I likely to run into problems or encounter strange errors because Django gets confused as to which is which?
Thanks.
I don't have an explicit reference to this fact, but you'll be fine. Keep in mind you still must follow the rules of Python, so you can't go importing name conflicts and such, but the models you are creating are themselves are subclasses of a class provided by Django, so it's not like internal functions of isinstance() would behave foolishly purely because of a similar name. When models are loaded by Django, they are indeed namespaced by app (as you can see in accessing a model in a different app, when dealing with database routers or by how the database tables are named. To get deeper, check out the source for apps.registry that ensures even model names between modules do not conflict, and apps.config for the object that deals with importing names wrapped up in a module. All this registration and app loading is going to be completed before you even get into running a lot of your Django code (assuming you didn't inject it in the way of course). Also, I have done it, so no worries about Django being too foolish when it comes to class/model names.
Baseline: I'm building a django based application that is heavily using the admin interface as it spares me a lot of work in developing own CRUD routines. By now I came across several situations where i have models that hold some general information (say parents) and often have foreignkey-relations to derived models (say childs).
I realized that i sometimes implemented my routines to create child objects within the admin-class, sometimes within the model class(method being called from within some admin routine) or sometimes even within view-classes (e.g. as reaction to POST requests on some custom forms). It feels now, that my design is not very consistent (the effects of changing some model parameters being distributed over a lot of files) and i should refactor before it gets to big a mess.
So what is the best approach? Where should one concentrate methods that create/modify related objects (keeping in mind that i often want to give some feedback-messages related to process) ?
If your code is about a Model class, add it to models.py. This makes sense when the classes have to be added to database (migrations)
If your code is related to views, attach it to views.py. This makes sense when the code handles requests.
If your code is related to admin, attach it to admins.py. This makes sense when the code is related to admin interface.
If your code is generic, used in multiple places, refactor it into a separate file, and import that file elsewhere.
Your use case isn't exactly clear to me, so I'm taking a stab in the dark here - You can have the Models in models.py and create a separate file to create objects for models with child objects containing the code that's related to creating parent-child objects with given data. Then use this as an import in the admin and views wherever applicable.
Something like:
# foo in views.py and admin.py
def foo():
data = {} # get all data
make_parent_child(data) # create parent-child objects
I'm going to ask this question in two parts: first the general question, and than the question for my specific use case.
The general question:
I'm building a podcast app, where, hopefully, we'll have users. Users have subscripitons, settings, ... , which I'd like to store on the User object, but subscriptions and settings don't belong in the same module in my code.
How do you structure your code so that all the relevant data about a user is stored together, but the code that defines and deals with specific properties can be separated?
My specific use case
I'm building the back end on Google App Engine. My user class looks something like this:
class User(ndb.Model):
username = ndb.StringProperty(required=True)
email = ndb.StringProperty(required=True)
...
Now I could just add another property for subscriptions, settings etc, but these definitions don't really belong in the users module. I've tried defining a SubscriptionsHolder and SettingsHolder class using ndb.PolyModel, but with multiple inheritance, only queries on the last superclass in the User definition supports querying.
I could just make the settings and other module query the User model directly, but this results in a circular dependency, where the User the users module depends on settings for subclassing, and settings depends on users for querying. I know I can resolve the circular dependency by moving the import statement around, but that just seems like a hack to me.
My approach was to treat User and Settings data as separate but related collections. Instead of subclassing or using PolyModel I simply introduced a way to imply a 1:1 relation between those data sets.
One way is to add a KeyProperty to Settings that links back to User. Another way is to create each Settings entity with the same id/name that is used by the related User entity. This second way allows a direct Settings.get_by_id() call once you have the User key.
I apologize if this seems like a stupid question but I'm still very much a novice Python/Django programmer. Is it normal to create Python objects in a Django application that aren't models that will be saved in the database?
I'm creating what's become a fairly large Django application and, to me, my code is really starting to "smell". What I mean is that my views are becoming very large because I'm taking a procedural rather than object-oriented approach. My intuition tells me that my code might be simpler, easier to test, and more robust in the long run if I were using more objects with their own attributes and behaviors rather than passing information from one function to the next in my views.
What's hanging me up is that these aren't objects I want to save in my database so I don't quite know if I should be using them and, if I should, where I'd put them. Is the approach I'm proposing typical in a Django application? If so, where would I store those objects with respect to the Django model/view/template structure? Also, are there any popular Django modules or libraries that do what I'm describing that I should study?
Thanks in advance for your response.
You can store your objects anywhere. There could be helper functions in your views file or models file or wherever. I prefer to put miscellaneous functions in a utils.py file but that is not a convention, just something I end up doing. I end up putting most of miscellaneous helper functions and base classes in a common app, and more specifically a common.utils file.
In one project I have lots of apps, and each app has an api client. The base class for the client resides in an app called common. Then each app then has their specific client in client.py file
project
common
client
app1
client
app2
client
Then in app1 client
from project.common.client import BaseClient
class ConcreteApp1Client(BaseClient):
pass
Then in my views or management commands or models or wherever the concrete client can be imported and used as normal. from project.app1.client import ConcreteApp1Client
Django also has class-based views if you feel certain variables could best be encapsulated in a class.
https://docs.djangoproject.com/en/dev/topics/class-based-views/
I'd like to know where to put code that doesn't belong to a view, I mean, the logic.
I've been reading a few similar posts, but couldn't arrive to a conclusion.
What I could understand is:
A View is like a controller, and lot of logic should not put in the controller.
Models should not have a lot of logic either.
So where is all the logic based stuff supposed to be?
I'm coming from Groovy/Grails and for example if we need to access the DB or if we have a complex logic, we use services, and then those services are injected into the controllers.
Is it a good practice to have .py files containing things other than Views and Models in Django?
PS: I've read that some people use a services.py, but then other people say this is a bad practice, so I'm a little confused...
I don't know why you say
we can't put a lot of logic in the controller, and we cannot have the models with a lot of logic either
You can certainly put logic in either of those places. It depends to a great extent what that logic is: if it's specifically related to a single model class, it should go in the model. If however it's more related to a specific page, it can go in a view.
Alternatively, if it's more general logic that's used in multiple views, you could put it in a separate utility module. Or, you could use class-based views with a superclass that defines the logic, and subclasses which inherit from it.
Having a java background I can relate with this question.
I have been working on python for quite some time. Even though I do my best to treat Java as Java and Python as Python, some times I mix them both so that I can get a good deal out of both.
In short
Put all model related stuff in models app, it could be from simply models definition to custom save , pre save hooks .....
Put any request/ response related stuff in views, and some logic like verifying Jon schema, validation request body ... handling exceptions and so on ....
Put your business logic in separate folder/ app or module per views directory/ app. Meaning have separate middle module between your models and views.
There isn't strict rule to organise your code as long as you are consistent.
Project : Ci
Models: ci/model/device.py
Views: ci/views/list_device.py
Business logic:
(1) ci/business_logic/discover_device.py
Or
(2) ci/views/discover_device.py
Short answer: Django is more of a MTV or MVT (Model / Template / View), as described in the official FAQ : https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names
The business logic has its place in your views, but nothing prevents you from putting it inside a "utils.py", "services.py" or anything to your liking.
If the functionality fits well as a method of some model instance, put it there. After all, models are just classes.
Otherwise, just write a Python module (some .py file) and put the code there, just like in any other Python library.
Don't put it in the views. Views should be the only part of your code that is aware of HTTP, and they should stay as small as possible.