Added JSON Support and started working on jQuery docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent c64a4e0 · Browse files · 7 files·+254 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+254 added−9 removed
- tests:+30 added−2 removed
- other:+224 added−7 removed
Provenance
- Commit
6e2be6a- Tree
ee37c61- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c64a4e0
7 files changed+254 added−9 removed
modified:docs/patterns/index.rst+1 added
17 unmodified lines18 sqlalchemy19 wtforms20 templateinheritance21 flashing22+ jqueryadded:docs/patterns/jquery.rst+59 added
1+AJAX With jQuery2+================3+4+`jQuery`_ is a small JavaScript library commonly used to simplify working5+with the DOM and JavaScript in general. It is the perfect tool to make6+web applications more dynamic by exchanging JSON between server and7+client.8+9+.. _jQuery: http://jquery.com/10+11+Loading jQuery12+--------------13+14+In order to use jQuery, you have to download it first and place it in the15+static folder of your application and then ensure it's loaded. Ideally16+you have a layout template that is used for all pages where you just have17+to add two script statements to your `head` section. One for jQuery, and18+one for your own script (called `app.js` here):19+20+.. sourcecode:: html21+22+ <script type=text/javascript src="{{23+ url_for('static', filename='jquery.js') }}"></script>24+ <script type=text/javascript src="{{25+ url_for('static', filename='app.js') }}"></script>26+27+Where is My Site?28+-----------------29+30+Do you know where your application is? If you are developing the answer31+is quite simple: it's on localhost port something and directly on the root32+of that server. But what if you later decide to move your application to33+a different location? For example to ``http://example.com/myapp``? On34+the server side this never was a problem because we were using the handy35+:func:`~flask.url_for` function that did could answer that question for36+us, but if we are using jQuery we should better not hardcode the path to37+the application but make that dynamic, so how can we do that?38+39+A simple method would be to add a script tag to our page that sets a40+global variable to the prefix to the root of the application. Something41+like this:42+43+.. sourcecode:: html+jinja44+45+ <script type=text/javascript>46+ $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};47+ </script>48+49+The ``|safe`` is necessary so that Jinja does not escape the JSON encoded50+string with HTML rules. Usually this would be necessary, but we are51+inside a `script` block here where different rules apply.52+53+.. admonition:: Information for Pros54+55+ In HTML the `script` tag is declared `CDATA` which means that entities56+ will not be parsed. Everything until ``</script>`` is handled as script.57+ This also means that there must never be any ``</`` between the script58+ tags. ``|tojson`` is kindly enough to do the right thing here and59+ escape backslashes for you.modified:docs/api.rst+54 added-5 removed
54 unmodified lines55 the request.56 57 .. attribute:: stream58 59- If the incoming form data was not encoded with a known encoding (for60- example it was transmitted as JSON) the data is stored unmodified in61- this stream for consumption. For example to read the incoming62- request data as JSON, one can do the following::59+ If the incoming form data was not encoded with a known mimetype60+ the data is stored unmodified in this stream for consumption. Most61+ of the time it is a better idea to use :attr:`data` which will give62+ you that data as a string. The stream only returns the data once.63+ 64+ .. attribute:: data65 64- json_body = simplejson.load(request.stream)66+ Contains the incoming request data as string in case it came with67+ a mimetype Flask does not handle.68 69 .. attribute:: files70 71 A :class:`~werkzeug.MultiDict` with files uploaded as part of a36 unmodified lines108 `base_url` ``http://www.example.com/myapplication/page.html?x=y``109 `root_url` ``http://www.example.com/myapplication/``110 ============= ======================================================111 112+ .. attribute:: is_xhr113+114+ `True` if the request was triggered via a JavaScript115+ `XMLHttpRequest`. This only works with libraries that support the116+ ``X-Requested-With`` header and set it to `XMLHttpRequest`.117+ Libraries that do that are prototype, jQuery and Mochikit and118+ probably some more.119+120+ .. attribute:: json121+122+ Contains the parsed body of the JSON request if the mimetype of123+ the incoming data was `application/json`. This requires Python 2.6124+ or an installed version of simplejson.125+126 Response Objects127 ----------------128 129 .. autoclass:: flask.Response87 unmodified lines217 .. autofunction:: flash218 219 .. autofunction:: get_flashed_messages220 221+Returning JSON222+--------------223+224+.. autofunction:: jsonify225+226+.. data:: json227+228+ If JSON support is picked up, this will be the module that Flask is229+ using to parse and serialize JSON. So instead of doing this yourself::230+231+ try:232+ import simplejson as json233+ except ImportError:234+ import json235+236+ You can instead just do this::237+238+ from flask import json239+240+ For usage examples, read the :mod:`json` documentation.241+242+ The :func:`~json.dumps` function of this json module is also available243+ as filter called ``|tojson`` in Jinja2. Note that inside `script`244+ tags no escaping must take place, so make sure to disable escaping245+ with ``|safe`` if you intend to use it inside `script` tags:246+247+ .. sourcecode:: html+jinja248+249+ <script type=text/javascript>250+ doSomethingWith({{ user.username|tojson|safe }});251+ </script>252+253 Template Rendering254 ------------------255 256 .. autofunction:: render_template4 unmodified linesadded:examples/jqueryexample/templates/index.html+25 added
12345678910111213141516171819202122232425<!doctype html><title>jQuery Example</title><script type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type=text/javascript src="{{ url_for('static', filename='app.js') }}"></script><script type=text/javascript> var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$(function() { $('a#calculate').bind('click', function() { $.getJSON($SCRIPT_ROOT + '/_add_numbers', { a: $('input[name="a"]').val(), b: $('input[name="b"]').val() }, function(data) { $("#result").text(data.result); }); }); });</script><h1>jQuery Example</h1><p><input type=text size=5 name=a> + <input type=text size=5 name=b> = <span id=result>?</span><p><a href=# id=calculate>calculate server side</a>added:examples/jqueryexample/jqueryexample.py+29 added
1+# -*- coding: utf-8 -*-2+"""3+ jQuery Example4+ ~~~~~~~~~~~~~~5+6+ A simple application that shows how Flask and jQuery get along.7+8+ :copyright: (c) 2010 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from flask import Flask, jsonify, render_template, request12+app = Flask(__name__)13+14+15+@app.route('/_add_numbers')16+def add_numbers():17+ """Add two numbers server side, ridiculous but well..."""18+ a = request.args.get('a', 0, type=int)19+ b = request.args.get('b', 0, type=int)20+ return jsonify(result=a + b)21+22+23+@app.route('/')24+def index():25+ return render_template('index.html')26+27+28+if __name__ == '__main__':29+ app.run()modified:tests/flask_tests.py+30 added-2 removed
30 unmodified lines31 with app.test_request_context('/meh'):32 assert meh() == 'http://localhost/meh'33 34 35-class BasicFunctionality(unittest.TestCase):35+class BasicFunctionalityTestCase(unittest.TestCase):36 37 def test_request_dispatching(self):38 app = flask.Flask(__name__)39 @app.route('/')126 unmodified lines166 assert flask.url_for('static', filename='index.html') \167 == '/static/index.html'168 169 170-class Templating(unittest.TestCase):170+class JSONTestCase(unittest.TestCase):171 172+ def test_jsonify(self):173+ d = dict(a=23, b=42, c=[1, 2, 3])174+ app = flask.Flask(__name__)175+ @app.route('/kw')176+ def return_kwargs():177+ return flask.jsonify(**d)178+ @app.route('/dict')179+ def return_dict():180+ return flask.jsonify(d)181+ c = app.test_client()182+ for url in '/kw', '/dict':183+ rv = c.get(url)184+ assert rv.mimetype == 'application/json'185+ assert flask.json.loads(rv.data) == d186+187+ def test_json_attr(self):188+ app = flask.Flask(__name__)189+ @app.route('/add', methods=['POST'])190+ def add():191+ return unicode(flask.request.json['a'] + flask.request.json['b'])192+ c = app.test_client()193+ rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),194+ content_type='application/json')195+ assert rv.data == '3'196+197+198+class TemplatingTestCase(unittest.TestCase):199+200 def test_context_processing(self):201 app = flask.Flask(__name__)202 @app.context_processor203 def context_processor():33 unmodified linesmodified:flask.py+56 added-2 removed
13 unmodified lines14 import sys15 16 from jinja2 import Environment, PackageLoader, FileSystemLoader17 from werkzeug import Request as RequestBase, Response as ResponseBase, \18- LocalStack, LocalProxy, create_environ, SharedDataMiddleware18+ LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \19+ cached_property20 from werkzeug.routing import Map, Rule21 from werkzeug.exceptions import HTTPException22 from werkzeug.contrib.securecookie import SecureCookie23 24+# try to load the best simplejson implementation available. If JSON25+# is not installed, we add a failing class.26+json_available = True27+try:28+ import simplejson as json29+except ImportError:30+ try:31+ import json32+ except ImportError:33+ json_available = False34+35 # utilities we import from Werkzeug and Jinja2 that are unused36 # in the module but are exported as public interface.37 from werkzeug import abort, redirect38 from jinja2 import Markup, escape21 unmodified lines60 RequestBase.__init__(self, environ)61 self.endpoint = None62 self.view_args = None63 64+ @cached_property65+ def json(self):66+ """If the mimetype is `application/json` this will contain the67+ parsed JSON data.68+ """69+ if not json_available:70+ raise AttributeError('simplejson not available')71+ if self.mimetype == 'application/json':72+ return json.loads(self.data)73 74+75 class Response(ResponseBase):76 """The response object that is used by default in flask. Works like the77 response object from Werkzeug but is set to have a HTML mimetype by78 default. Quite often you don't have to create this object yourself because23 unmodified lines102 update = setdefault = _fail103 del _fail104 105 84-106 class _RequestContext(object):107 """The request context contains all request relevant information. It is108 created at the beginning of the request and pushed to the109 `_request_ctx_stack` and removed at the end of it. It will create the43 unmodified lines153 154 hello = get_template_attribute('_foo.html', 'hello')155 return hello('World')156 157+ .. versionadded:: 0.2158+159 :param template_name: the name of the template160 :param attribute: the name of the variable of macro to acccess161 """162 return getattr(current_app.jinja_env.get_template(template_name).module,21 unmodified lines184 session.pop('_flashes', [])185 return flashes186 187 188+def jsonify(*args, **kwargs):189+ """Creates a :class:`~flask.Response` with the JSON representation of190+ the given arguments with an `application/json` mimetype. The arguments191+ to this function are the same as to the :class:`dict` constructor.192+193+ Example usage::194+195+ @app.route('/_get_current_user')196+ def get_current_user():197+ return jsonify(username=g.user.username,198+ email=g.user.email,199+ id=g.user.id)200+201+ This will send a JSON response like this to the browser::202+203+ {204+ "username": "admin",205+ "email": "admin@localhost",206+ "id": 42207+ }208+209+ This requires Python 2.6 or an installed version of simplejson.210+211+ .. versionadded:: 0.2212+ """213+ return current_app.response_class(json.dumps(dict(*args, **kwargs),214+ indent=None if request.is_xhr else 2), mimetype='application/json')215+216+217 def render_template(template_name, **context):218 """Renders a template from the template folder with the given219 context.220 156 unmodified lines377 self.jinja_env.globals.update(378 url_for=url_for,379 get_flashed_messages=get_flashed_messages380 )381+ if json_available:382+ self.jinja_env.filters['tojson'] = json.dumps383 384 def create_jinja_loader(self):385 """Creates the Jinja loader. By default just a package loader for386 the configured package is returned that looks up templates in the374 unmodified lines