article

Thursday, April 13, 2023

Python Flask and React

Python Flask and React

https://flask.palletsprojects.com/en/2.2.x/installation/
 
Create an environment
C:\flask_dev>py -3 -m venv venv

Activate the environment
C:\flask_dev>venv\Scripts\activate

Install Flask
venv C:\flask_dev>pip install Flask
C:\flask_dev\flaskreact\app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#C:\flask_dev\flaskreact\app.py
from flask import Flask
from flask_restful import Api, Resource, reqparse #ModuleNotFoundError: No module named 'flask_restful' = pip install flask-restful
from flask_cors import CORS #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
from api.ApiHandler import ApiHandler
 
app = Flask(__name__)
 
CORS(app)
api = Api(app)
 
api.add_resource(ApiHandler, '/flask')
 
@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"
 
if __name__ == '__main__':
    app.run(debug=True)
C:\flask_dev\flaskreact\api\ApiHandler.py
1
2
3
4
5
6
7
8
9
#C:\flask_dev\flaskreact\api\ApiHandler.py
from flask_restful import Api, Resource
 
class ApiHandler(Resource):
  def get(self):
    return {
      'resultStatus': 'SUCCESS',
      'message': "Hello Api Handler ApiHandler.py"
      }
flask run (venv) C:\flask_dev\flaskreact>flask run:
React JS

Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start

C:\react-js\myreactdev\src\App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//C:\react-js\myreactdev\src\App.js
import './App.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios'
 
function App() {
  const [getMessage, setGetMessage] = useState({})
 
  useEffect(()=>{
    axios.get('http://localhost:5000/flask').then(response => {
      console.log("SUCCESS", response)
      setGetMessage(response)
    }).catch(error => {
      console.log(error)
    })
 
  }, [])
  return (
    <div className="App">
      <header className="App-header">
        <p><h1>Python Flask and React</h1></p>
        <div>{getMessage.status === 200 ?
          <h3>{getMessage.data.message}</h3>
          :
          <h3>LOADING</h3>}</div>
      </header>
    </div>
  );
}
 
export default App;
Run C:\react-j\myreactdev>npm start

Related Post