User Parameters - renzon/zenwarch GitHub Wiki
When building an app sooner or later you will collect data from users. This process will need the creation of forms or even receiving data through rest API.
This section will describe how receiving user parameters.
First, lets create a html form. We are using Jinja2 template system:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="/static/img/favicon.ico" />
<title>Zenwarch</title>
</head>
<body>
{% block body %}
<h1>Hello World</h1>
<form action="{{ form_url }}">
Type your name <input type="text" name="name"/>
<button type="submit">Send</button>
</form>
{% endblock %}
</body>
</html>
First thing to note is that the template is expection for a form_url variable.
Let's modify home.py to use zen.router to generate this url:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from web import my_form
from zen import router
def index(_write_tmpl):
url = router.to_path(my_form)
_write_tmpl('templates/home.html', {'form_url': url})
Once router is generating the url, you will not have to worry with broken links anymore. If you decide refactoring the functions names, the links are gonna be automatically updated.
Another interesting thing is the _write_tmpl. The framework is injection this function for you and we will talk about it later.
You can see the resulting html on http://zenwarchi.appspot.com
For now, let's see the my_form.py code:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
def index(_write_tmpl, name):
_write_tmpl('templates/form.html', {'name': name})
What we can see is the same _write_tmpl plus the second parameter: name. Do you remember the property name of the form's text input? Yeah, you are right, it has the name "name" too. So you receive the User Parameter by name convention. If you want, You could adding a input with property name "age" and add on index function an age argument to receive it. All the parameters received are strings, so remember to transform it before saving them o database.
The form.html template just shows the message "Hello Foo" if you fill the text with the value "Foo":
{% extends 'templates/home.html' %}
{% block body %}
<h1>Hello {{ name }}</h1>
{% endblock %}
You can see it on http://zenwarchi.appspot.com/my_form?name=Foo.
The important thin here is that we are using GET method to submit the form, but it could be POST too.
You could use a restfull approach too, getting on same result: http://zenwarchi.appspot.com/my_form/Foo
So that is how you receive parameters when using ZenWArch.
Lets see the special argument _write_tmpl with more detail in Dependency Injection