Related
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"
I am new to flask-alchemy. I want to filter a SQL query on the values of a LOC_CODE column. I made db.session.query(schools).filter_by(LOC_CODE='X270').first(). But the compiler returns:
(base) C:\Users\antoi\Documents\Programming\musicaltroupefinder>python hello_world.py
C:\ProgramData\Anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
* Serving Flask app "hello_world" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
the total number of school is 3281
[2019-12-18 11:08:31,831] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 210, in __getattr__
return self._data[key]
KeyError: 'LOC_CODE'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\base.py", line 399, in _entity_descriptor
return getattr(entity, key)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 212, in __getattr__
raise AttributeError(key)
AttributeError: LOC_CODE
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "hello_world.py", line 37, in index
school = db.session.query(schools).filter_by(LOC_CODE='X270').first()
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 1800, in filter_by
for key, value in kwargs.items()
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 1800, in <listcomp>
for key, value in kwargs.items()
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\base.py", line 402, in _entity_descriptor
"Entity '%s' has no property '%s'" % (description, key)
sqlalchemy.exc.InvalidRequestError: Entity 'schools' has no property 'LOC_CODE'
127.0.0.1 - - [18/Dec/2019 11:08:31] "[1m[35mGET / HTTP/1.1[0m" 500 -
However, I have this column in the database:
sqlite> SELECT * FROM SCHOOLS ORDER BY ROWID ASC LIMIT 1
...>
...> ;
0,,O,0,OAQK,"Victory Schools, DBA The Charter School of Excelle",Elementary,2,0,0,260 WARBURTON AVE,NY,10701,,,,"0K,01,02,03,04",YONKERS,260 WARBURTON AVE,1006,YONKERS,"-73.897156,40.94465",119,"260 WARBURTON AVE, YONKERS, NY, 10701",0,Exact,Match,40.94465,-73.897156,"260 WARBURTON AVE, YONKERS, NY, 10701",R,NY,36,139742928,402,10701
sqlite> PRAGMA table_info(schools);
0|,ATS_CODE,BORO,BORONUM,LOC_CODE,SCHOOLNAME,SCH_TYPE,MANAGED_BY,GEO_DISTRI,ADMIN_DIST,ADDRESS,STATE_CODE,ZIP,PRINCIPAL,PRIN_PH,FAX,GRADES,City,address2,block,city2,coordinates,county_fips,geocoded_address,id,is_exact,is_match,latitude,longitude,returned_address,side,state,state_fips,tiger_line,tract,zipcode|TEXT|0||0
Here's my entire code:
from flask import Flask # pip install flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import mapper, sessionmaker
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)
schools = db.Table("schools",db.metadata, autoload = True, autoload_with = db.engine)
#app.route("/")
def index():
results = db.session.query(schools).count()
print("the total number of school is ", db.session.query(schools).count())
school = db.session.query(schools).filter_by(LOC_CODE='X270').first()
print("School's name is", school.SCHOOLNAME)
return render_template("index.html")
#app.route("/map")
def shoelaces():
return "This works now!"
#app.route("/about")
def about():
return "All about my website"
if __name__ == "__main__":
app.run()
But I couldn't tell SQLAlchemy that we are lazy and that he should learn on his own about the database, we use this line:
I based it on this tutorial but I couldn't tell SQLAlchemy that he was lazy and that he should learn on his own about the database with a line db.Model.metadata.reflect(db.engine).
With classes
I also tried with a class:
(base) C:\Users\antoi\Documents\Programming\musicaltroupefinder>python hello_world.py
C:\ProgramData\Anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
* Serving Flask app "hello_world" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2019-12-20 13:03:58,460] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such column: schools.LOC_CODE
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "hello_world.py", line 32, in index
school = School.query.filter(School.LOC_CODE == 'X270').all()
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3186, in all
return list(self)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3342, in __iter__
return self._execute_and_instances(context)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 3367, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 988, in execute
return meth(self, multiparams, params)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
distilled_params,
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1253, in _execute_context
e, statement, parameters, cursor, context
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1473, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: schools.LOC_CODE
[SQL: SELECT schools."LOC_CODE" AS "schools_LOC_CODE"
FROM schools
WHERE schools."LOC_CODE" = ?]
[parameters: ('X270',)]
(Background on this error at: http://sqlalche.me/e/e3q8)
127.0.0.1 - - [20/Dec/2019 13:03:58] "[1m[35mGET / HTTP/1.1[0m" 500 -
Here is the code
from flask import Flask # pip install flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import mapper, sessionmaker
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)
class School(db.Model):
__tablename__ = 'schools'
# __table_args__ = { 'extend_existing': True }
LOC_CODE = db.Column(db.Text, primary_key=True)
#app.route("/")
def index():
school = School.query.filter(School.LOC_CODE == 'X270').first()
print("School's name is", school.SCHOOLNAME)
return render_template("index.html")
The error has to do with how you utilize db or session. In your third code snippet, the configuration is handled by the School class, and your hashed out line is important to the subsequent queries through it. It is also important for utilizing the reflect method on the db.engine configuration. Switching filter() to filter_by() will also yield the result. I've split my .py files into two, one to create the sqlite db and another for the Flask session. Minimal changes were required to get no error and expected result, tested on both scripts' ending lines.
#create_db.py
from sqlalchemy import create_engine, MetaData, Table, Column, String
from sqlalchemy.orm import mapper, sessionmaker
engine= create_engine('sqlite:///example.db')
metadata = MetaData(engine)
table = Table('schools', metadata,
Column('name', String),
Column('LOC_CODE', String))
metadata.create_all()
ins = table.insert().values(name = 'Victory',
LOC_CODE = 'X270'
)
conn = engine.connect()
conn.execute(ins)
Session = sessionmaker(bind=engine)
session = Session()
schools = table
# Test session below
results = session.query(schools).count()
filt = session.query(schools).filter_by(LOC_CODE='X270').first()
print(results)
print(filt)
#filter_by_test.py
from flask import Flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, Table, Column, String
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
db.Model.metadata.reflect(db.engine)
class School(db.Model):
__tablename__ = 'schools'
__table_args__ = {'extend_existing': True}
LOC_CODE = db.Column(db.Text, primary_key = True)
#app.route("/")
def hello():
print("Total number of schools is", School.query.count())
school = School.query.filter_by(LOC_CODE='X270').first()
print(school.name)
hello()
#combined.py
from flask import Flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, Table, Column, String
import sqlite3
import pandas as pd
#data = 'schools-geocoded - schools-geocoded.csv'
#df = pd.read_csv(data)
#con = sqlite3.connect('example2.db')
#df.to_sql("schools", con)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example2.db'
db = SQLAlchemy(app)
db.Model.metadata.reflect(db.engine)
class School(db.Model):
__tablename__ = 'schools'
__table_args__ = {'extend_existing': True}
LOC_CODE = db.Column(db.Text, primary_key = True)
#app.route("/")
def hello():
print("Total number of schools is", School.query.count())
school = School.query.filter_by(LOC_CODE='X270').first()
print(school.SCHOOLNAME)
hello()
I was able to get past your first error by running these commands from the python console first, then starting up the flask application. This creates the database that is used by your code in the given example. If you have an existing database you will need to change the URI to where it is at. The URI you are using is the one that will be created by using this command. I would look over the Flask-SQLAlchemy documentation to see how to connect to an existing database if desired.
from yourapplication import db
db.create_all()
Source:
https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/
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()
I'm designing a project in Flask with Python that utilizes IBM Watson's Speech-to-Text feature. All I'm trying to do for now is load a FLAC file (0001.flac), interpret the file through Watson, and print the results to my console. I have the following code written thus far (I replaced my username and password for the example):
from werkzeug import secure_filename
import pprint, json, os
from watson_developer_cloud import SpeechToTextV1
. . .
speech_to_text = SpeechToTextV1(
username='My username is here',
password='My password is here')
with open(os.path.join(os.path.dirname(__file__), '0001.flac'), 'rb') as audio_file:
speech_to_text.set_detailed_response(True)
outthis = speech_to_text.recognize(
audio_file, content_type='audio/flac', timestamps=True)
pprint.pprint(json.dumps(outthis.getResult(), indent=2))
And here is my output:
[2018-09-13 11:46:36,553] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 31, in home
pprint.pprint(json.dumps(outthis.getResult(), indent=2))
AttributeError: 'DetailedResponse' object has no attribute 'getResult'
According to the Watson documentation (https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/python.html?python#introduction) I should be able to receive information through getResult on a DetailedResponse object. What am I doing wrong?
I am seeing the same thing from our CI environment, which runs "pip install" from a clean environment. It looks like a breaking changed introduced with watson_developer_cloud v2.0.0 (https://pypi.org/project/watson-developer-cloud/2.0.0/#changes-for-v2.0).
I've addressed for the time being by forcing version 1.7.1 until I can go look deeper at the code changes. It looks like it might be a small-ish change (from a response.get to a response.get_result, but I cannot be sure of that).
FYI - here's the list of breaking changes in 2.0 release: https://github.com/watson-developer-cloud/python-sdk/wiki/Migration
To adhere to PEP8 conventions for function and variable names, the getResult method was renamed to get_result in v2.0.
I am trying to get Flask-SQLAlchemy working and running in to some hiccups. Take a look at the two files I'm using. When I run gwg.py and goto /util/db/create-all it spits out an error no such table: stories. I thought I did everything correct; can someone point out what I'm missing or whats wrong? It does create data.db but the file shows as 0Kb
gwg.py:
application = Flask(__name__)
db = SQLAlchemy(application)
import models
# Utility
util = Blueprint('util', __name__, url_prefix='/util')
#util.route('/db/create-all/')
def db_create_all():
db.create_all()
return 'Tables created'
application.register_blueprint(util)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
application.debug = True
application.run()
models.py:
from gwg import application, db
class Story(db.Model):
__tablename__ = 'stories'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150))
subscribed = db.Column(db.Boolean)
def __init__(self, name):
self.name = name
self.subscribed = False
def toggle_subscription(self):
self.subscribed = False if self.subscribed else True
Edit
Here is the function that seems to be triggering the error but it shouldn't because I specifically go to /util/db/create-all first and then reload /. Even after the error I go to /util/db/create-all and then / and still get the same error
#application.route('/')
def homepage():
stories = models.Story.query.all()
return render_template('index.html', stories=stories)
Stacktrace
sqlalchemy.exc.OperationalError
OperationalError: (OperationalError) no such table: stories u'SELECT stories.id AS stories_id, stories.name AS stories_name, stories.subscribed AS stories_subscribed \nFROM stories' ()
Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\kylee\Code\GWG\gwg.py", line 20, in homepage
stories = models.Story.query.all()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2104, in all
return list(self)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2216, in __iter__
return self._execute_and_instances(context)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2231, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 662, in execute
params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 874, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1024, in _handle_dbapi_exception
exc_info
File "C:\Python27\lib\site-packages\sqlalchemy\util\compat.py", line 163, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 867, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 324, in do_execute
cursor.execute(statement, parameters)
OperationalError: (OperationalError) no such table: stories u'SELECT stories.id AS stories_id, stories.name AS stories_name, stories.subscribed AS stories_subscribed \nFROM stories' ()
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.
The issue here is one a gotcha in the Python import system. It can be simplified to the following explanation...
Assume you have two files in a directory...
a.py:
print 'a.py is currently running as module {0}'.format(__name__)
import b
print 'a.py as module {0} is done'.format(__name__)
b.py:
print 'b.py is running in module {0}'.format(__name__)
import a
print 'b.py as module {0} is done'.format(__name__)
The results of running python a.py are the following...
a.py is currently running as module __main__
b.py is running in module b
a.py is currently running as module a
a.py as module a is done
b.py as module b is done
a.py as module __main__ is done
Notice that when a.py is run, the module is called __main__.
Now think about the code you have. In it, your a.py script creates your application and db objects. However, those values are not stored in a module called a, they are stored in a module called __main__. Therefore, b.py tries to import a, it is NOT importing the values that you just created a few seconds ago! Instead, since it doesn't find module a, it creates a NEW module, running a.py a SECOND TIME and storing the results into the module a.
You can use print statements like what I have shown above to hopefully guide you through the entire process to see exactly what's going on. The solution is to make sure that you are only calling a.py ONCE, and when b.py imports a it will import the same values as a.py rather than importing it a second time.
The easiest way to fix this would be to create a python script that is just for running the application. Remove the application.run() from the end of gwg.py, and add the following script...
main.py:
from gwg import application
application.run()
Then run using python main.py.