So Flask does have a way to do this, but it's kind of hacky and took forever for me to finally find and figure out the solution- I was having this problem too.
There's 3 parts to this:
- Get the dictionary information in Python
- Embed the data into your webpage
- Access that data from your JavaScript/TypeScript code
Step 1
Setup the Python dictionary for external use
Somewhere in your Flask code in either the __init__.py
file, the routes.py
file, or some other similarly accessible file, have the following setup:
all = {"some":"random data"}
@server.context_processor
def inject_data() -> dict:
# .context_processor information: https://stackoverflow.com/a/43336023/8705841
flask_data = {'all',
'the',
'python',
'variables',
'you',
'want',
'in',
'your',
'js_or_ts'}
# Create a dictionary from a list of variables: https://stackoverflow.com/a/9496018/8705841
return {'flask_data': dict(((k, eval(k)) for k in flask_data))}
The @server
part should match the name of your Flask app variable (instantiated with server = Flask(__name__)
) and does not particularly matter (usually it's called app
). The flask_data
dict/list should have all the Python variables you want ported over to the front end, but with quotes around them- the eval
part of the return will grab the Python variable that matches the input string k
.
Step 2
Make the data available on the webpage
In your index.html
page, inside the <head>
tag (next to your other <script>
tags, have this tag as well:
<head>
<!-- a whole bunch of stuff -->
<!-- get all the Flask variables from Python -> TypeScript -->
<script id=flask_data type="text/json">{{ flask_data|tojson }}</script>
<!-- possibly a whole bunch more stuff -->
</head>
Basically every single StackOverflow post even mentioning Flask has the above copy-pasted.
Step 3
Access the data from any of your JavaScript files
This is the part that no one else talked about- actually using your data from within your JavaScript (or TypeScript) code, regardless of your directory setup. It's a little hacky, but basically you access the HTML element that has your embedded data and then parse it for use in your program however you want. This is technically TypeScript code, but should work for both JavaScript and TypeScript (it took a ton of trial and error to finally get it to work on my TypeScript build).
foo() {
const flask_data = JSON.parse((document.querySelector('#flask_data') as HTMLElement).textContent || "");
this.version = flask_data.version
const my_flask_var = flask_data.my_flask_var;
console.log("Data: " + flask_data);
console.log("Variable: " + my_flask_var);
console.log("Running verison '" + this.version + "'");
if (my_flask_var === "some value") {
do_something();
else {
do_something_else();
return my_flask_var;
}
}
// the rest of your program, using any part of the flask_data dictionary however you need
// .
// .
// .