I'm building a very simple React frontend and want to build my backend server in Python.
After reading what Flask is in 4 different places I'm still a bit confused. It's generally described as "a web application framework written in Python."
Is a web application framework designed to return the content that appears on a web page, whereas that would normally live in React (or whatever other FE framework)?
If I only want to spin up a reliable web server with some basic endpoints to be hit by my React web application, is Flask the right tool for me? Or should I go with something else?
Videos
You're creating a new application in your test module - meaning that you have no registered endpoints.
You'll need to import the app created in your server module.
from your_package.server import app
and use that as you're currently doing.
Ideally your server.py and your app.py are separate - meaning you have app.py with your app configuration and server.py imports the app required, and tests import the app required, so on and so forth.
Example:
application.py
import sys
import json
from flask import Flask, request, render_template
app = Flask(__name__)
from mf import gameplay
game = gameplay.Game()
@app.route('/')
def index():
return render_template('mainmap.html')
@app.route('/api', methods=['POST'])
def api():
data_json = request.data.decode()
data = json.loads(data_json)
return game(data_json)
server.py
from application import app
app.run('0.0.0.0', 5000, threaded=True)
test.py
from application import app
def test_1():
"""Example test"""
with app.test_client() as client:
response = client.get('/')
print(response)
That should work!
Firstly ensure your Flask application is running and simply you can use tools like postman or cUrl to test your endpoint.
If you are using same machine, you do not need to use flask-cors.
Update:
As you are using Docker you can use flask-cors to handle CORS.
I found that the AJAX calls were not correct in your JS code. const url = "localhost:5000/test"; does not provide information on request protocol.
I followed these steps to run Flask application successfully using Docker and accessing the /test endpoint using JS outside Docker.
- I updated AJAX request
- Added
Dockerfileto run Flask application inside Docker - Build and run the
Dockerfile - Get the IP address of running Docker container.
- Used the IP address in AJAX call in JS code which is outside Docker.
Folder structure:
.
├── backend.py
├── Dockerfile
├── readme.md
└── requirements.txt
requirements.txt:
Flask==1.0.2
Flask-Cors==3.0.7
Dockerfile:
FROM python:3
ENV PYTHONBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
CMD ["python", "backend.py" ]
Build Docker file:
docker build -t flask-docker .
Run Docker:
docker run -p 5000:5000 flask-docker
* Serving Flask app "backend" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Get Docker container ID:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
69cb7d5d243a flask-docker "python backend.py" 15 minutes ago Up 15 minutes 0.0.0.0:5000->5000/tcp
Get Docker container IP address:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' 69cb7d5d243a
172.17.0.2
Use this IP address in AJAX request in HTML file:
<html>
<head>
<title>Frontend</title>
</head>
<body>
<div id="data"></div>
<button type="button" id="btn">Grab data</button>
<script type="text/javascript">
document.getElementById("btn").addEventListener('click', add);
function add()
{
const api_url = "http://172.17.0.2:5000/test";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").append(this.responseText);
}
};
xhttp.open("GET", api_url, true);
xhttp.send();
}
</script>
</body>
</html>
backend.py:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/test")
def test():
return "It's working"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
Output:

Add the following line below app = Flask(__name__):
CORS(app)
Check out flask-cors simple usage
