Skip to content

Instantly share code, notes, and snippets.

@Gijs-Koot
Last active February 21, 2020 10:23
Show Gist options
  • Save Gijs-Koot/249d2314defa7c6b72d57c2e6574ca5b to your computer and use it in GitHub Desktop.
Save Gijs-Koot/249d2314defa7c6b72d57c2e6574ca5b to your computer and use it in GitHub Desktop.
Sample flask app with two-way communication

start app

pip install flask
FLASK_DEBUG=1 FLASK_APP=app.py flask run

move index.* files into separate folder static (cannot use folders in gists)

open url in browser

http://localhost:5000/static/index.html
import json
import time
import random
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/coordinates')
def hello_world():
time.sleep(1)
return jsonify({
"coordinates": [random.randint(0, 400) for _ in range(4)]
})
@app.route('/post_image', methods=["POST"])
def get_image():
body = request.json
print(f"received {json.dumps(body, indent=2)}")
return jsonify({
"message": "ok got it",
"vars": list(body.keys())
})
<!doctype html>
<html lang="en">
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
fetch('/coordinates')
.then(res => res.json())
.then(json => console.log("received" + JSON.stringify(json))).then(
e => fetch('/post_image', {
method:"POST",
body: JSON.stringify({
"data": "blabla",
"asdfasd": "asdfasdf"
}),
headers: {
"Content-Type<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Uber Renderer</title>
</head>
<body>
This is the renderer!
<script src="index.js"></script>
</body>
</html>
": "application/json; charset=UTF-8"
}})
).then(
res => console.log(res)
);
}
<head>
<meta charset="utf-8">
<title>Uber Renderer</title>
</head>
<body>
This is the renderer!
<script src="index.js"></script>
</body>
</html>
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
fetch('/coordinates')
.then(res => res.json())
.then(json => console.log("received" + JSON.stringify(json))).then(
e => fetch('/post_image', {
method:"POST",
body: JSON.stringify({
"data": "blabla",
"asdfasd": "asdfasdf"
}),
headers: {
"Content-Type": "application/json; charset=UTF-8"
}})
).then(
res => console.log(res)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment