Merge pull request #2699 from pallets/javascript
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add javascript ajax example
authored by David Lord · committed by GitHub · parents d8bf589, fce1885 · Browse files · 21 files·+341 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+341 added−13 removed
- tests:+43 added−0 removed
- other:+298 added−13 removed
Provenance
- Commit
746b91d- Tree
05cedc3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d8bf589- Parent 2
fce1885
21 files changed+341 added−13 removed
modified:docs/patterns/jquery.rst+3 added-2 removed
160 unmodified lines161 data arrived, it will call the given function with the return value as162 argument. Note that we can use the `$SCRIPT_ROOT` variable here that163 we set earlier.164 165-If you don't get the whole picture, download the :gh:`sourcecode166-for this example <examples/jqueryexample>`.165+Check out the :gh:`example source <examples/javascript>` for a full166+application demonstrating the jQuery on this page, as well as the same167+thing using ``XMLHttpRequest`` and ``fetch``.modified:docs/testing.rst-6 removed
207 unmodified lines208 tests/test_flaskr.py::test_messages PASSED209 210 ============= 3 passed in 0.23 seconds ==============211 212-For more complex tests with headers and status codes, check out the213-`MiniTwit Example`_ from the sources which contains a larger test214-suite.212 216-.. _MiniTwit Example:217- https://github.com/pallets/flask/tree/master/examples/minitwit/218-213 Other Testing Tricks214 --------------------215 216 Besides using the test client as shown above, there is also the240 unmodified linesadded:examples/javascript/js_example/templates/base.html+33 added
123456789101112131415161718192021222324252627282930313233<!doctype html><title>JavaScript Example</title><link rel="stylesheet" href="https://unpkg.com/sakura.css@1.0.0/css/normalize.css"><link rel="stylesheet" href="https://unpkg.com/sakura.css@1.0.0/css/sakura-earthly.css"><style> ul { margin: 0; padding: 0; display: flex; list-style-type: none; } li > * { padding: 1em; } li.active > a { color: #5e5e5e; border-bottom: 2px solid #4a4a4a; } form { display: flex; } label > input { width: 3em; } form > * { padding-right: 1em; } #result { font-weight: bold; }</style><ul> <li><span>Type:</span> <li class="{% if js == 'plain' %}active{% endif %}"> <a href="{{ url_for('index', js='plain') }}">Plain</a> <li class="{% if js == 'fetch' %}active{% endif %}"> <a href="{{ url_for('index', js='fetch') }}">Fetch</a> <li class="{% if js == 'jquery' %}active{% endif %}"> <a href="{{ url_for('index', js='jquery') }}">jQuery</a></ul><hr><p>{% block intro %}{% endblock %}</p><hr><form> <label>a <input name="a"></label> <span>+</span> <label>b <input name="b"></label> <input type="submit" value="Calculate"></form><span>= <span id="result"></span></span>{% block script %}{% endblock %}added:examples/javascript/js_example/templates/fetch.html+35 added
1234567891011121314151617181920212223242526272829303132333435{% extends 'base.html' %}
{% block intro %} <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch"><code>fetch</code></a> is the <em>new</em> plain JavaScript way to make requests. It's supported in all modern browsers except IE, which requires a <a href="https://github.com/github/fetch">polyfill</a>.{% endblock %}
{% block script %} <script src="https://unpkg.com/promise-polyfill@7.1.2/dist/polyfill.min.js"></script> <script src="https://unpkg.com/whatwg-fetch@2.0.4/fetch.js"></script> <script> function addSubmit(ev) { ev.preventDefault(); fetch('{{ url_for('add') }}', { method: 'POST', body: new FormData(this) }) .then(parseJSON) .then(addShow); }
function parseJSON(response) { return response.json(); }
function addShow(data) { var span = document.getElementById('result'); span.innerText = data.result; }
document.forms[0].addEventListener('submit', addSubmit); </script>{% endblock %}added:examples/javascript/js_example/templates/jquery.html+27 added
123456789101112131415161718192021222324252627{% extends 'base.html' %}
{% block intro %} <a href="https://jquery.com/">jQuery</a> is a popular library that adds cross browser APIs for common tasks. However, it requires loading an extra library.{% endblock %}
{% block script %} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> function addSubmit(ev) { ev.preventDefault(); $.ajax({ method: 'POST', url: '{{ url_for('add') }}', data: $(this).serialize() }).done(addShow); }
function addShow(data) { $('#result').text(data.result); }
$('form:first').on('submit', addSubmit); </script>{% endblock %}added:examples/javascript/js_example/templates/plain.html+27 added
123456789101112131415161718192021222324252627{% extends 'base.html' %}
{% block intro %} <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> is the plain JavaScript way to make requests. It's natively supported by all browsers.{% endblock %}
{% block script %} <script> function addSubmit(ev) { ev.preventDefault(); var request = new XMLHttpRequest(); request.addEventListener('load', addShow); request.open('POST', '{{ url_for('add') }}'); request.send(new FormData(this)); }
function addShow() { var data = JSON.parse(this.responseText); var span = document.getElementById('result'); span.innerText = data.result; }
document.forms[0].addEventListener('submit', addSubmit); </script>{% endblock %}added:examples/javascript/js_example/__init__.py+5 added
1+from flask import Flask2+3+app = Flask(__name__)4+5+from js_example import viewsadded:examples/javascript/js_example/views.py+16 added
1+from flask import jsonify, render_template, request2+3+from js_example import app4+5+6+@app.route('/', defaults={'js': 'plain'})7+@app.route('/<any(plain, jquery, fetch):js>')8+def index(js):9+ return render_template('{0}.html'.format(js), js=js)10+11+12+@app.route('/add', methods=['POST'])13+def add():14+ a = request.form.get('a', 0, type=float)15+ b = request.form.get('b', 0, type=float)16+ return jsonify(result=a + b)added:examples/javascript/tests/conftest.py+15 added
1+import pytest2+3+from js_example import app4+5+6+@pytest.fixture(name='app')7+def fixture_app():8+ app.testing = True9+ yield app10+ app.testing = False11+12+13+@pytest.fixture14+def client(app):15+ return app.test_client()added:examples/javascript/tests/test_js_example.py+28 added
1+import pytest2+3+from flask import template_rendered4+5+6+@pytest.mark.parametrize(('path', 'template_name'), (7+ ('/', 'plain.html'),8+ ('/plain', 'plain.html'),9+ ('/fetch', 'fetch.html'),10+ ('/jquery', 'jquery.html'),11+))12+def test_index(app, client, path, template_name):13+ def check(sender, template, context):14+ assert template.name == template_name15+16+ with template_rendered.connected_to(check, app):17+ client.get(path)18+19+20+@pytest.mark.parametrize(('a', 'b', 'result'), (21+ (2, 3, 5),22+ (2.5, 3, 5.5),23+ (2, None, 2),24+ (2, 'b', 2),25+))26+def test_add(client, a, b, result):27+ response = client.post('/add', data={'a': a, 'b': b})28+ assert response.get_json()['result'] == resultadded:examples/javascript/.gitignore+14 added
1+venv/2+*.pyc3+__pycache__/4+instance/5+.cache/6+.pytest_cache/7+.coverage8+htmlcov/9+dist/10+build/11+*.egg-info/12+.idea/13+*.swp14+*~added:examples/javascript/LICENSE+31 added
1+Copyright © 2010 by the Pallets team.2+3+Some rights reserved.4+5+Redistribution and use in source and binary forms of the software as6+well as documentation, with or without modification, are permitted7+provided that the following conditions are met:8+9+* Redistributions of source code must retain the above copyright notice,10+ this list of conditions and the following disclaimer.11+12+* Redistributions in binary form must reproduce the above copyright13+ notice, this list of conditions and the following disclaimer in the14+ documentation and/or other materials provided with the distribution.15+16+* Neither the name of the copyright holder nor the names of its17+ contributors may be used to endorse or promote products derived from18+ this software without specific prior written permission.19+20+THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND21+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,22+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND23+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE24+COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,25+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT26+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF27+USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON28+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF30+THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF31+SUCH DAMAGE.added:examples/javascript/MANIFEST.in+4 added
1+include LICENSE2+graft js_example/templates3+graft tests4+global-exclude *.pycadded:examples/javascript/README.rst+49 added
1+JavaScript Ajax Example2+=======================3+4+Demonstrates how to post form data and process a JSON response using5+JavaScript. This allows making requests without navigating away from the6+page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and7+|jQuery.ajax|_. See the `Flask docs`_ about jQuery and Ajax.8+9+.. |XMLHttpRequest| replace:: ``XMLHttpRequest``10+.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest11+12+.. |fetch| replace:: ``fetch``13+.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch14+15+.. |jQuery.ajax| replace:: ``jQuery.ajax``16+.. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/17+18+.. _Flask docs: http://flask.pocoo.org/docs/patterns/jquery/19+20+21+Install22+-------23+24+::25+26+ python3 -m venv venv27+ . venv/bin/activate28+ pip install -e .29+30+31+Run32+---33+34+::35+36+ export FLASK_APP=js_example37+ flask run38+39+Open http://127.0.0.1:5000 in a browser.40+41+42+Test43+----44+45+::46+47+ pip install -e '.[test]'48+ coverage run -m pytest49+ coverage reportadded:examples/javascript/setup.cfg+13 added
1+[metadata]2+license_file = LICENSE3+4+[bdist_wheel]5+universal = True6+7+[tool:pytest]8+testpaths = tests9+10+[coverage:run]11+branch = True12+source =13+ js_exampleadded:examples/javascript/setup.py+30 added
1+import io2+3+from setuptools import find_packages, setup4+5+with io.open('README.rst', 'rt', encoding='utf8') as f:6+ readme = f.read()7+8+setup(9+ name='js_example',10+ version='1.0.0',11+ url='http://flask.pocoo.org/docs/patterns/jquery/',12+ license='BSD',13+ maintainer='Pallets team',14+ maintainer_email='contact@palletsprojects.com',15+ description='Demonstrates making Ajax requests to Flask.',16+ long_description=readme,17+ packages=find_packages(),18+ include_package_data=True,19+ zip_safe=False,20+ install_requires=[21+ 'flask',22+ ],23+ extras_require={24+ 'test': [25+ 'pytest',26+ 'coverage',27+ 'blinker',28+ ],29+ },30+)modified:examples/tutorial/flaskr/auth.py+1 added-1 removed
54 unmodified lines55 error = 'Password is required.'56 elif db.execute(57 'SELECT id FROM user WHERE username = ?', (username,)58 ).fetchone() is not None:59- error = 'User {} is already registered.'.format(username)59+ error = 'User {0} is already registered.'.format(username)60 61 if error is None:62 # the name is available, store it in the database and go to63 # the login page45 unmodified linesmodified:examples/tutorial/README.rst+1 added-2 removed
63 unmodified lines64 ----65 66 ::67 68- pip install pytest68+ pip install '.[test]'69 pytest70 71 Run with coverage report::72 73- pip install pytest coverage73 coverage run -m pytest74 coverage report75 coverage html # open htmlcov/index.html in a browsermodified:examples/tutorial/setup.cfg+1 added-1 removed
1 [metadata]2 license_file = LICENSE3 4 [bdist_wheel]5-universal = False5+universal = True6 7 [tool:pytest]8 testpaths = tests9 4 unmodified linesmodified:examples/tutorial/setup.py+6 added
18 unmodified lines19 zip_safe=False,20 install_requires=[21 'flask',22 ],23+ extras_require={24+ 'test': [25+ 'pytest',26+ 'coverage',27+ ],28+ },29 )modified:tox.ini+2 added-1 removed
29 unmodified lines30 simplejson: simplejson31 32 commands =33 # the examples need to be installed to test successfully34- pip install -e examples/tutorial -q34+ pip install -q -e examples/tutorial[test]35+ pip install -q -e examples/javascript[test]36 37 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest tests examples39 24 unmodified lines