Skip to content
This repository was archived by the owner on Apr 4, 2021. It is now read-only.

Commit 28216ab

Browse files
committed
Use AJAX requests with the cookie.
1 parent d5ccfc9 commit 28216ab

File tree

3 files changed

+45
-12
lines changed

3 files changed

+45
-12
lines changed

app.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,26 @@
1-
from flask import Flask, make_response, request
1+
from flask import Flask, make_response, request, render_template, jsonify
22

33
app = Flask(__name__)
44

55

66
@app.route('/', methods=["GET"])
77
def index():
8-
response = make_response("Here, take some cookie!")
9-
response.set_cookie(key="id", value="3db4adj3d", path="/about/")
10-
return response
8+
return render_template("index.html")
119

1210

13-
@app.route("/about/", methods=["GET"])
14-
def about():
15-
print(request.cookies)
16-
return "Hello world!"
11+
@app.route("/get-cookie/", methods=["GET"])
12+
def get_cookie():
13+
response = make_response("Here, take some cookie!")
14+
response.set_cookie(key="id", value="3db4adj3d")
15+
return response
1716

1817

19-
@app.route("/contact/", methods=["GET"])
20-
def contact():
21-
print(request.cookies)
22-
return "Hello world!"
18+
@app.route("/api/cities/", methods=["GET"])
19+
def cities():
20+
if request.cookies["id"] == "3db4adj3d":
21+
cities = [{"name": "Rome", "id": 1}, {"name": "Siena", "id": 2}]
22+
return jsonify(cities)
23+
return jsonify(msg="Ops!")
2324

2425

2526
if __name__ == '__main__':

static/index.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const button = document.getElementsByTagName("button")[0];
2+
3+
button.addEventListener("click", function() {
4+
getACookie().then(() => getData());
5+
});
6+
7+
function getACookie() {
8+
return fetch("/get-cookie/").then(response => {
9+
// make sure to check response.ok in the real world!
10+
return Promise.resolve("All good, fetch the data");
11+
});
12+
}
13+
14+
function getData() {
15+
fetch("/api/cities/")
16+
.then(response => {
17+
// make sure to check response.ok in the real world!
18+
return response.json();
19+
})
20+
.then(json => console.log(json));
21+
}

templates/index.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Title</title>
6+
</head>
7+
<body>
8+
<button>FETCH</button>
9+
</body>
10+
<script src="{{ url_for('static', filename='index.js') }}"></script>
11+
</html>

0 commit comments

Comments
 (0)