Nagare Tutorial, learning concepts¶
The main goal of Nagare is to develop a web application like any standard python application. There are three steps to reach this goal:
- Hide the request/response connectionless nature of HTTP: no manual handling of the session
- Use aggregation as the shortest way to transform any python object into a Nagare component
Part 2. Modify the default application¶
nagare-admin create-appa complete
setuptoolscompatible package is created. Some Nagare specific files are also created:
conf/tutorial.cfg: application configuration file
data: folder where read/write datas are expected (sqlite database, csv files, etc.)
tutorial/models.py: module where the database models are defined using Elixir/SQLAlchemy ORM
tutorial/app.py: code of your application
Let’s start with a pure python class. Replace the whole content of
class Counter(object): def __init__(self): self.val = 0 def increase(self): self.val += 1 def decrease(self): self.val -= 1
Now, add an HTML view for the
from nagare import presentation ... @presentation.render_for(Counter) def render(counter, h, *args): return 'Hello'
For Nagare, a view is just a function that takes the object to render and a renderer (
h) as parameters and returns a DOM tree. In this example, we return a simple DOM tree with only a single text node. To bind the view to the
Counterclass, we import the Nagare presentation service and use the
Define the Nagare application:
For Nagare, an application is just an object factory (i.e. a callable that returns an objects graph), and obviously a class is, so we just have to add the following to our
... # define app app = Counter
You can now view your new web application in your browser (go to http://localhost:8080/tutorial).
If you take a look at the page source, you could see that Nagare has wrapped the text node into a valid html structure. By default, the DOM tree is serialized as HTML4. This can be changed in the application configuration file, to use XHTML if the browser accepts it or HTML5.
A more complex DOM tree:
Counterview with the following one:
... @presentation.render_for(Counter) def render(counter, h, *args): return h.div('Value: ', counter.val) ...
As you can see the
hHTML renderer can be used as a factory for all the HTML tags.
As we build a server-side DOM tree, we are protected against code injection. For example, if
counter.valcontains something like: