How to use flask_jwt_extended with blueprints? - python

I'm trying to build a blog as a portfolio sample using python3 and flask and flask_jwt_extended.
I can create a single file like this and it will run:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
#app.route(....)
#jwt required
But when I try to use Blueprint, it will not register the JWTManager
Here is my user.py file:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt required
here is my app.py:
from user import *
app = Flask(__name__)
app.register_blueprint(user_blueprint)
Now when I try to run app.py, this it returns a 500 (Internal Error) and will log this to the log file:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 127, in _get_jwt_manager
return current_app.extensions['flask-jwt-extended']
KeyError: 'flask-jwt-extended'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ali/Desktop/cetia_api/user.py", line 63, in login
return create_token(user_inputs)
File "/home/ali/Desktop/cetia_api/user_functions.py", line 103, in create_token
access_token = create_access_token(identity=data, expires_delta=expires)
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 156, in create_access_token
jwt_manager = _get_jwt_manager()
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 129, in _get_jwt_manager
raise RuntimeError("You must initialize a JWTManager with this flask "
RuntimeError: You must initialize a JWTManager with this flask application before using this method
Could someone please tell me what to do? I tried EVERYTHING for the last 3 days. its been 20 hours of debugging and it's still not fixed

You need to use the same app in every location. Currently you are creating an app in your users.py file, and a different app in you app.py file.
Generally you will want to use the flask application factory pattern to do this (https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/). An example might look something like this:
extensions.py
from flask_jwt_extended import JWTManager
jwt = JWTManager()
users.py
from flask_jwt_extended import (create_access_token, get_jwt_identity, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt_required
app.py
from extensions import jwt
from users import users_blueprint
def create_app():
app = Flask(__name__)
app.secret_key = 'ChangeMe!'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt.init_app(app)
app.register_blueprint(user_blueprint)
return app
main.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()

Related

Python Flask - Session Not Being Set with Waitress

I am using waitress on IIS with Flask.
I have a route that sets a session as follows
#gp_clinicals_bp.route("/setting", methods=["POST","GET"])
def gp_clinicals():
session["gp_clinicals_meds_repeat"] = "123456"
return session["gp_clinicals_meds_repeat"]
This returns, unsurprisingly:
123456
I have another route as follows:
#gp_clinicals_bp.route("/testing", methods=["POST","GET"])
def gp_clinicals_test():
return session["gp_clinicals_meds_repeat"]
Now, I get nothing back and the following in the error log
2022-08-02 20:03:51,126 - ERROR - app.py - log_exception - 1455 - Exception on /gp-clinicals/medication-repeat [GET]
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python310\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python310\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "E:\Apps\dev\digital\gp_clinicals\gp_clinicals.py", line 158, in gp_clinicals_medication_repeat
return str(session["gp_clinicals_meds_repeat"])
KeyError: 'gp_clinicals_meds_repeat'
2022-08-02 20:03:51,128 - ERROR - __init__.py - handle_error_500 - 92 - 500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I'm the only one on the server. Below is a snippet from my initilisation file:
"""Initialize Flask app."""
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template, flash,request
from flask_session import Session
from flask_assets import Environment
from config import Config
if Config.FLASK_ENV == "development" and Config.DD_SERVICE:
patch_all()
sess = Session()
def init_app():
"""Create Flask application."""
app = Flask(__name__, instance_relative_config=False)
app.config["CACHE_TYPE"] = "null"
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config["SESSION_TYPE"] = "filesystem"
app.config.from_object("config.Config")
assets = Environment()
assets.init_app(app)
sess.init_app(app)
What's going wrong? In the flask_session folder I am seeing files being created
Any advice? I tried using single apostophes instead of quotes but no go there either
The site in IIS is running through a reverse proxy in IIS - could that be doing it?

Flask app NameError: name 'Markup' is not defined

I have been really stumped on this, been out of this game of web dev/python for a bit. I had a previously working Azure app service running this website, we did a minor HTML spelling change and re deployed. I am assuming some dependency got updated and now its broken. I don't know if this is a packaging version issue or if I have a missing import for my flask app.
I am getting a NameError: name 'Markup' is not defined error when trying to load a static html page. My app starts up just fine but I can't load the actual web pages.
Full Traceback
Traceback (most recent call last):
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\St**\PycharmProjects\**Site-portfolio\application.py", line 32, in index
return render_template("//index.html")
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\templating.py", line 147, in render_template
ctx.app.update_template_context(context)
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask\app.py", line 756, in update_template_context
context.update(func())
File "C:\Users\St**\PythonProjects\**Site-Portfolio\lib\site-packages\flask_recaptcha.py", line 59, in get_code
return dict(recaptcha=Markup(self.get_code()))
NameError: name 'Markup' is not defined
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [08/Apr/2022 17:02:51] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
Process finished with exit code 0
Here is my code:
from flask import Flask, request, render_template, flash
from flask_mail import Mail, Message
from flask_cors import CORS, cross_origin
from flask_recaptcha import ReCaptcha
import requests
import json
import os
app = Flask(__name__, static_folder='static', static_url_path='')
recaptcha = ReCaptcha(app=app)
app.config['RECAPTCHA_ENABLED'] = True
app.config['RECAPTCHA_PUBLIC_KEY'] = '***********************'
app.config['RECAPTCHA_PRIVATE_KEY'] = '****************************'
#app.route('/', methods=['GET'])
def index():
return render_template("//index.html")
#app.route('/contact-us', methods=['GET'])
#app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
r = requests.post('https://www.google.com/recaptcha/api/siteverify',
data={'secret': '***********',
'response': request.form['g-recaptcha-response']})
google_response = json.loads(r.text)
if google_response['success']:
contact_form = {'name': request.form['name'],
'email': request.form['email'],
'message': request.form['message']}
msg = Message(subject='Contact from website',
sender=contact_form['email'],
recipients=['*************'],
body=contact_form['message'])
mail.send(msg)
flash('Success, we will respond within at least 24 hours.')
return render_template('contact.html')
else:
flash('failed to submit, please retry or contact us at ************')
return render_template('contact.html')
return render_template('contact.html')
if __name__ == '__main__':
app.run()
My requirements.txt for package version
Flask>=1.0.2
jinja2>=2.11.3
Flask-Mail>=0.9.1
Flask-Cors>=3.0.9
Flask-Admin>=1.5.2
Flask-ReCaptcha>=0.4.2
Flask-SQLAlchemy>=2.3.2
Flask-WTF>=0.14.2
SQLAlchemy>=1.3.0
requests>=2.20.0
Flask-Login>=0.4.1
Werkzeug>=0.15.3
Flask-ReCaptcha is a very old project. The last update of Flask-ReCaptcha is on 2016. You'd better not use it.
Back to the error log itself, Flask-ReCaptcha has code like from jinja2 import Markup. But, since jinja2==3.1.0, Markup's position has changed. Try pip install jinja2==3.0.0`.
You will probably meet other problems as Flask-ReCaptcha is really old.
Go to Python installation folder
Go to Lib > site-packages
Open flask_recaptcha.py
You'll see something like this:
try:
from flask import request
from jinja2 import Markup
import requests
except ImportError as ex:
print("Missing dependencies")
Change it to:
try:
from flask import request
from markupsafe import Markup
import requests
except ImportError as ex:
print("Missing dependencies")

How to use Flask Login with Blueprints

I'm trying to use LoginManager for my flask application. When I run the application and open the index page, it says the following
File "...\python38-32\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "...\python38-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "...\python38-32\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "...\python38-32\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "...\python38-32\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "...\python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...\root\project\user_auth\routes.py", line 18, in index
return render_template('index.html', title='Welcome')
File "...\python38-32\lib\site-packages\flask\templating.py", line 137, in render_template
return _render(
File "...\python38-32\lib\site-packages\flask\templating.py", line 120, in _render
rv = template.render(context)
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 1090, in render
self.environment.handle_exception()
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "...\python38-32\lib\site-packages\jinja2\_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "...\root\project\user_auth\templates\index.html", line 1, in top-level template code
{% extends "base.html" %}
File "...\root\project\user_auth\templates\base.html", line 13, in top-level template code
{% if current_user.is_anonymous %}
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 471, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'current_user' is undefined
Here is my structure
root /
config.py
|project/
| __init__.py
| user_auth/
| __init__.py
| app.py
| routes.py
In the app/init.py file, it is the following
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
from .user_auth.routes import user_auth_bp
app.register_blueprint(user_auth_bp, url_prefix="")
From the user_auth init.py file is
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask import current_app
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = '.login'
app.config['SECRET_KEY'] = 'trial'
from ..user_auth import routes, models
This is the user_auth/routes.py file
from ..user_auth import app, db
from flask_login import login_required
from ..user_auth.forms import RegistrationForm, LoginForm
from flask import request, render_template, flash, redirect, url_for, Blueprint
from werkzeug.urls import url_parse
from flask_login import logout_user
from flask_login import current_user, login_user
from ..user_auth.models import User
from flask import Blueprint
user_auth_bp = Blueprint('user_auth', __name__, template_folder='templates')
#user_auth_bp.route('/')
#user_auth_bp.route('/index')
def index():
return render_template('index.html', title='Welcome')
#user_auth_bp.route('/register', methods=["POST", "GET"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
print("validated")
# Create User Model
username = form.username.data
password = form.password.data
email = form.email.data
newUser = User(username=username,email=email)
newUser.set_password(password)
db.session.add(newUser)
db.session.commit()
return redirect(url_for('.index'))
else:
return render_template('register.html', title='Welcome', form=form)
... (Other paths)
I am running Windows and used the following command
set FLASK_APP=project
I then use
flask run
Thank you in advance for the help.
You can try to search same problem
UndefinedError: 'current_user' is undefined
Check the init file:
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
#login_manager.user_loader
def load_user(user_id):
user = User.query.filter_by(id=user_id).first()
And strure, i think you should do like that

gunicorn when started using supervisor throws database error, works properly when manually started?

I have a simple flash website created and deployed in a server with Nginx as frontend and gunicorn as backend to run the python code. With this setup everything is working fine. However, if i run the server using supervisor module, I'm getting below error. I have ensured all the environment variables are accessible, they are placed in .bashrc under home directory.
Not sure what am missing. My python code is deployed in server inside a pipenv virtual environment. supervisor was started within the virtualenv only. Not sure if it has any relevance.
error log with supervisor
[2020-11-10 05:45:29,604] ERROR in app: Exception on /home [GET]
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/_collections.py",
line 1020, in call
return self.registry[key] KeyError: 139749229659968
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 2447, in wsgi_app
response = self.full_dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1952, in full_dispatch_request
rv = self.handle_user_exception(e) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/_compat.py",
line 39, in reraise
raise value File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1950, in full_dispatch_request
rv = self.dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1936, in dispatch_request
return self.view_functionsrule.endpoint File "/home/anandraj/FlaskProject/Proj2/main/routes.py", line 12, in home
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page,
per_page=7) File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 514, in get
return type.query_class(mapper, session=self.sa.session()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py",
line 78, in call
return self.registry() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/collections.py",
line 1022, in call
return self.registry.setdefault(key, self.createfunc()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/session.py",
line 3300, in call
return self.class(**local_kw) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 138, in init
bind = options.pop('bind', None) or db.engine File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 943, in engine
return self.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 962, in get_engine
return connector.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 555, in get_engine
options = self.get_options(sa_url, echo) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 883, in apply_driver_hacks
if sa_url.drivername.startswith('mysql'): AttributeError: 'NoneType' object has no attribute 'drivername'
Supervisor config
cat /etc/supervisor/conf.d/supervisord.conf
[program:Proj2]
directory=/home/<user>/FlaskProject
command=/home/<user>/.local/share/virtualenvs/FlaskProject->tLcktdEC/bin/gunicorn -w 3 run:app
user=<user>
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stderr_logfile=/var/log/flaskblog/Proj2Flask.err.log
stdout_logfile=/var/log/flaskblog/Proj2Flask.out.log
Error while querying DB
~/FlaskProject/Proj2/main$ cat routes.py
from flask import render_template, request, Blueprint
from Proj2.models import Post
main = Blueprint('main', __name__)
#main.route("/")
#main.route("/home")
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=7)
return render_template('home.html', posts=posts)
#main.route("/about")
def about():
return render_template('about.html', title='Anandraj')
How my app is initialized?
~/FlaskProject/Proj2$ cat __init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from Proj2.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_mgr = LoginManager()
login_mgr.login_view = 'users.login'
login_mgr.login_message_category = 'info'
mail = Mail()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_mgr.init_app(app)
mail.init_app(app)
from Proj2.users.routes import users
from Proj2.posts.routes import posts
from Proj2.main.routes import main
from Proj2.errors.handler import errors
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
app.register_blueprint(errors)
return app(FlaskProject)
Can you post your supervisor config file? My guess here is that it's related to your PATH definition...
EDIT (12/Nov): After seeing you're supervisor config file I noticed that you haven't set the environment path.
A list of key/value pairs in the form KEY="val",KEY2="val2" that will be placed in the supervisord process’ environment (and as a result in all of its child process’ environments)
from: https://docs.red-dove.com/supervisor/configuration.html
Can you try adding this to your configuration file? This will define your PATH as "/usr/bin/" for the environment that runs your gunicorn. If that doesn't work, please try use the path from where your virtualenv is running.
environment=PATH="/usr/bin"

AttributeError when using pandas and Google App Engine

I understand that Pandas isn't included and believe that I've properly included the library via adding the module into the lib directory for the app and by adding
from google.appengine.ext import vendor
vendor.add('lib')
to appengine_config.py - other modules don't seem to be having issues.
When I run my app, the following stack trace shows up:
ERROR 2016-12-15 23:05:31,038 app.py:1587] Exception on / [GET]
Traceback (most recent call last): File
".../PycharmProjects/fpl-flask-app/lib/flask/app.py", line 1988, in
wsgi_app  response = self.full_dispatch_request() File
".../PycharmProjects/fpl-flask-app/lib/flask/app.py", line 1641, in
full_dispatch_request
  rv = self.handle_user_exception(e) File ".../PycharmProjects/fpl-flask-app/lib/flask/app.py", line 1544, in
handle_user_exception
  reraise(exc_type, exc_value, tb) File ".../PycharmProjects/fpl-flask-app/lib/flask/app.py", line 1639, in
full_dispatch_request
  rv = self.dispatch_request() File ".../PycharmProjects/fpl-flask-app/lib/flask/app.py", line 1625, in
dispatch_request
  return self.view_functionsrule.endpoint File ".../PycharmProjects/fpl-flask-app/main.py", line 13, in index
  datar = pandas.read_sql('SELECT p.nationality, SUM(s.mins_played) AS mins_played   FROM CurrentSeasonStats s left join Player p ON
s.Player_pid = p.pid GROUP BY   p.nationality', con)
AttributeError: 'module' object has no attribute 'read_sql'**
Here's my code:
from flask import Flask, request, render_template
import pandas
from sqlalchemy import create_engine
import pymysql
import random
app = Flask(__name__)
#app.route('/')
def index():
con = create_engine('mysql+pymysql://user:pass#ix.cs.uoregon.edu:port/fpl', echo=False)
datar = pandas.read_sql('SELECT p.nationality, SUM(s.mins_played) AS mins_played FROM CurrentSeasonStats s left join Player p ON s.Player_pid = p.pid GROUP BY p.nationality', con)
return render_template('index.html', table=datar)
if __name__ == '__main__':
app.run()
Any ideas?
I had copy-pasted a Binary Skeleton version of the pandas library into /lib/ which is why none of the pandas functions were working.
This a direct and annoying result of me not using virtual environments...
USE VIRTUAL ENVIRONMENTS, KIDS!

Categories