Skip to content
Myr

Merge pull request #4636 from pallets/docs-javascript

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by GitHub · parents ebc0d30, 2f3c87d · Browse files · 11 files+311 added−196 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+311 added−196 removed

  • tests:+2 added−2 removed
  • other:+309 added−194 removed

11 files+311 added−196 removed

modified:docs/patterns/index.rst+1 added-1 removed
27 unmodified lines
28 viewdecorators29 wtforms30 templateinheritance31 flashing32 jquery32 javascript33 lazyloading34 mongoengine35 favicon36 streaming
6 unmodified lines
added:docs/patterns/javascript.rst+259 added
1JavaScript, ``fetch``, and JSON2===============================34You may want to make your HTML page dynamic, by changing data without5reloading the entire page. Instead of submitting an HTML ``<form>`` and6performing a redirect to re-render the template, you can add7`JavaScript`_ that calls |fetch|_ and replaces content on the page.89|fetch|_ is the modern, built-in JavaScript solution to making10requests from a page. You may have heard of other "AJAX" methods and11libraries, such as |XHR|_ or `jQuery`_. These are no longer needed in12modern browsers, although you may choose to use them or another library13depending on your application's requirements. These docs will only focus14on built-in JavaScript features.1516.. _JavaScript: https://developer.mozilla.org/Web/JavaScript17.. |fetch| replace:: ``fetch()``18.. _fetch: https://developer.mozilla.org/Web/API/Fetch_API19.. |XHR| replace:: ``XMLHttpRequest()``20.. _XHR: https://developer.mozilla.org/Web/API/XMLHttpRequest21.. _jQuery: https://jquery.com/222324Rendering Templates25-------------------2627It is important to understand the difference between templates and28JavaScript. Templates are rendered on the server, before the response is29sent to the user's browser. JavaScript runs in the user's browser, after30the template is rendered and sent. Therefore, it is impossible to use31JavaScript to affect how the Jinja template is rendered, but is is32possible to render data into the JavaScript that will run.3334To provide data to JavaScript when rendering the template, use the35:func:`~jinja-filters.tojson` filter in a ``<script>`` block. This will36convert the data to a valid JavaScript object, and ensure that any37unsafe HTML characters are rendered safely. If you do not use the38``tojson`` filter, you will get a ``SyntaxError`` in the browser39console.4041.. code-block:: python4243 data = generate_report()44 return render_template("report.html", chart_data=data)4546.. code-block:: jinja4748 <script>49 const chart_data = {{ chart_data|tojson }}50 chartLib.makeChart(chart_data)51 </script>5253A less common pattern is to add the data to a ``data-`` attribute on an54HTML tag. In this case, you must use single quotes around the value, not55double quotes, otherwise you will produce invalid or unsafe HTML.5657.. code-block:: jinja5859 <div data-chart='{{ chart_data|tojson }}'></div>606162Generating URLs63---------------6465The other way to get data from the server to JavaScript is to make a66request for it. First, you need to know the URL to request.6768The simplest way to generate URLs is to continue to use69:func:`~flask.url_for` when rendering the template. For example:7071.. code-block:: javascript7273 const user_url = {{ url_for("user", id=current_user.id)|tojson }}74 fetch(user_url).then(...)7576However, you might need to generate a URL based on information you only77know in JavaScript. As discussed above, JavaScript runs in the user's78browser, not as part of the template rendering, so you can't use79``url_for`` at that point.8081In this case, you need to know the "root URL" under which your82application is served. In simple setups, this is ``/``, but it might83also be something else, like ``https://example.com/myapp/``.8485A simple way to tell your JavaScript code about this root is to set it86as a global variable when rendering the template. Then you can use it87when generating URLs from JavaScript.8889.. code-block:: javascript9091 const SCRIPT_ROOT = {{ request.script_root|tojson }}92 let user_id = ... // do something to get a user id from the page93 let user_url = `${SCRIPT_ROOT}/user/${user_id}`94 fetch(user_url).then(...)959697Making a Request with ``fetch``98-------------------------------99100|fetch|_ takes two arguments, a URL and an object with other options,101and returns a |Promise|_. We won't cover all the available options, and102will only use ``then()`` on the promise, not other callbacks or103``await`` syntax. Read the linked MDN docs for more information about104those features.105106By default, the GET method is used. If the response contains JSON, it107can be used with a ``then()`` callback chain.108109.. code-block:: javascript110111 const room_url = {{ url_for("room_detail", id=room.id)|tojson }}112 fetch(room_url)113 .then(response => response.json())114 .then(data => {115 // data is a parsed JSON object116 })117118To send data, use a data method such as POST, and pass the ``body``119option. The most common types for data are form data or JSON data.120121To send form data, pass a populated |FormData|_ object. This uses the122same format as an HTML form, and would be accessed with ``request.form``123in a Flask view.124125.. code-block:: javascript126127 let data = new FormData()128 data.append("name": "Flask Room")129 data.append("description": "Talk about Flask here.")130 fetch(room_url, {131 "method": "POST",132 "body": data,133 }).then(...)134135In general, prefer sending request data as form data, as would be used136when submitting an HTML form. JSON can represent more complex data, but137unless you need that it's better to stick with the simpler format. When138sending JSON data, the ``Content-Type: application/json`` header must be139sent as well, otherwise Flask will return a 400 error.140141.. code-block:: javascript142143 let data = {144 "name": "Flask Room",145 "description": "Talk about Flask here.",146 }147 fetch(room_url, {148 "method": "POST",149 "headers": {"Content-Type": "application/json"},150 "body": JSON.stringify(data),151 }).then(...)152153.. |Promise| replace:: ``Promise``154.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise155.. |FormData| replace:: ``FormData``156.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData157158159Following Redirects160-------------------161162A response might be a redirect, for example if you logged in with163JavaScript instead of a traditional HTML form, and your view returned164a redirect instead of JSON. JavaScript requests do follow redirects, but165they don't change the page. If you want to make the page change you can166inspect the response and apply the redirect manually.167168.. code-block:: javascript169170 fetch("/login", {"body": ...}).then(171 response => {172 if (response.redirected) {173 window.location = response.url174 } else {175 showLoginError()176 }177 }178 )179180181Replacing Content182-----------------183184A response might be new HTML, either a new section of the page to add or185replace, or an entirely new page. In general, if you're returning the186entire page, it would be better to handle that with a redirect as shown187in the previous section. The following example shows how to a ``<div>``188with the HTML returned by a request.189190.. code-block:: html191192 <div id="geology-fact">193 {{ include "geology_fact.html" }}194 </div>195 <script>196 const geology_url = {{ url_for("geology_fact")|tojson }}197 const geology_div = getElementById("geology-fact")198 fetch(geology_url)199 .then(response => response.text)200 .then(text => geology_div.innerHtml = text)201 </script>202203204Return JSON from Views205----------------------206207To return a JSON object from your API view, you can directly return a208dict from the view. It will be serialized to JSON automatically.209210.. code-block:: python211212 @app.route("/user/<int:id>")213 def user_detail(id):214 user = User.query.get_or_404(id)215 return {216 "username": User.username,217 "email": User.email,218 "picture": url_for("static", filename=f"users/{id}/profile.png"),219 }220221If you want to return another JSON type, use the222:func:`~flask.json.jsonify` function, which creates a response object223with the given data serialized to JSON.224225.. code-block:: python226227 from flask import jsonify228229 @app.route("/users")230 def user_list():231 users = User.query.order_by(User.name).all()232 return jsonify([u.to_json() for u in users])233234It is usually not a good idea to return file data in a JSON response.235JSON cannot represent binary data directly, so it must be base64236encoded, which can be slow, takes more bandwidth to send, and is not as237easy to cache. Instead, serve files using one view, and generate a URL238to the desired file to include in the JSON. Then the client can make a239separate request to get the linked resource after getting the JSON.240241242Receiving JSON in Views243-----------------------244245Use the :attr:`~flask.Request.json` property of the246:data:`~flask.request` object to decode the request's body as JSON. If247the body is not valid JSON, or the ``Content-Type`` header is not set to248``application/json``, a 400 Bad Request error will be raised.249250.. code-block:: python251252 from flask import request253254 @app.post("/user/<int:id>")255 def user_update(id):256 user = User.query.get_or_404(id)257 user.update_from_json(request.json)258 db.session.commit()259 return user.to_json()
modified:docs/patterns/jquery.rst+3 added-145 removed
1:orphan:23AJAX with jQuery4================54`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.89JSON itself is a very lightweight transport format, very similar to how10Python primitives (numbers, strings, dicts and lists) look like which is11widely supported and very easy to parse. It became popular a few years12ago and quickly replaced XML as transport format in web applications.1314.. _jQuery: https://jquery.com/1516Loading jQuery17--------------1819In order to use jQuery, you have to download it first and place it in the20static folder of your application and then ensure it's loaded. Ideally21you have a layout template that is used for all pages where you just have22to add a script statement to the bottom of your ``<body>`` to load jQuery:2324.. sourcecode:: html2526 <script src="{{ url_for('static', filename='jquery.js') }}"></script>2728Another method is using Google's `AJAX Libraries API29<https://developers.google.com/speed/libraries/>`_ to load jQuery:3031.. sourcecode:: html3233 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>34 <script>window.jQuery || document.write('<script src="{{35 url_for('static', filename='jquery.js') }}">\x3C/script>')</script>3637In this case you have to put jQuery into your static folder as a fallback, but it will38first try to load it directly from Google. This has the advantage that your39website will probably load faster for users if they went to at least one40other website before using the same jQuery version from Google because it41will already be in the browser cache.4243Where is My Site?44-----------------4546Do you know where your application is? If you are developing the answer47is quite simple: it's on localhost port something and directly on the root48of that server. But what if you later decide to move your application to49a different location? For example to ``http://example.com/myapp``? On50the server side this never was a problem because we were using the handy51:func:`~flask.url_for` function that could answer that question for52us, but if we are using jQuery we should not hardcode the path to53the application but make that dynamic, so how can we do that?5455A simple method would be to add a script tag to our page that sets a56global variable to the prefix to the root of the application. Something57like this:5859.. sourcecode:: html+jinja6061 <script>62 $SCRIPT_ROOT = {{ request.script_root|tojson }};63 </script>646566JSON View Functions67-------------------6869Now let's create a server side function that accepts two URL arguments of70numbers which should be added together and then sent back to the71application in a JSON object. This is a really ridiculous example and is72something you usually would do on the client side alone, but a simple73example that shows how you would use jQuery and Flask nonetheless::7475 from flask import Flask, jsonify, render_template, request76 app = Flask(__name__)7778 @app.route('/_add_numbers')79 def add_numbers():80 a = request.args.get('a', 0, type=int)81 b = request.args.get('b', 0, type=int)82 return jsonify(result=a + b)8384 @app.route('/')85 def index():86 return render_template('index.html')8788As you can see I also added an `index` method here that renders a89template. This template will load jQuery as above and have a little form where90we can add two numbers and a link to trigger the function on the server91side.9293Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here94which will never fail. If the key is missing a default value (here ``0``)95is returned. Furthermore it can convert values to a specific type (like96in our case `int`). This is especially handy for code that is97triggered by a script (APIs, JavaScript etc.) because you don't need98special error reporting in that case.99100The HTML101--------102103Your index.html template either has to extend a :file:`layout.html` template with104jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.105Here's the HTML code needed for our little application (:file:`index.html`).106Notice that we also drop the script directly into the HTML here. It is107usually a better idea to have that in a separate script file:108109.. sourcecode:: html110111 <script>112 $(function() {113 $('a#calculate').bind('click', function() {114 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {115 a: $('input[name="a"]').val(),116 b: $('input[name="b"]').val()117 }, function(data) {118 $("#result").text(data.result);119 });120 return false;121 });122 });123 </script>124 <h1>jQuery Example</h1>125 <p><input type=text size=5 name=a> +126 <input type=text size=5 name=b> =127 <span id=result>?</span>128 <p><a href=# id=calculate>calculate server side</a>129130I won't go into detail here about how jQuery works, just a very quick131explanation of the little bit of code above:1321331. ``$(function() { ... })`` specifies code that should run once the134 browser is done loading the basic parts of the page.1352. ``$('selector')`` selects an element and lets you operate on it.1363. ``element.bind('event', func)`` specifies a function that should run137 when the user clicked on the element. If that function returns138 `false`, the default behavior will not kick in (in this case, navigate139 to the `#` URL).1404. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will141 send the contents of the `data` object as query parameters. Once the142 data arrived, it will call the given function with the return value as143 argument. Note that we can use the `$SCRIPT_ROOT` variable here that144 we set earlier.145146Check out the :gh:`example source <examples/javascript>` for a full147application demonstrating the code on this page, as well as the same148thing using ``XMLHttpRequest`` and ``fetch``.6Obsolete, see :doc:`/patterns/javascript` instead.
modified:examples/javascript/js_example/templates/base.html+4 added-4 removed
modified:examples/javascript/js_example/templates/fetch.html+2 added-5 removed
deleted:examples/javascript/js_example/templates/plain.html-28 removed
added:examples/javascript/js_example/templates/xhr.html+29 added
modified:examples/javascript/js_example/views.py+2 added-2 removed
3 unmodified lines
45from js_example import app678@app.route("/", defaults={"js": "plain"})9@app.route("/<any(plain, jquery, fetch):js>")8@app.route("/", defaults={"js": "fetch"})9@app.route("/<any(xhr, jquery, fetch):js>")10def index(js):11 return render_template(f"{js}.html", js=js)1213
5 unmodified lines
modified:examples/javascript/tests/test_js_example.py+2 added-2 removed
3 unmodified lines
45@pytest.mark.parametrize(6 ("path", "template_name"),7 (8 ("/", "plain.html"),9 ("/plain", "plain.html"),8 ("/", "xhr.html"),9 ("/plain", "xhr.html"),10 ("/fetch", "fetch.html"),11 ("/jquery", "jquery.html"),12 ),13)
14 unmodified lines
modified:examples/javascript/README.rst+8 added-8 removed
1 unmodified line
2=======================34Demonstrates how to post form data and process a JSON response using5JavaScript. This allows making requests without navigating away from the6page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and7|jQuery.ajax|_. See the `Flask docs`_ about jQuery and Ajax.6page. Demonstrates using |fetch|_, |XMLHttpRequest|_, and7|jQuery.ajax|_. See the `Flask docs`_ about JavaScript and Ajax.89.. |XMLHttpRequest| replace:: ``XMLHttpRequest``10.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest119.. |fetch| replace:: ``fetch``10.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch1112.. |XMLHttpRequest| replace:: ``XMLHttpRequest``13.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest1415.. |jQuery.ajax| replace:: ``jQuery.ajax``16.. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/1718.. _Flask docs: https://flask.palletsprojects.com/patterns/jquery/
1 unmodified line
2021Install22-------2324::24.. code-block:: text2526 $ python3 -m venv venv27 $ . venv/bin/activate28 $ pip install -e .
1 unmodified line
3031Run32---3334::34.. code-block:: text3536 $ export FLASK_APP=js_example37 $ flask run38
2 unmodified lines
4142Test43----4445::45.. code-block:: text4647 $ pip install -e '.[test]'48 $ coverage run -m pytest49 $ coverage report
modified:examples/javascript/setup.cfg+1 added-1 removed
1[metadata]2name = js_example3version = 1.0.03version = 1.1.04url = https://flask.palletsprojects.com/patterns/jquery/5license = BSD-3-Clause6maintainer = Pallets7maintainer_email = contact@palletsprojects.com
22 unmodified lines