I'm writing a cherrypy app and I was wondering what the best way is for structuring my handlers and code for larger applications?
I realize assignment is simple trough cherrypy.root, but what are some practices for writing the handlers and assigning them?
(Allow me to prove my confusion!) My initial thought is to write a standard handler class that infers a template to run based on the current URL or class/method combination. Then I would assign one instance of that handler multiple times to the path to create pages. I don't see this working however as the recursive references wouldn't work quite right.
So, given the fact that I'm already drawing blanks on how my own source code should look, I'd love some pointers and examples!
Feel free to ask some detailed questions for me to clarify. While there is plenty of cherrypy tutorial material out there, it tends to only scratch the surface.
This question is wildly subjective - but I'll give it a shot.
First of all, always keep database and data code separate to the web code. What I do is have lots of small files with one class each in a DB/
folder which are all joined together into a Base.py
file, e.g:
Web/
Base.py - The main "base" class, which includes the classes in other
web files, starts the web server in __init__
Users.py - The class which includes methods generally from "DB/Users.py"
which checks permissions etc before returning (you may
wish to add DB-level security later though)
...
DB/
Base.py - The main base DB class, includes the other DB classes. Creates
new SQLAlchemy/whatever instances and create database schemas if
they don't etc. May pay to have database-wide methods
here to keep creating connections etc in one place if you
decide to change databases later
Users.py - The user/password etc DB storage class file
...
Templates/
(HTML templates go here)
Static/
(Static images/CSS/javscript etc go here)
Don't forget the __init__.py
in each module directory of course so python can find the modules in subdirectoriesIt doesn't always matter what methods you use for structuring code in my opinion, but be consistent. I write a document up with all my conventions with my justifications for using them and try to follow them up to the point it makes sense to, but as always a foolish consistency is the hobgoblin of small minds
, as quoting the python style docs :-)
Class
and just reference it by the module name. I'll give an example of Base.py:import Users
class Base(Users.Class):
def __init__
(self):
Users.Class.__init__
(self)
This helps to reduce problems when other modules reference each other when importing, as from Users import Users
will conflict if Users.py
has from Base import x
so I always reference by module name. This is just a personal preference though, so do what you want :-PHopefully you should get an idea from this post though.