article

Thursday, April 18, 2024

Next.js 14 Python Flask Dynamic Select Country State City Mysql | TailwindCSS DaisyUI

Next.js 14 Python Flask Dynamic Select Country State City Mysql | TailwindCSS DaisyUI

https://python-guide-es.readthedocs.io/es/guide-es/dev/virtualenvs.html

Create an environment
ednalan@Cairocoders myapp % pip install virtualenv
ednalan@Cairocoders myapp % pip install virtualenv

Activate the environment
ednalan@Cairocoders myapp % source venv/bin/activate
(venv) ednalan@Cairocoders myapp %

Install Flask
https://pypi.org/project/Flask/
(venv) ednalan@Cairocoders myapp % pip install -U Flask
(venv) ednalan@Cairocoders myapp % flask run

Install requirements
pip install -U flask-cors
https://pypi.org/project/Flask-Cors/

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\myapp>pip install -U Flask-SQLAlchemy

python3 -m pip install
https://pypi.org/project/pymysql/
app.py
//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:root@localhost:8889/nextjsdb'
   
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>',methods =['GET'])
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>',methods =['GET'])
def city(get_city):
    city_data = City.query.filter_by(stateid=get_city).all()
    results = city_schema.dump(city_data)
    return jsonify(results)

if __name__ == "__main__":
    app.run(debug=True)
models.py
//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)
Country State and City : https://github.com/cairocodes/cairocoders/blob/main/country-state-city.sql

run (venv) C:\flask_dev\myapp>flask run

Next.js
Install requirements
npm install axios
https://www.npmjs.com/package/axios

app\page.tsx
//app\page.tsx
import Form from "@/components/form";

export default function Home() {
  return (
    <div className="w-screen py-20 flex justify-center flex-col items-center">
      <div className="flex items-center justify-between gap-1 mb-5">
        <h1 className="text-4xl font-bold">Next.js 14 Python Flask Dynamic Select Country State City Mysql | TailwindCSS DaisyUI</h1>
      </div>    
      <div className="overflow-x-auto">
          <Form/>
      </div>  
    </div>
  );
}
components\form.tsx
//components\form.tsx
"use client";
 
import React, { useEffect, useState } from "react";
import axios from 'axios' //npm install axios https://www.npmjs.com/package/axios

export default function Form() {

    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;
        console.log(getcoutryid);
        setCountryid(getcoutryid);
        event.preventDefault();
    }  
    
    const handlestate=(event)=>{
        const stateid= event.target.value;
        console.log(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="max-w-xl mx-auto mt-5">
            <div>
            <form>
            <div className="mb-5 pr-4 pl-4">
                <label className="block text-sm font-medium text-gray-900">
                    Country
                </label>
                <select onChange={(e)=>handlecountry(e)} name="country" className="select select-info w-full max-w-xs">
                    <option defaultValue={'DEFAULT'}>--Select Country--</option>
                    {
                     country.map( (getcon)=>(
                        <option key={getcon.ID} value={getcon.ID }> { getcon.countryName}</option>
                     ))
                    }
                </select>
            </div>
            <div className="mb-5 pr-4 pl-4">
                <label className="block text-sm font-medium text-gray-900">
                    State
                </label>
                <select onChange={(e)=>handlestate(e)} name="state" className="select select-success w-full max-w-xs">
                   <option defaultValue={'DEFAULT'}>--Select State--</option>
                   {
                     state.map( (st,index)=>(                    
                        <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
            </div>
            <div className="mb-5 pr-4 pl-4">
                <label className="block text-sm font-medium text-gray-900">
                    City
                </label>
                <select name="city" className="select select-warning w-full max-w-xs">
                   <option>--Select City--</option>                  
                    {
                     city.map( (st,index)=>(                    
                        <option key={index} value={st.id}>{ st.name}</option>
                     ))
                    }
                 </select>
            </div>
        </form>
        </div>
        </div>
        
        </>
  );
}
run C:\nextjs>npm run dev

Related Post