How to connect Flask REST API to HTML page - python

I have created an REST-API using flask so now , I don't know how to connect it with HTML page .
Hear is my app.py code of rest-api
from blocklist import blocklist
import re
from flask import Flask, jsonify
from flask_restful import Api
from flask_jwt_extended import JWTManager
import redis
from db import db
from jwt import PyJWKClient
from resources.user import UserRegister, User, UserLogin, TokenRefresh, UserLogout
from resources.item import Item, ItemList
from resources.store import Store, StoreList
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["JWT_BLACKLIST_ENABLED"] = True
app.secret_key = "jose"
api = Api(app)
#app.before_first_request
def create_tables():
db.create_all()
jwt = JWTManager(app) # not creating an auth
jwt_redis_blocklist = redis.StrictRedis(
host="localhost", port=5000, decode_responses=True
)
#jwt.expired_token_loader
def check_if_token_is_revoked(jwt_header, jwt_payload):
jti = jwt_payload["jti"]
token_in_redis = jwt_redis_blocklist.get(jti)
return token_in_redis is not None
#jwt.token_in_blocklist_loader
def check_if_token_in_blacklist(jwt_header, jwt_payload):
return jwt_payload["jti"] in blocklist
api.add_resource(Store, "/store/<string:name>")
api.add_resource(StoreList, "/stores")
api.add_resource(Item, "/item/<string:name>")
api.add_resource(ItemList, "/items")
api.add_resource(UserRegister, "/register")
api.add_resource(User, "/user/<int:user_id>")
api.add_resource(UserLogin, "/login")
api.add_resource(UserLogout, "/logout")
api.add_resource(TokenRefresh, "/refresh")
if __name__ == "__main__":
db.init_app(app)
app.run(port=5000, debug=True)
I have no idea how do I fetch data from API and show it to HTML page

#app.route("/")
def page_home():
# YOUR CODE HERE
return flask.render_template('home.html')
like above you can render the html file

Related

TypeError: Blueprint.__init__() got an unexpected keyword argument 'template_folder'

This is what my directory looks like
p/
student/
template/
student/
index.html/
views.py/
__init__.py/
app.py/
this is what my app.py file looks like
from flask import Flask, render_template
from p import app
#app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run()
__init__.py file
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] =
"postgresql://postgres:1234#localhost/studentRegDB"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app, db)
from p.student.views import student_blueprints
app.register_blueprint(student_blueprints, url_prefix='/student')
views.py file
from flask import Flask, request
import psycopg2
from p import db
from p.student.forms import studentform
from p.student.models import Student
from flask import Flask, render_template, url_for,redirect
from flask_blueprint import Blueprint
student_blueprints = Blueprint('student', __name__, template_folder='student')
#student_blueprints.route("/add", methods=["GET", "POST"])
def addstudent():
form = studentform()
if form.validate_on_submit():
name = request.form['name']
course = request.form['course']
new_student = Student(name,course)
db.session.add(new_student)
db.session.commit()
return redirect(url_for("success.html"))
return render_template("student.html", form=form)
when run the code i get the following error
student_blueprints = Blueprint('student', name, template_folder='student')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blueprint.init() got an unexpected keyword argument 'template_folder'
thank you for your help
You have to be very careful with names. The package flask_blueprint is unrelated to the flask blueprints you get from from flask import Blueprint, and has completely different parameters.
I suggest you pip uninstall flask-blueprint, and change your code to
from flask import Blueprint

Integrate Dash into Flask

I am trying to integrate a Dash app into an existing Flask program with Flask-Login. If I add server=server to the Dash instance every route (even ones that don't exist!!!), except the specified routes in run (ie. /home, /login), take me to the Dash app.
Example:
localhost:500/ - Takes me to Dash app
localhost:5000/home - Takes me to home route
localhost:5000/da - Takes me to Dash App
If I remove the server=server from the Dash instance, all the path's work as I would like, but when I pull up the dashboard at localhost:5000/test I get the error 'Error Loading Layout'.
If I add a url_base_pathname='/base/' to the dash instance, the routes work, but the dashboard bypasses my login.
Code Files:
server.py:
from flask import Flask
server = Flask(__name__,instance_relative_config=False)
server.config['SECRET_KEY'] = 'secretkey'
run.py:
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
from server import server
from dashboard import app as app_1
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
server.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db'
db = SQLAlchemy(server)
login_manager = LoginManager()
login_manager.init_app(server)
class User(UserMixin,db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(30), unique=True)
password = db.Column(db.String(30))
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#server.route('/login')
def login():
return render_template('login.html')
#server.route('/homepage', methods=['POST'])
def homepage():
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username,password=password).first()
if not user:
return 'User not Found'
else:
login_user(user)
return render_template('homepage.html')
#server.route('/logout')
def logout():
logout_user()
return index()
#server.route('/')
#server.route('/home')
def index():
return render_template('index.html')
#server.route('/test')
#login_required
def dashboard():
return redirect('/dash1')
app = DispatcherMiddleware(server, {
'/dash1': app_1.server})
if __name__ == '__main__':
run_simple('0.0.0.0', 5000, app, use_reloader=True, use_debugger=True)
dashboard.py
import dash
import dash_html_components as html
from server import server
app = dash.Dash(__name__)
app.layout = html.Div('Dashboard Page')
I would appreciate any insight on this. I've been scouring the internet for the past 2 days and can't solve this. Ultimately, the best solution would be if I can figure out why there is a layout error when server=server is removed because the entire app functions other than that.
Thanks

How can I make a non-permanent session in Flask

I'm learning flask and am trying to associate some randomly generated data with each session.
I use the approach from this answer to set session.permanent to False, but closing the browser, then reopening it at going back to the page still displays the same code.
MWE:
from flask import Flask, session
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
#app.before_request
def make_session_permanent():
session.permanent = False
#app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
if __name__ == '__main__':
app.run(debug=True)
Update: Based on this answer someone recommended to use socketio to notice disconnects. This also makes no difference, i.e. closing the browser, reopening it, and going to 127.0.0.1:5000 gives the same number as before closing. An updated MWE using this is below:
from flask import Flask, session
from flask_socketio import SocketIO
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
#app.before_request
def make_session_permanent():
session.permanent = False
#app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
socketio = SocketIO(app)
#socketio.on('disconnect')
def disconnect_user():
session.pop('id', None)
if __name__ == '__main__':
app.run(debug=True)
# Instantiate a new web application called `app`,
# with `__name__` representing the current file
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False

Why do I get a NameError when importing external DB models into my Flask App?

I'm trying to split out my models into a separate file as it's getting too large to manage. I've followed this but I am getting a NameError despite having run db.create_all():
NameError: name 'importsTable' is not defined
# stack_app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from stack_dbmodels import db
from stack_dbmodels import importsTable
from datetime import datetime
app = Flask(__name__)
app.secret_key = 'secretsquirrel'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stack_newAppCsv.db'
db.init_app(app)
#app.route('/', methods=['GET'])
def stack():
username = "username"
new_user = importsTable(username)
db.session.add(new_user)
db.session.commit()
return "Done!"
if __name__ == "__main__":
app.run(debug = True, port=8080)
My models file:
# stack_dbmodels.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class importsTable(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
def __init__(self, username):
self.username = username
def __repr__(self):
return '<Import {0}>'.format(self.username)
The problem was mainly with the context of the app but during my tests there were a couple of gotchas I found. Key to make the above work was:
When I reference importsTable it wasn't initially defined unless I did:
from stack_dbmodels import db
from stack_dbmodels import importsTable
And whilst the .db file was created, the context wasn't correct so it couldn't create the actual importsTable so I added the following and problem solved, the key bit was "with app.app_context()":
db.init_app(app)
with app.app_context():
db.create_all()
Final working code was:
# stack_app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from stack_dbmodels import db
from stack_dbmodels import importsTable
from datetime import datetime
app = Flask(__name__)
app.secret_key = 'secretsquirrel'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stack_newAppCsv.db'
db.init_app(app)
with app.app_context():
db.create_all()
#app.route('/', methods=['GET'])
def stack():
username = "username"
new_user = importsTable(username)
db.session.add(new_user)
db.session.commit()
return "Done!"
if __name__ == "__main__":
app.run(debug = True, port=8080)

Register blueprint in Python Flask unittest doesn't work

I can confirm that my unittest and api was already working but after moving my stuff to a Blueprint, my unittest kept on failing while the api is still working. I'm stumped, looking for ideas.
Here are the codes in question:
# project/app/__init__.py
from flask_sqlalchemy import SQLAlchemy
from flask import request, jsonify, abort, Flask
from instance.config import app_config
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
from app.api import api
app.register_blueprint(api, url_prefix='/api')
return app
Blueprint File
# project/app/api/__init__.py
from flask import Blueprint
api = Blueprint('api', __name__)
from app.api import campaigns
Test File
# project/test_campaigns.py
import unittest
import json
from app import create_app, db
from flask import Flask, Blueprint
from instance.config import app_config
class CampaignsTestCase(unittest.TestCase):
"""Campaigns Test Case"""
def setUp(self):
"""Define test varibles and initialize app."""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
self.campaigns = {'name': 'Test Campaign'}
#binds the app to the current context
with self.app.app_context():
# create all tables
db.create_all()
def test_create_campaign(self):
"""Test API can create campaign (POST Request)"""
res = self.client().post('/api/campaigns/', data=self.campaigns)
self.assertEqual(res.status_code, 201)
self.assertIn('Test', str(res.data))
### REST OF TEST ####
API Route File. This is where I used the '/campaigns' route which will be prefixed by '/api'.
# project/app/api/campaigns.py
from app.api import api
from flask_sqlalchemy import SQLAlchemy
from flask import request, jsonify, abort, Flask
import os
#api.route('/campaigns/', methods=['POST'])
def create_campaign():
if request.method == 'POST':
name = request.form['name']
if name:
campaign = Campaign(name=name)
campaign.save()
response = jsonify({
'id': campaign.id,
'name': campaign.name,
'date_created': campaign.date_created
})
response.status_code = 201
return response
All of my test results into a 404
======================================================================
FAIL: test_create_campaign (__main__.CampaignsTestCase)
Test API can create campaign (POST Request)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_campaigns.py", line 25, in test_create_campaign
self.assertEqual(res.status_code, 201)
AssertionError: 404 != 201

Categories

Resources