Skip to content
Myr

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

21 files+341 added−13 removed

modified:docs/patterns/jquery.rst+3 added-2 removed
160 unmodified lines
161 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.164165If you don't get the whole picture, download the :gh:`sourcecode166for this example <examples/jqueryexample>`.165Check out the :gh:`example source <examples/javascript>` for a full166application demonstrating the jQuery on this page, as well as the same167thing using ``XMLHttpRequest`` and ``fetch``.
modified:docs/testing.rst-6 removed
207 unmodified lines
208 tests/test_flaskr.py::test_messages PASSED209210 ============= 3 passed in 0.23 seconds ==============211212For more complex tests with headers and status codes, check out the213`MiniTwit Example`_ from the sources which contains a larger test214suite.212216.. _MiniTwit Example:217 https://github.com/pallets/flask/tree/master/examples/minitwit/218213Other Testing Tricks214--------------------215216Besides using the test client as shown above, there is also the
240 unmodified lines
added:examples/javascript/js_example/templates/base.html+33 added
added:examples/javascript/js_example/templates/fetch.html+35 added
added:examples/javascript/js_example/templates/jquery.html+27 added
added:examples/javascript/js_example/templates/plain.html+27 added
added:examples/javascript/js_example/__init__.py+5 added
1from flask import Flask23app = Flask(__name__)45from js_example import views
added:examples/javascript/js_example/views.py+16 added
1from flask import jsonify, render_template, request23from js_example import app456@app.route('/', defaults={'js': 'plain'})7@app.route('/<any(plain, jquery, fetch):js>')8def index(js):9 return render_template('{0}.html'.format(js), js=js)101112@app.route('/add', methods=['POST'])13def 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
1import pytest23from js_example import app456@pytest.fixture(name='app')7def fixture_app():8 app.testing = True9 yield app10 app.testing = False111213@pytest.fixture14def client(app):15 return app.test_client()
added:examples/javascript/tests/test_js_example.py+28 added
1import pytest23from flask import template_rendered456@pytest.mark.parametrize(('path', 'template_name'), (7 ('/', 'plain.html'),8 ('/plain', 'plain.html'),9 ('/fetch', 'fetch.html'),10 ('/jquery', 'jquery.html'),11))12def test_index(app, client, path, template_name):13 def check(sender, template, context):14 assert template.name == template_name1516 with template_rendered.connected_to(check, app):17 client.get(path)181920@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))26def test_add(client, a, b, result):27 response = client.post('/add', data={'a': a, 'b': b})28 assert response.get_json()['result'] == result
added:examples/javascript/.gitignore+14 added
1venv/2*.pyc3__pycache__/4instance/5.cache/6.pytest_cache/7.coverage8htmlcov/9dist/10build/11*.egg-info/12.idea/13*.swp14*~
added:examples/javascript/LICENSE+31 added
1Copyright © 2010 by the Pallets team.23Some rights reserved.45Redistribution and use in source and binary forms of the software as6well as documentation, with or without modification, are permitted7provided that the following conditions are met:89* Redistributions of source code must retain the above copyright notice,10 this list of conditions and the following disclaimer.1112* 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.1516* 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.1920THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND21CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,22BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND23FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE24COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,25INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT26NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF27USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON28ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT29(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF30THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF31SUCH DAMAGE.
added:examples/javascript/MANIFEST.in+4 added
1include LICENSE2graft js_example/templates3graft tests4global-exclude *.pyc
added:examples/javascript/README.rst+49 added
1JavaScript Ajax Example2=======================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.89.. |XMLHttpRequest| replace:: ``XMLHttpRequest``10.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest1112.. |fetch| replace:: ``fetch``13.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch1415.. |jQuery.ajax| replace:: ``jQuery.ajax``16.. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/1718.. _Flask docs: http://flask.pocoo.org/docs/patterns/jquery/192021Install22-------2324::2526 python3 -m venv venv27 . venv/bin/activate28 pip install -e .293031Run32---3334::3536 export FLASK_APP=js_example37 flask run3839Open http://127.0.0.1:5000 in a browser.404142Test43----4445::4647 pip install -e '.[test]'48 coverage run -m pytest49 coverage report
added:examples/javascript/setup.cfg+13 added
1[metadata]2license_file = LICENSE34[bdist_wheel]5universal = True67[tool:pytest]8testpaths = tests910[coverage:run]11branch = True12source =13 js_example
added:examples/javascript/setup.py+30 added
1import io23from setuptools import find_packages, setup45with io.open('README.rst', 'rt', encoding='utf8') as f:6 readme = f.read()78setup(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 lines
55 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)6061 if error is None:62 # the name is available, store it in the database and go to63 # the login page
45 unmodified lines
modified:examples/tutorial/README.rst+1 added-2 removed
63 unmodified lines
64----6566::6768 pip install pytest68 pip install '.[test]'69 pytest7071Run with coverage report::7273 pip install pytest coverage73 coverage run -m pytest74 coverage report75 coverage html # open htmlcov/index.html in a browser
modified:examples/tutorial/setup.cfg+1 added-1 removed
1[metadata]2license_file = LICENSE34[bdist_wheel]5universal = False5universal = True67[tool:pytest]8testpaths = tests9
4 unmodified lines
modified:examples/tutorial/setup.py+6 added
18 unmodified lines
19 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 lines
30 simplejson: simplejson3132commands =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]3637 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest tests examples39
24 unmodified lines