Debian Codegraph @

docs/source/simple_ajax.rst

raw
1 .. _simple_ajax:
2
3 Example Application: Simple AJAX
4 ================================
5
6 This guide will walk you through building a simple Pecan web application that uses AJAX to fetch JSON data from a server.
7
8 Project Setup
9 -------------
10
11 First, you'll need to install Pecan:
12
13 ::
14
15 $ pip install pecan
16
17 Use Pecan's basic template support to start a new project:
18
19 ::
20
21 $ pecan create myajax
22 $ cd myajax
23
24 Install the new project in development mode:
25
26 ::
27
28 $ python setup.py develop
29
30 Adding JavaScript AJAX Support
31 ------------------------------
32
33 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.
34
35 Adding jQuery support is easy, we actually only need one line of code:
36
37 .. code-block:: html
38
39 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
40
41 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.
42
43 The ``layout.html`` file will look like this:
44
45 .. code-block:: html
46
47 <html>
48 <head>
49 <title>${self.title()}</title>
50 ${self.style()}
51 ${self.javascript()}
52 </head>
53 <body>
54 ${self.body()}
55 </body>
56 </html>
57
58 <%def name="title()">
59 Default Title
60 </%def>
61
62 <%def name="style()">
63 <link rel="stylesheet" type="text/css" media="screen" href="/css/style.css" />
64 </%def>
65
66 <%def name="javascript()">
67 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
68 <script language="text/javascript" src="/javascript/shared.js"></script>
69
70 <script>
71 function onSuccess(data, status, jqXHR) {
72 // Use a template or something here instead
73 // Just for demo purposes
74 $("#result").html("<div>" +
75 "<p></p><strong>Project Name: " + data.name + "</strong></p>" +
76 "<p>Project License: " + data.licensing + "</p>" +
77 "<p><a href='" + data.repository + "'>Project Repository: " + data.repository + "</a></p>" +
78 "<p><a href='" + data.documentation + "'>Project Documentation: " + data.documentation + "</a></p>" +
79 "</div>");
80 }
81
82 function onError(jqXHR, textStatus, errorThrown) {
83 alert('HTTP Status Code: ' + jqXHR.status + ', ' + errorThrown);
84 }
85
86 $(document).ready(function () {
87 $("#submit").click(function () {
88 $.ajax({
89 url: "/projects/",
90 data: "id=" + $("#projects").val(),
91 contentType: 'application/json',
92 dataType: 'json',
93 success: onSuccess,
94 error: onError
95 });
96
97 return false;
98 });
99 });
100 </script>
101 </%def>
102
103 **What did we just do?**
104
105 #. In the ``head`` section we added jQuery support via the `Google CDN <https://developers.google.com/speed/libraries/devguide>`_
106 #. 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
107 #. Once the ``onSuccess`` event is triggered by the returning data we take that and display it on the web page below the controls
108
109 Adding Additional HTML
110 ----------------------
111
112 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:
113
114 .. code-block:: html
115
116 <%inherit file="layout.html" />
117
118 <%def name="title()">
119 Welcome to Pecan!
120 </%def>
121
122 <header>
123 <h1><img src="/images/logo.png"/></h1>
124 </header>
125
126 <div id="content">
127 <p>Select a project to get details:</p>
128 <select id="projects">
129 <option value="0">OpenStack</option>
130 <option value="1">Pecan</option>
131 <option value="2">Stevedore</option>
132 </select>
133 <button id="submit" type="submit">Submit</button>
134
135 <div id="result"></div>
136
137 </div>
138
139 **What did we just do?**
140
141 #. 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
142
143 Building the Model with JSON Support
144 ------------------------------------
145
146 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:
147
148 .. code-block:: python
149
150 class Project(object):
151 def __init__(self, name, licensing, repository, documentation):
152 self.name = name
153 self.licensing = licensing
154 self.repository = repository
155 self.documentation = documentation
156
157 def __json__(self):
158 return dict(
159 name=self.name,
160 licensing=self.licensing,
161 repository=self.repository,
162 documentation=self.documentation
163 )
164
165 **What did we just do?**
166
167 #. Created a model called ``Project`` that can hold project specific data
168 #. 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
169
170 .. note::
171
172 There are other ways to return JSON with Pecan, check out :ref:`jsonify` for more information.
173
174 Working with the Controllers
175 ----------------------------
176
177 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:
178
179 .. code-block:: python
180
181 from pecan import expose
182
183 from myajax.controllers.projects import ProjectsController
184
185
186 class RootController(object):
187
188 projects = ProjectsController()
189
190 @expose(generic=True, template='index.html')
191 def index(self):
192 return dict()
193
194 **What did we just do?**
195
196 #. Removed some of the initial boilerplate code since we won't be using it
197 #. Add support for the upcoming ``ProjectsController``
198
199 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.
200
201 Add the following code to the ``projects.py`` file:
202
203 .. code-block:: python
204
205 from pecan import expose, response
206 from pecan.rest import RestController
207
208 from myajax.model.projects import Project
209
210
211 class ProjectsController(RestController):
212
213 # Note: You would probably store this information in a database
214 # This is just for simplicity and demonstration purposes
215 def __init__(self):
216 self.projects = [
217 Project(name='OpenStack',
218 licensing='Apache 2',
219 repository='http://github.com/openstack',
220 documentation='http://docs.openstack.org'),
221 Project(name='Pecan',
222 licensing='BSD',
223 repository='http://github.com/pecan/pecan',
224 documentation='https://pecan.readthedocs.io'),
225 Project(name='stevedore',
226 licensing='Apache 2',
227 repository='http://github.com/dreamhost/pecan',
228 documentation='http://docs.openstack.org/developer/stevedore/')
229 ]
230
231
232 @expose('json', content_type='application/json')
233 def get(self, id):
234 response.status = 200
235 return self.projects[int(id)]
236
237 **What did we just do?**
238
239 #. 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
240 #. 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
241
242 Run the application:
243
244 ::
245
246 $ pecan serve config.py
247
248 Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
249
250 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``.
251
252 Change the ``get`` function to look like this:
253
254 .. code-block:: python
255
256 @expose('json', content_type='application/json')
257 def get(self, id):
258 try:
259 response.status = 200
260 return self.projects[int(id)]
261 except (IndexError, ValueError) as ex:
262 abort(404)
263
264 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.
265
266 .. code-block:: html
267
268 <p>Select a project to get details:</p>
269 <select id="projects">
270 <option value="0">OpenStack</option>
271 <option value="1">Pecan</option>
272 <option value="2">Stevedore</option>
273 <option value="3">WSME</option>
274 </select>
275
276 You can see that we added ``WSME`` to the list and the value is 3.
277
278 Run the application:
279
280 ::
281
282 $ pecan serve config.py
283
284 Open a web browser: `http://127.0.0.1:8080/ <http://127.0.0.1:8080/>`_
285
286 Select ``WSME`` from the list. You should see the error dialog box triggered.