I have some code from python that displays a table using Flask and render template. I'd like to place this into my React App.js file how can I do this?
My CRUD from python
I'd like to place that into App.js.
Thanks in Advance.
You can create API in flask and call from react js with axios package.
Install axios with
npm install axios
Simple Example:
Suppose you API is localhost:8080/hello
and it returns "Hello world"
In app.js imports,
import axios from "axios";
and in return
return (
<div>
axios.get("localhost:8080/hello")
</div>
)
References:
https://www.npmjs.com/package/axios
Related
Hey guys I am doing a project that uses Python as a backend and React as a frontend. Everything works fine. After deploying to heroku I changed all my axios request URL to my domain name. But I realize if I change my domain name I have to change the axios URL in my react app everytime. I have used redux to do perform axios request for CRUDL and all types of authentication. I know this sounds stupid but is there a way to configure all the axios request to particular domain name by only giving path name every time it makes request? Thanks
setup axios defaults something like this:
axios.defaults.baseURL =
process.env.NODE_ENV === "production"
? process.env.REACT_APP_PROD_URL
: process.env.REACT_APP_DEV_URL;
then in your .env file
REACT_APP_PROD_URL="https://api.example.com"
REACT_APP_DEV_URL="http://localhost:8000"
i am new to backend dev. I try to developp a flask restful api. I followed the documentation and made the suggested minimal api, that is just returning a jsonified dict. With postman, curl and in the browser, no problem, the api is running and responds to my requests.
From my react native app however, i always get a Netwrok Error.
I tried lots of things:
- multiple IP addresses for the flask serveur
- differents ways to use axios
- different os : win10, ubuntu
- different endpoints : /, /api, /test
- different ways of writing the api (flask-restful class, flask app functions ...)
- manips from web documentations : dev mode of my device, chrome dev tools (port forwarding)
- i asked a react native developper to check my client-side code, nothing wrong according to him,
precisions :
- python code runs under a conda virtual env
- appli runs under node js and expo
- container folders of my app and my api are at the same level
- the flask server does not respond 404 or whatever, it does not respond at all, the error returned in react native is a network error
- depending on url, the network errors occurs immediately or after a 2 minutes delay
- flask shows requests and status when called by postman, curl, chrome, but does not react when i press my buttons from the react native app
Here is (one of) my python code:
from flask import (Flask, jsonify)
# from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/api", methods=["GET"])
def get():
return jsonify(hello='bouh !')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
and here is the clientside code:
import React, {Component} from 'react';
import { View, Button } from 'react-native';
import axios from 'axios';
import { sharedStyles } from '../../SHARED/_shared';
var url = "http://192.168.1.16:5000/api";
export default class PrevCommune extends Component {
constructor(props){
super(props);
this.navigation=this.props.navigation;
};
getAxios=()=>{
axios.get(`${url}`).then((response)=>{
console.log("succes axios :",response);
}).catch((error)=>{
console.log("fail axios :", error);
});
};
getFetch=()=>{
fetch(url).then((response)=>{
console.log("succes fetch :",response)
}).catch((error)=>{
console.log("fail fetch :",error)
})
}
render(){
return (
<View style={sharedStyles.mainContainer}>
<Button onPress={()=>this.getAxios()} title={"get axios"}></Button>
<Button onPress={()=>this.getFetch()} title={"get fetch"}></Button>
</View>
);
};
};
And the lines returned by requests:
fail axios : [Error: Network Error]
fail fetch : [TypeError: Network request failed]
I saw lots of tutos, videos, articles on flask api but i didn't find where i am wrong. Please tell me if you have any ideas ! I think both client and server codes are ok, the problem seems to be that my requests are blocked by something.
Solved : the probleme was my firewall ... thank you ricardo for the CORS doc =)
What worked for me was to change the IP address of localhost to my network IP in the api call in react native and then starting the flask application using the below command.
flask run --host=0.0.0.0
I'm trying my hand at building a simple CMS with React, Flask, and MongoDB. I am trying to find a way to get data from MongoDB through Flask to render the correct React components.
The data is stored in MongoDB as:
{
title: "home",
modules: {
headerBlock: {
title: "My Website"
byline: "Some other text here"
}
}
}
I can get that data into Python fairly easily, but then I need to get Flask to render the React components. It would translate to:
<Header title="My Website" byline="Some other text here" />
So there needs to be some way for Flask to provide a container and information about which components to render. (There will be more than one component).
Any help or tips or pushes in the right direction would be appreciated!
It depends, if you are trying to build a single page application SPA , with react in front end, you would need to pass data from your back-end (flask) to react as json data.
Flask has a function called jsonify that reponse to json.
I have an app Vue + Django. I try to send some data from vue to database using axios post method. Unfortunately console shows error:
GET http://localhost:8080/api/get_data/ 404 (Not Found)
And the same happend in python console:
Not Found: /get_data/
I have function get_data defined in my views and i added a path to urls:
path('get_data/', views.get_data)
In frontend it looks like this:
addNewData() {
axios.post("/api/get_data/", this.componentData.data).then(response => {
console.log("ok");
});
}
Did I missed something?
axios.post("/api/get_data/" - this URL is relative to "current". That's why it is trying ot access http://localhost:8080/... where 8080 is the port of VUE app. Whereas Django app is running by default on 8000.
You should use absolute URLs to access one app from another: to access Django app API from Vue app.
Use different config/env.var in your VUE app to refer to backend API in debug (localhost) and prod (domain name + http/https) modes, like:
axios.post(conf.BACKEND_URL + "/api/get_data/")
in your case, in debug mode it should be (expanded):
axios.post("http://localhost:8000/api/get_data/")
if you don't used webpack proxyTable deal with '/api' ,you should add the backend address
I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.