article

Thursday, April 27, 2023

ReactJs Python Flask Dynamic Select Country State City | Axios Mysql

ReactJs Python Flask Dynamic Select Country State City | Axios Mysql

Python Flask 

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

Install requirements

Flask-SQLAlchemy
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application.
https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/

(venv) PS C:\flask_dev\flaskreact>pip install -U Flask-SQLAlchemy

Flask + marshmallow for beautiful APIs
https://pypi.org/project/flask-marshmallow/

(venv) PS C:\flask_dev\flaskreact>pip install flask-marshmallow

Flask-Cors
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
https://pypi.org/project/Flask-Cors/

(venv) PS C:\flask_dev\flaskreact>pip install -U flask-cors

C:\flask_dev\flaskreact\app.py

 
#C:\flask_dev\flaskreact\app.py
from flask import Flask, jsonify
from flask_cors import CORS #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
from flask_marshmallow import Marshmallow #ModuleNotFoundError: No module named 'flask_marshmallow' = pip install flask-marshmallow https://pypi.org/project/flask-marshmallow/
  
from models import db, Countries, State, City
  
app = Flask(__name__)
CORS(app, supports_credentials=True)
  
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flaskdb.db'
# Databse configuration mysql                             Username:password@hostname/databasename
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@localhost/flaskreact'
  
db.init_app(app)
    
with app.app_context():
    db.create_all()
  
ma=Marshmallow(app)
   
class CountriesSchema(ma.Schema):
    class Meta:
        fields = ('ID','countryName')

class StateSchema(ma.Schema):
    class Meta:
        fields = ('id','name','country_id')

class CitySchema(ma.Schema):
    class Meta:
        fields = ('id','name','stateid')

countries_schema = CountriesSchema(many=True)
state_schema = StateSchema(many=True)
city_schema = CitySchema(many=True)

@app.route("/")
def hello_world():
    return "Hello, World!"
  
@app.route('/listall',methods =['GET'])
def listall():
    all_countries = Countries.query.all()
    results = countries_schema.dump(all_countries)
    return jsonify(results)

@app.route('/state/<get_state>')
def statebycountry(get_state):
    state = State.query.filter_by(country_id=get_state).all()
    results = state_schema.dump(state)
    return jsonify(results)

@app.route('/city/<get_city>')
def city(get_city):
    city_data = City.query.filter_by(stateid=get_city).all()
    results = city_schema.dump(city_data)
    return jsonify(results)
C:\flask_dev\flaskreact\models.py
 
#C:\flask_dev\flaskreact\models.py
from flask_sqlalchemy import SQLAlchemy
     
db = SQLAlchemy()
     
class Countries(db.Model):
    __tablename__ = "countries"
    ID = db.Column(db.Integer, primary_key=True)
    countryName = db.Column(db.String(120), index=True, unique=True)

class State(db.Model):
    __tablename__ = "state"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True, unique=True)
    country_id = db.Column(db.Integer)

class City(db.Model):
    __tablename__ = "city"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True, unique=True)
    stateid = db.Column(db.Integer)
run (venv) C:\flask_dev\flaskreact>flask run
http://127.0.0.1:5000/users/1/4

Country State and City : https://github.com/cairocodes/cairocoders/blob/main/country-state-city.sql

React JS
https://create-react-app.dev/

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

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

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios
C:\react-js\myreactdev\src\App.js
//C:\react-js\myreactdev\src\App.js
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";

function App() {
  
  const [country, setCountry]= useState([]);
  const [countryid, setCountryid]= useState('0');
  const [stateid, setStateid]= useState('0');
  const [state, setState]= useState([]);
  const [city, setCity]= useState([]);

 
  useEffect(() => {
	  
    const fetchCountry = async () => {
        axios.get('http://127.0.0.1:5000/listall')
        .then(function (response) {
            //handle success
            //console.log(response)
            setCountry(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
  
    fetchCountry()
  }, [])
 
  const handlecountry=(event)=>{
    const getcoutryid= event.target.value;
	alert(getcoutryid);
    setCountryid(getcoutryid);
    event.preventDefault();
  }  
  
  const handlestate=(event)=>{
    const stateid= event.target.value;
	alert(stateid);
    setStateid(stateid);
    event.preventDefault();
  }
 
  useEffect( ()=>{
 
    const getstate= async ()=>{	
        axios.get(`http://127.0.0.1:5000/state/${countryid }`)
        .then(function (response) {
            //handle success
            //console.log(response)
            setState(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
    getstate();
 
  },[countryid]);
 
  useEffect( ()=>{
 
    const getcity= async ()=>{
        axios.get(`http://127.0.0.1:5000/city/${stateid }`)
        .then(function (response) {
            //handle success
            //console.log(response)
            setCity(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
    getcity();
 
  },[stateid]);
	
  return (
    <div className="container">
     <div className="row">
       <div className="col-sm-12">
         <h5 className="mt-4 mb-4 fw-bold">ReactJs Python Flask Dynamic Select Country State City | Axios Mysql</h5>

             <div className="row mb-3">
                 <div className="form-group col-md-12">
                 <label className="mb-2">Country</label>
                 <select name="country" className="form-select" onChange={(e)=>handlecountry(e)}>
                   <option>--Select Country--</option>
                   {
                     country.map( (getcon)=>(
                   <option key={getcon.ID} value={getcon.ID }> { getcon.countryName}</option>
                     ))
                }
                  
                 </select>
               </div>
               <div className="form-group col-md-12">
               <label className="mb-2">State</label>
               <select name="state" className="form-select" onChange={(e)=>handlestate(e)}>
                   <option>--Select State--</option>
                   {
                     state.map( (st,index)=>(                    
                   <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
               </div>
 
               <div className="form-group col-md-12">
               <label className="mb-2">City</label>
               <select name="city" className="form-select">
                   <option>--Select City--</option>                  
                   {
                     city.map( (st,index)=>(                    
                   <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
               </div>
			   
               <div className="form-group col-md-12 mt-12">              
               <button type="submit" className="btn btn-success mt-2" >Submit</button>               
               </div>
            </div>
            
       </div>
     </div>
    </div>
  );
}
export default App;
react-js\myreactdev\public\index.html
//react-js\myreactdev\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

Related Post