Bruno Desthuilliers
2/5/2008 3:27:00 PM
lanwrangler@gmail.com a écrit :
> Hi,
>
> This isn't a strictly Python question but I wonder if someone could
> give me some clues here. I've been writing a number of stand-alone
> apps that use CherryPy as an embedded web server for displaying
> processed data and interacting with the application. To go along with
> this I've also been using CherryTemplate as a handy HTML template
> generator.
>
> My question is this - what's the best way to separate the application
> code from the UI generation code from the "raw" HTML? To give you an
> idea what I mean, the core application code is fairly straightforward
> and writes to SQLite databases and/or dictionaries. That's the easy
> bit.
>
> The data then often needs a fair amount of massaging to make it
> suitable for display. For example, one app I've got monitors network
> utilisation so writes bits-per-second values to SQLite. The UI then
> takes those values and generates bar charts (done by cropping an image
> to size before putting it into a table cell), changes text colour if
> utilisation is >90% and so on etc.
>
> I've done this with lots of Python code embedded in the CherryTemplate
> pages but that becomes a real maintenance headache as the templates
> become huge and the code and HTML is scattered around with no clear
> distinction between the two. I've also tried using pure-Python HTML
> generation functions that output, say, entire tables made up from the
> source data that are then called by the template, but then you end up
> with Python functions with lots of HTML embedded in them which, again,
> ends up being difficult to keep track of.
>
> Are there any good approaches of doing this kind of thing that I've
> missed, or am I resigned to having HTML and Python code mixed and so
> will just have to keep all that nastiness to as few modules as
> possible?
The answer I can see is so terribly obvious that I surely have missed
something, but anyway: when the internal structure of the data is not
appropriate for the view, I usually use a helper function that takes the
raw data and format it the way the view expect it. Depending on the web
framework and whatnot, this can be either a special controller, or an
helper function called by the template with the data passed in by the
controller.