diff --git a/docs/patterns/jquery.rst b/docs/patterns/jquery.rst index c12f4474..32eb6f04 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -88,7 +88,7 @@ Now let's create a server side function that accepts two URL arguments of numbers which should be added together and then sent back to the application in a JSON object. This is a really ridiculous example and is something you usually would do on the client side alone, but a simple -example that shows how you would use jQuer and Flask nonetheless:: +example that shows how you would use jQuery and Flask nonetheless:: from flask import Flask, jsonify, render_template, request app = Flask(__name__) @@ -108,6 +108,13 @@ template. This template will load jQuery as above and have a little form we can add two numbers and a link to trigger the function on the server side. +Note that we are using the :meth:`~werkzeug.MultiDict.get` method here +which will never fail. If the key is missing a default value (here ``0``) +is returned. Furthermore it can convert values to a specific type (like +in our case `int`). This is especially handy for code that that is +triggered by a script (APIs, JavaScript etc.) because you don't need +special error reporting in that case. + The HTML -------- diff --git a/flask.py b/flask.py index 89a4fee5..bc99bee0 100644 --- a/flask.py +++ b/flask.py @@ -66,8 +66,8 @@ class Request(RequestBase): """If the mimetype is `application/json` this will contain the parsed JSON data. """ - if not json_available: - raise AttributeError('simplejson not available') + if __debug__: + _assert_have_json() if self.mimetype == 'application/json': return json.loads(self.data) @@ -210,6 +210,8 @@ def jsonify(*args, **kwargs): .. versionadded:: 0.2 """ + if __debug__: + _assert_have_json() return current_app.response_class(json.dumps(dict(*args, **kwargs), indent=None if request.is_xhr else 2), mimetype='application/json') @@ -251,6 +253,12 @@ def _default_template_ctx_processor(): ) +def _assert_have_json(): + """Helper function that fails if JSON is unavailable""" + if not json_available: + raise RuntimeError('simplejson not installed') + + def _get_package_path(name): """Returns the path to a package or cwd if that cannot be found.""" try: @@ -261,6 +269,8 @@ def _get_package_path(name): def _tojson_filter(string, *args, **kwargs): """Calls dumps for the template engine, escaping Slashes properly.""" + if __debug__: + _assert_have_json() return json.dumps(string, *args, **kwargs).replace('