Skip to content
Myr

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

7 files+254 added−9 removed

modified:docs/patterns/index.rst+1 added
17 unmodified lines
18 sqlalchemy19 wtforms20 templateinheritance21 flashing22 jquery
added:docs/patterns/jquery.rst+59 added
1AJAX With jQuery2================34`jQuery`_ is a small JavaScript library commonly used to simplify working5with the DOM and JavaScript in general. It is the perfect tool to make6web applications more dynamic by exchanging JSON between server and7client.89.. _jQuery: http://jquery.com/1011Loading jQuery12--------------1314In order to use jQuery, you have to download it first and place it in the15static folder of your application and then ensure it's loaded. Ideally16you have a layout template that is used for all pages where you just have17to add two script statements to your `head` section. One for jQuery, and18one for your own script (called `app.js` here):1920.. sourcecode:: html2122 <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>2627Where is My Site?28-----------------2930Do you know where your application is? If you are developing the answer31is quite simple: it's on localhost port something and directly on the root32of that server. But what if you later decide to move your application to33a different location? For example to ``http://example.com/myapp``? On34the server side this never was a problem because we were using the handy35:func:`~flask.url_for` function that did could answer that question for36us, but if we are using jQuery we should better not hardcode the path to37the application but make that dynamic, so how can we do that?3839A simple method would be to add a script tag to our page that sets a40global variable to the prefix to the root of the application. Something41like this:4243.. sourcecode:: html+jinja4445 <script type=text/javascript>46 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};47 </script>4849The ``|safe`` is necessary so that Jinja does not escape the JSON encoded50string with HTML rules. Usually this would be necessary, but we are51inside a `script` block here where different rules apply.5253.. admonition:: Information for Pros5455 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 lines
55 the request.5657 .. attribute:: stream5859 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:: data6564 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.6869 .. attribute:: files7071 A :class:`~werkzeug.MultiDict` with files uploaded as part of a
36 unmodified lines
108 `base_url` ``http://www.example.com/myapplication/page.html?x=y``109 `root_url` ``http://www.example.com/myapplication/``110 ============= ======================================================111112 .. attribute:: is_xhr113114 `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.119120 .. attribute:: json121122 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.125126Response Objects127----------------128129.. autoclass:: flask.Response
87 unmodified lines
217.. autofunction:: flash218219.. autofunction:: get_flashed_messages220221Returning JSON222--------------223224.. autofunction:: jsonify225226.. data:: json227228 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::230231 try:232 import simplejson as json233 except ImportError:234 import json235236 You can instead just do this::237238 from flask import json239240 For usage examples, read the :mod:`json` documentation.241242 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:246247 .. sourcecode:: html+jinja248249 <script type=text/javascript>250 doSomethingWith({{ user.username|tojson|safe }});251 </script>252253Template Rendering254------------------255256.. autofunction:: render_template
4 unmodified lines
added:examples/jqueryexample/templates/index.html+25 added
added:examples/jqueryexample/jqueryexample.py+29 added
1# -*- coding: utf-8 -*-2"""3 jQuery Example4 ~~~~~~~~~~~~~~56 A simple application that shows how Flask and jQuery get along.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from flask import Flask, jsonify, render_template, request12app = Flask(__name__)131415@app.route('/_add_numbers')16def 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)212223@app.route('/')24def index():25 return render_template('index.html')262728if __name__ == '__main__':29 app.run()
modified:tests/flask_tests.py+30 added-2 removed
30 unmodified lines
31 with app.test_request_context('/meh'):32 assert meh() == 'http://localhost/meh'333435class BasicFunctionality(unittest.TestCase):35class BasicFunctionalityTestCase(unittest.TestCase):3637 def test_request_dispatching(self):38 app = flask.Flask(__name__)39 @app.route('/')
126 unmodified lines
166 assert flask.url_for('static', filename='index.html') \167 == '/static/index.html'168169170class Templating(unittest.TestCase):170class JSONTestCase(unittest.TestCase):171172 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) == d186187 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'196197198class TemplatingTestCase(unittest.TestCase):199200 def test_context_processing(self):201 app = flask.Flask(__name__)202 @app.context_processor203 def context_processor():
33 unmodified lines
modified:flask.py+56 added-2 removed
13 unmodified lines
14import sys1516from jinja2 import Environment, PackageLoader, FileSystemLoader17from werkzeug import Request as RequestBase, Response as ResponseBase, \18 LocalStack, LocalProxy, create_environ, SharedDataMiddleware18 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \19 cached_property20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException22from werkzeug.contrib.securecookie import SecureCookie2324# try to load the best simplejson implementation available. If JSON25# is not installed, we add a failing class.26json_available = True27try:28 import simplejson as json29except ImportError:30 try:31 import json32 except ImportError:33 json_available = False3435# utilities we import from Werkzeug and Jinja2 that are unused36# in the module but are exported as public interface.37from werkzeug import abort, redirect38from jinja2 import Markup, escape
21 unmodified lines
60 RequestBase.__init__(self, environ)61 self.endpoint = None62 self.view_args = None6364 @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)737475class 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 because
23 unmodified lines
102 update = setdefault = _fail103 del _fail10410584106class _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 the
43 unmodified lines
153154 hello = get_template_attribute('_foo.html', 'hello')155 return hello('World')156157 .. versionadded:: 0.2158159 :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 lines
184 session.pop('_flashes', [])185 return flashes186187188def 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.192193 Example usage::194195 @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)200201 This will send a JSON response like this to the browser::202203 {204 "username": "admin",205 "email": "admin@localhost",206 "id": 42207 }208209 This requires Python 2.6 or an installed version of simplejson.210211 .. 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')215216217def render_template(template_name, **context):218 """Renders a template from the template folder with the given219 context.220
156 unmodified lines
377 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.dumps383384 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 the
374 unmodified lines