Skip to content

Commit 1120c0e

Browse files
committed
Initial Flask Javascript Example
0 parents  commit 1120c0e

File tree

14 files changed

+329
-0
lines changed

14 files changed

+329
-0
lines changed

.gitignore

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
venv/
2+
*.pyc
3+
__pycache__/
4+
instance/
5+
.cache/
6+
.pytest_cache/
7+
.coverage
8+
htmlcov/
9+
dist/
10+
build/
11+
*.egg-info/
12+
.idea/
13+
*.swp
14+
*~

LICENSE

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 as
6+
well as documentation, with or without modification, are permitted
7+
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 copyright
13+
notice, this list of conditions and the following disclaimer in the
14+
documentation and/or other materials provided with the distribution.
15+
16+
* Neither the name of the copyright holder nor the names of its
17+
contributors may be used to endorse or promote products derived from
18+
this software without specific prior written permission.
19+
20+
THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND
21+
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
22+
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
23+
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24+
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25+
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26+
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
27+
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
28+
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30+
THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF
31+
SUCH DAMAGE.

MANIFEST.in

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
include LICENSE
2+
graft js_example/templates
3+
graft tests
4+
global-exclude *.pyc

README.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
JavaScript Ajax Example
2+
=======================
3+
4+
Demonstrates how to post form data and process a JSON response using
5+
JavaScript. This allows making requests without navigating away from the
6+
page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and
7+
|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/XMLHttpRequest
11+
12+
.. |fetch| replace:: ``fetch``
13+
.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
14+
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+
Install
22+
-------
23+
24+
::
25+
26+
python3 -m venv venv
27+
. venv/bin/activate
28+
pip install -e .
29+
30+
31+
Run
32+
---
33+
34+
::
35+
36+
export FLASK_APP=js_example
37+
flask run
38+
39+
Open http://127.0.0.1:5000 in a browser.
40+
41+
42+
Test
43+
----
44+
45+
::
46+
47+
pip install -e '.[test]'
48+
coverage run -m pytest
49+
coverage report

js_example/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from flask import Flask
2+
3+
app = Flask(__name__)
4+
5+
from js_example import views

js_example/templates/base.html

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!doctype html>
2+
<title>JavaScript Example</title>
3+
<link rel="stylesheet" href="https://unpkg.com/sakura.css@1.0.0/css/normalize.css">
4+
<link rel="stylesheet" href="https://unpkg.com/sakura.css@1.0.0/css/sakura-earthly.css">
5+
<style>
6+
ul { margin: 0; padding: 0; display: flex; list-style-type: none; }
7+
li > * { padding: 1em; }
8+
li.active > a { color: #5e5e5e; border-bottom: 2px solid #4a4a4a; }
9+
form { display: flex; }
10+
label > input { width: 3em; }
11+
form > * { padding-right: 1em; }
12+
#result { font-weight: bold; }
13+
</style>
14+
<ul>
15+
<li><span>Type:</span>
16+
<li class="{% if js == 'plain' %}active{% endif %}">
17+
<a href="{{ url_for('index', js='plain') }}">Plain</a>
18+
<li class="{% if js == 'fetch' %}active{% endif %}">
19+
<a href="{{ url_for('index', js='fetch') }}">Fetch</a>
20+
<li class="{% if js == 'jquery' %}active{% endif %}">
21+
<a href="{{ url_for('index', js='jquery') }}">jQuery</a>
22+
</ul>
23+
<hr>
24+
<p>{% block intro %}{% endblock %}</p>
25+
<hr>
26+
<form id="calc">
27+
<label>a <input name="a"></label>
28+
<span>+</span>
29+
<label>b <input name="b"></label>
30+
<input type="submit" value="Calculate">
31+
</form>
32+
<span>= <span id="result"></span></span>
33+
{% block script %}{% endblock %}

js_example/templates/fetch.html

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{% extends 'base.html' %}
2+
3+
{% block intro %}
4+
<a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch"><code>fetch</code></a>
5+
is the <em>new</em> plain JavaScript way to make requests. It's
6+
supported in all modern browsers except IE, which requires a
7+
<a href="https://github.com/github/fetch">polyfill</a>.
8+
{% endblock %}
9+
10+
{% block script %}
11+
<script src="https://unpkg.com/promise-polyfill@7.1.2/dist/polyfill.min.js"></script>
12+
<script src="https://unpkg.com/whatwg-fetch@2.0.4/fetch.js"></script>
13+
<script>
14+
function addSubmit(ev) {
15+
ev.preventDefault();
16+
fetch({{ url_for('add')|tojson }}, {
17+
method: 'POST',
18+
body: new FormData(this)
19+
})
20+
.then(parseJSON)
21+
.then(addShow);
22+
}
23+
24+
function parseJSON(response) {
25+
return response.json();
26+
}
27+
28+
function addShow(data) {
29+
var span = document.getElementById('result');
30+
span.innerText = data.result;
31+
}
32+
33+
var form = document.getElementById('calc');
34+
form.addEventListener('submit', addSubmit);
35+
</script>
36+
{% endblock %}

js_example/templates/jquery.html

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{% extends 'base.html' %}
2+
3+
{% block intro %}
4+
<a href="https://jquery.com/">jQuery</a> is a popular library that
5+
adds cross browser APIs for common tasks. However, it requires loading
6+
an extra library.
7+
{% endblock %}
8+
9+
{% block script %}
10+
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
11+
<script>
12+
function addSubmit(ev) {
13+
ev.preventDefault();
14+
$.ajax({
15+
method: 'POST',
16+
url: {{ url_for('add')|tojson }},
17+
data: $(this).serialize()
18+
}).done(addShow);
19+
}
20+
21+
function addShow(data) {
22+
$('#result').text(data.result);
23+
}
24+
25+
$('#calc').on('submit', addSubmit);
26+
</script>
27+
{% endblock %}

js_example/templates/plain.html

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{% extends 'base.html' %}
2+
3+
{% block intro %}
4+
<a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a>
5+
is the plain JavaScript way to make requests. It's natively supported
6+
by all browsers.
7+
{% endblock %}
8+
9+
{% block script %}
10+
<script>
11+
function addSubmit(ev) {
12+
ev.preventDefault();
13+
var request = new XMLHttpRequest();
14+
request.addEventListener('load', addShow);
15+
request.open('POST', {{ url_for('add')|tojson }});
16+
request.send(new FormData(this));
17+
}
18+
19+
function addShow() {
20+
var data = JSON.parse(this.responseText);
21+
var span = document.getElementById('result');
22+
span.innerText = data.result;
23+
}
24+
25+
var form = document.getElementById('calc');
26+
form.addEventListener('submit', addSubmit);
27+
</script>
28+
{% endblock %}

js_example/views.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from flask import jsonify, render_template, request
2+
3+
from js_example import app
4+
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)

0 commit comments

Comments
 (0)