27
loading...
This website collects cookies to deliver better user experience
# Import the required packages
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_marshmallow import Marshmallow
from flask_cors import CORS
...
db = SQLAlchemy()
migrate = Migrate()
ma = Marshmallow()
cors = CORS()
...
...
def create_app():
"""Application-factory pattern"""
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize extensions
# To use the application instances above, instantiate with an application:
db.init_app(app)
migrate.init_app(app, db)
ma.init_app(app)
cors.init_app(app)
return app
...
def deploy():
"""Run deployment tasks."""
from app import create_app,db
from flask_migrate import upgrade,migrate,init,stamp
from models import Articles
app = create_app()
app.app_context().push()
# create database and tables
db.create_all()
# migrate database to latest revision
stamp()
migrate()
upgrade()
deploy()
...
class Articles(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100),nullable=False)
body = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime(), default=datetime.utcnow)
def __repr__(self):
return "<Articles %r>" % self.title
# Generate marshmallow Schemas from your models
class ArticlesShema(ma.Schema):
class Meta:
# Fields to expose
fields = ("id","title", "body", "date")
article_schema = ArticlesShema()
articles_schema = ArticlesShema(many=True)
article_schema
and articles_schema
are utilized. The first serializes a single article, while the second serializes a queryset....
# Create an application instance
app = create_app()
# Define a route to fetch the available articles
@app.route("/articles", methods=["GET"], strict_slashes=False)
def articles():
articles = Articles.query.all()
results = articles_schema.dump(articles)
return jsonify(results)
if __name__ == "__main__":
app.run(debug=True)
...
const [articles, setArticles] = useState([]);
...
useEffect(()=>{
fetch('http://localhost:5000/articles',{
'methods':'GET',
headers : {
'Content-Type':'application/json'
}
})
.then(response => response.json())
.then(response => setArticles(response))
.catch(error => console.log(error))
},[])
useEffect
hook allows us to do a DOM update after the render. In this case, we're instructing React to update the DOM with a json response from our flask api after the render.useState
hook, which is now set to an empty list, will be updated with fresh data from our backend; it returns a pair of values: the current state and a function that updates it.ArticleList
component out of a list of articles.This component receives props that we will pass in the next phase.const ArticleList = (props) => {
return (
<div className="mt-2">
{/* Display the article details if article is not None */}
{props.articles && props.articles.map(article =>{
return (
<div key= {article.id}>
<h2 className="text-primary"> { article.title} </h2>
<p> { article.body } </p>
<p> { article.date } </p>
<hr/>
</div>
)
})}
</div>
)
}
export default ArticleList;
import ArticleList from './Components/ArticleList'
ArticleList
component to the DOM after making it available, as well as the articles
- the current state effect from the useState
, which is then consumed as props.return (
<div className="App container m-4">
<div className="row">
<div className="text-center">
<h1>Connecting a React Frontend to a Flask Backend.</h1>
</div>
</div>
<ArticleList
articles={articles}
/>
</div>
);