article

Wednesday, April 3, 2024

Next.Js Python Flask

Next.Js Python Flask

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/

app.py
//app.py
from flask import Flask, jsonify
from flask_cors import CORS #pip install -U flask-cors https://pypi.org/project/Flask-Cors/

# app instance
app = Flask(__name__)
CORS(app)

@app.route("/")
def hello():
    return "Hello, World!"

# /api/user
@app.route("/api/user", methods=['GET'])
def return_home():
    return jsonify({
        'name': ['cairocoders', 'clydey', 'caitlyn'],
        'email': ['cairocoders@gmail.com', 'clydey@gmail.com', 'caitlyn@gmail.com']
    })


if __name__ == "__main__":
    app.run(debug=True, port=8080)
Install Nextjs 14
https://nextjs.org/docs/getting-started/installation
app\page.tsx
//app\page.tsx
"use client";
  
import React, { useEffect, useState } from "react";

export default function Home() {
  const [message, setMessage] = useState("Loading");
  const [userData, setUSerData] = useState([]);
            
    fetch("http://127.0.0.1:5000/api/user")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setMessage(data.message);
        setUSerData(data.name)
      });
  }, []);

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h3>Next js Python Flask</h3>
      <div>{message}</div>
      {userData.map((user, index) => (
        <div key={index}>{user}</div>
      ))}
    </main>
  );
}
app\page.tsx axios
"use client";
  
import React, { useEffect, useState } from "react";
import axios from 'axios' //npm install axios https://www.npmjs.com/package/axios

export default function Home() {
    const [userData, setUSerData] = useState([]);
    useEffect(() => {
        fetchData();
    }, [])
 
    const fetchData = async () => {
        try {
            const result = await axios("http://127.0.0.1:5000/api/user");
            console.log(result.data);
            setUSerData(result.data.name)
        } catch (err) {
            console.log("somthing Wrong");
        }
    }

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h3>Next js Python Flask</h3>
      {userData.map((user, index) => (
        <div key={index}>{user}</div>
      ))}
    </main>
  );
}

Related Post