summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorchadlung <chad.lung@gmail.com>2014-03-14 12:19:56 -0500
committerchadlung <chad.lung@gmail.com>2014-03-27 22:37:05 -0500
commit5bc482572272714b290e930ab6580c11c93e5159 (patch)
tree0b81137f0ba73aaf0aad25845ebf65f4a9b4bfd2
parent8e9d8b7bb77f4c2ad32f37f0dfc4360575a4c6a5 (diff)
downloadpecan-5bc482572272714b290e930ab6580c11c93e5159.tar.gz
Adding new walkthroughs for docs
Change-Id: I419d337e06ecc70d539823e89dd768d923b1e2c5
-rw-r--r--docs/source/index.rst4
-rw-r--r--docs/source/simple_ajax.rst286
-rw-r--r--docs/source/simple_forms_processing.rst195
3 files changed, 484 insertions, 1 deletions
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 614baee..8a4ef37 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -54,7 +54,9 @@ Cookbook and Common Patterns
sessions.rst
databases.rst
errors.rst
-
+ simple_forms_processing.rst
+ simple_ajax.rst
+
API Documentation
=================
diff --git a/docs/source/simple_ajax.rst b/docs/source/simple_ajax.rst
new file mode 100644
index 0000000..fcebb3a
--- /dev/null
+++ b/docs/source/simple_ajax.rst
@@ -0,0 +1,286 @@
+.. _simple_ajax:
+
+Example Application: Simple AJAX
+================================
+
+This guide will walk you through building a simple Pecan web application that uses AJAX to fetch JSON data from a server.
+
+Project Setup
+-------------
+
+First, you'll need to install Pecan:
+
+::
+
+$ pip install pecan
+
+Use Pecan's basic template support to start a new project:
+
+::
+
+$ pecan create myajax
+$ cd myajax
+
+Install the new project in development mode:
+
+::
+
+$ python setup.py develop
+
+Adding JavaScript AJAX Support
+------------------------------
+
+For this project we will need to add `jQuery <http://jquery.com/>`_ support. To add jQuery go into the ``templates`` folder and edit the ``layout.html`` file.
+
+Adding jQuery support is easy, we actually only need one line of code:
+
+.. code-block:: html
+
+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
+
+The JavaScript to make the AJAX call is a little more in depth but shouldn't be unfamiliar if you've ever worked with jQuery before.
+
+The ``layout.html`` file will look like this:
+
+.. code-block:: html
+
+ <html>
+ <head>
+ <title>${self.title()}</title>
+ ${self.style()}
+ ${self.javascript()}
+ </head>
+ <body>
+ ${self.body()}
+ </body>
+ </html>
+
+ <%def name="title()">
+ Default Title
+ </%def>
+
+ <%def name="style()">
+ <link rel="stylesheet" type="text/css" media="screen" href="/css/style.css" />
+ </%def>
+
+ <%def name="javascript()">
+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
+ <script language="text/javascript" src="/javascript/shared.js"></script>
+
+ <script>
+ function onSuccess(data, status, jqXHR) {
+ // Use a template or something here instead
+ // Just for demo purposes
+ $("#result").html("<div>" +
+ "<p></p><strong>Project Name: " + data.name + "</strong></p>" +
+ "<p>Project License: " + data.licensing + "</p>" +
+ "<p><a href='" + data.repository + "'>Project Repository: " + data.repository + "</a></p>" +
+ "<p><a href='" + data.documentation + "'>Project Documentation: " + data.documentation + "</a></p>" +
+ "</div>");
+ }
+
+ function onError(jqXHR, textStatus, errorThrown) {
+ alert('HTTP Status Code: ' + jqXHR.status + ', ' + errorThrown);
+ }
+
+ $(document).ready(function () {
+ $("#submit").click(function () {
+ $.ajax({
+ url: "/projects/",
+ data: "id=" + $("#projects").val(),
+ contentType: 'application/json',
+ dataType: 'json',
+ success: onSuccess,
+ error: onError
+ });
+
+ return false;
+ });
+ });
+ </script>
+ </%def>
+
+**What did we just do?**
+
+#. In the ``head`` section we added jQuery support via the `Google CDN <https://developers.google.com/speed/libraries/devguide>`_
+#. Added JavaScript to make an AJAX call to the server via an HTTP ``GET`` passing in the ``id`` of the project to fetch more information on
+#. Once the ``onSuccess`` event is triggered by the returning data we take that and display it on the web page below the controls
+
+Adding Additional HTML
+----------------------
+
+Let's edit the ``index.html`` file next. We will add HTML to support the AJAX interaction between the web page and Pecan. Modify ``index.html`` to look like this:
+
+.. code-block:: html
+
+ <%inherit file="layout.html" />
+
+ <%def name="title()">
+ Welcome to Pecan!
+ </%def>
+
+ <header>
+ <h1><img src="/images/logo.png"/></h1>
+ </header>
+
+ <div id="content">
+ <p>Select a project to get details:</p>
+ <select id="projects">
+ <option value="0">OpenStack</option>
+ <option value="1">Pecan</option>
+ <option value="2">Stevedore</option>
+ </select>
+ <button id="submit" type="submit">Submit</button>
+
+ <div id="result"></div>
+
+ </div>
+
+**What did we just do?**
+
+#. Added a dropdown control and submit button for the user to interact with. Users can pick an open source project and get more details on it
+
+Building the Model with JSON Support
+------------------------------------
+
+The HTML and JavaScript work is now taken care of. At this point we can add a model to our project inside of the ``model`` folder. Create a file in there called ``projects.py`` and add the following to it:
+
+.. code-block:: python
+
+ class Project(object):
+ def __init__(self, name, licensing, repository, documentation):
+ self.name = name
+ self.licensing = licensing
+ self.repository = repository
+ self.documentation = documentation
+
+ def __json__(self):
+ return dict(
+ name=self.name,
+ licensing=self.licensing,
+ repository=self.repository,
+ documentation=self.documentation
+ )
+
+**What did we just do?**
+
+#. Created a model called ``Project`` that can hold project specific data
+#. Added a ``__json__`` method so an instance of the ``Project class`` can be easily represented as JSON. The controller we will soon build will make use of that JSON capability
+
+.. note::
+
+ There are other ways to return JSON with Pecan, check out :ref:`jsonify` for more information.
+
+Working with the Controllers
+----------------------------
+
+We don't need to do anything major to the ``root.py`` file in the ``controllers`` folder except to add support for a new controller we will call ``ProjectsController``. Modify the ``root.py`` like this:
+
+.. code-block:: python
+
+ from pecan import expose
+
+ from myajax.controllers.projects import ProjectsController
+
+
+ class RootController(object):
+
+ projects = ProjectsController()
+
+ @expose(generic=True, template='index.html')
+ def index(self):
+ return dict()
+
+**What did we just do?**
+
+#. Removed some of the initial boilerplate code since we won't be using it
+#. Add support for the upcoming ``ProjectsController``
+
+The final piece is to add a file called ``projects.py`` to the ``controllers`` folder. This new file will host the ``ProjectsController`` which will listen for incoming AJAX ``GET`` calls (in our case) and return the appropriate JSON response.
+
+Add the following code to the ``projects.py`` file:
+
+.. code-block:: python
+
+ from pecan import expose, response
+ from pecan.rest import RestController
+
+ from myajax.model.projects import Project
+
+
+ class ProjectsController(RestController):
+
+ # Note: You would probably store this information in a database
+ # This is just for simplicity and demonstration purposes
+ def __init__(self):
+ self.projects = [
+ Project(name='OpenStack',
+ licensing='Apache 2',
+ repository='http://github.com/openstack',
+ documentation='http://docs.openstack.org'),
+ Project(name='Pecan',
+ licensing='BSD',
+ repository='http://github.com/stackforge/pecan',
+ documentation='http://pecan.readthedocs.org'),
+ Project(name='stevedore',
+ licensing='Apache 2',
+ repository='http://github.com/dreamhost/pecan',
+ documentation='http://stevedore.readthedocs.org')
+ ]
+
+
+ @expose('json', content_type='application/json')
+ def get(self, id):
+ response.status = 200
+ return self.projects[int(id)]
+
+**What did we just do?**
+
+#. Created a local class variable called ``projects`` that holds three open source projects and their details. Typically this kind of information would probably reside in a database
+#. Added code for the new controller that will listen on the ``projects`` endpoint and serve back JSON based on the ``id`` passed in from the web page
+
+Run the application:
+
+::
+
+$ pecan serve config.py
+
+Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
+
+There is something else we could add. What if an ``id`` is passed that is not found? A proper ``HTTP 404`` should be sent back. For this we will modify the ``ProjectsController``.
+
+Change the ``get`` function to look like this:
+
+.. code-block:: python
+
+ @expose('json', content_type='application/json')
+ def get(self, id):
+ try:
+ response.status = 200
+ return self.projects[int(id)]
+ except (IndexError, ValueError) as ex:
+ abort(404)
+
+To test this out we need to pass an invalid ``id`` to the ``ProjectsController``. This can be done by going into the ``index.html`` and adding an additional ``option`` tag with an ``id`` value that is outside of 0-2.
+
+.. code-block:: html
+
+ <p>Select a project to get details:</p>
+ <select id="projects">
+ <option value="0">OpenStack</option>
+ <option value="1">Pecan</option>
+ <option value="2">Stevedore</option>
+ <option value="3">WSME</option>
+ </select>
+
+You can see that we added ``WSME`` to the list and the value is 3.
+
+Run the application:
+
+::
+
+$ pecan serve config.py
+
+Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
+
+Select ``WSME`` from the list. You should see the error dialog box triggered.
diff --git a/docs/source/simple_forms_processing.rst b/docs/source/simple_forms_processing.rst
new file mode 100644
index 0000000..d7b73de
--- /dev/null
+++ b/docs/source/simple_forms_processing.rst
@@ -0,0 +1,195 @@
+.. _simple_forms_processing:
+
+Example Application: Simple Forms Processing
+============================================
+
+This guide will walk you through building a simple Pecan web application that will do some simple forms processing.
+
+Project Setup
+-------------
+
+First, you'll need to install Pecan:
+
+::
+
+$ pip install pecan
+
+Use Pecan's basic template support to start a new project:
+
+::
+
+$ pecan create mywebsite
+$ cd mywebsite
+
+Install the new project in development mode:
+
+::
+
+$ python setup.py develop
+
+With the project ready, go into the ``templates`` folder and edit the ``index.html`` file. Modify it so that it resembles this:
+
+.. code-block:: html
+
+ <%inherit file="layout.html" />
+
+ <%def name="title()">
+ Welcome to Pecan!
+ </%def>
+ <header>
+ <h1><img src="/images/logo.png" /></h1>
+ </header>
+ <div id="content">
+ <form method="POST" action="/">
+ <fieldset>
+ <p>Enter a message: <input name="message" /></p>
+ <p>Enter your first name: <input name="first_name" /></p>
+ <input type="submit" value="Submit" />
+ </fieldset>
+ </form>
+ % if not form_post_data is UNDEFINED:
+ <p>${form_post_data['first_name']}, your message is: ${form_post_data['message']}</p>
+ % endif
+ </div>
+
+**What did we just do?**
+
+#. Modified the contents of the ``form`` tag to have two ``input`` tags. The first is named ``message`` and the second is named ``first_name``
+#. Added a check if ``form_post_data`` has not been defined so we don't show the message or wording
+#. Added code to display the message from the user's ``POST`` action
+
+Go into the ``controllers`` folder now and edit the ``root.py`` file. There will be two functions inside of the ``RootController`` class which will display the ``index.html`` file when your web browser hits the ``'/'`` endpoint. If the user puts some data into the textbox and hits the submit button then they will see the personalized message displayed back at them.
+
+Modify the ``root.py`` to look like this:
+
+.. code-block:: python
+
+ from pecan import expose
+
+
+ class RootController(object):
+
+ @expose(generic=True, template='index.html')
+ def index(self):
+ return dict()
+
+ @index.when(method='POST', template='index.html')
+ def index_post(self, **kwargs):
+ return dict(form_post_data=kwargs)
+
+**What did we just do?**
+
+#. Modified the ``index`` function to render the initial ``index.html`` webpage
+#. Modified the ``index_post`` function to return the posted data via keyword arguments
+
+Run the application:
+
+::
+
+$ pecan serve config.py
+
+Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
+
+Adding Validation
+-----------------
+
+Enter a message into the textbox along with a name in the second textbox and press the submit button. You should see a personalized message displayed below the form once the page posts back.
+
+One problem you might have noticed is if you don't enter a message or a first name then you simply see no value entered for that part of the message. Let's add a little validation to make sure a message and a first name was actually entered. For this, we will use `WTForms <http://wtforms.simplecodes.com/>`_ but you can substitute anything else for your projects.
+
+Add support for the `WTForms <http://wtforms.simplecodes.com/>`_ library:
+
+::
+
+$ pip install wtforms
+
+.. note::
+
+ Keep in mind that Pecan is not opinionated when it comes to a particular library when working with form generation, validation, etc. Choose which libraries you prefer and integrate those with Pecan. This is one way of doing this, there are many more ways so feel free to handle this however you want in your own projects.
+
+Go back to the ``root.py`` files and modify it like this:
+
+.. code-block:: python
+
+ from pecan import expose, request
+ from wtforms import Form, TextField, validators
+
+
+ class PersonalizedMessageForm(Form):
+ message = TextField(u'Enter a message',
+ validators=[validators.required()])
+ first_name = TextField(u'Enter your first name',
+ validators=[validators.required()])
+
+
+ class RootController(object):
+
+ @expose(generic=True, template='index.html')
+ def index(self):
+ return dict(form=PersonalizedMessageForm())
+
+ @index.when(method='POST', template='index.html')
+ def index_post(self):
+ form = PersonalizedMessageForm(request.POST)
+ if form.validate():
+ return dict(message=form.message.data,
+ first_name=form.first_name.data)
+ else:
+ return dict(form=form)
+
+**What did we just do?**
+
+#. Added the ``PersonalizedMessageForm`` with two textfields and a required field validator for each
+#. Modified the ``index`` function to create a new instance of the ``PersonalizedMessageForm`` class and return it
+#. In the ``index_post`` function modify it to gather the posted data and validate it. If its valid, then set the returned data to be displayed on the webpage. If not valid, send the form which will contain the data plus the error message(s)
+
+Modify the ``index.html`` like this:
+
+.. code-block:: html
+
+ <%inherit file="layout.html" />
+
+ ## provide definitions for blocks we want to redefine
+ <%def name="title()">
+ Welcome to Pecan!
+ </%def>
+ <header>
+ <h1><img src="/images/logo.png" /></h1>
+ </header>
+ <div id="content">
+ % if not form:
+ <p>${first_name}, your message is: ${message}</p>
+ % else:
+ <form method="POST" action="/">
+ <div>
+ ${form.message.label}:
+ ${form.message}
+ % if form.message.errors:
+ <strong>${form.message.errors[0]}</strong>
+ % endif
+ </div>
+ <div>
+ ${form.first_name.label}:
+ ${form.first_name}
+ % if form.first_name.errors:
+ <strong>${form.first_name.errors[0]}</strong>
+ % endif
+ </div>
+ <input type="submit" value="Submit">
+ </form>
+ % endif
+ </div>
+
+.. note::
+
+ Keep in mind when using the `WTForms <http://wtforms.simplecodes.com/>`_ library you can customize the error messages and more. Also, you have multiple validation rules so make sure to catch all the errors which will mean you need a loop rather than the simple example above which grabs the first error item in the list. See the `documentation <http://wtforms.simplecodes.com/>`_ for more information.
+
+Run the application:
+
+::
+
+$ pecan serve config.py
+
+Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
+
+Try the form with valid data and with no data entered.