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:
Do everything in python (no sql, no templating language, avoid hand-written javascript as much as possible)
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#
With
nagare-admin create-appa completesetuptoolscompatible package is created. Some Nagare specific files are also created:conf/tutorial.cfg: application configuration filedata: folder where read/write datas are expected (sqlite database, csv files, etc.)static: folder where html static files are stored (css, images and javascripts)tutorial/models.py: module where the database models are defined using Elixir/SQLAlchemy ORMtutorial/app.py: code of your application
Let’s start with a pure python class. Replace the whole content of
tutorial/app.pywith: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
Counterclass: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 theCounterclass, we import the Nagare presentation service and use therender_fordecorator.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
app.pyfile:... # 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:
Replace the
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:"<script>alert('Hello World');</script>"This string would be escaped and no javascript will ever be executed.