I'm learning to create API's using Python here. I've gotten everything ready and downloaded the database, however when I run my app I'm getting the following error:
Traceback (most recent call last):
File "app.py", line 7, in <module>
e = create_engine("sqlite3:///salaries.db")
File "C:\Python27\lib\site-packages\sqlalchemy\engine\__init__.py", line 387, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\strategies.py", line 56, in create
entrypoint = u._get_entrypoint()
File "C:\Python27\lib\site-packages\sqlalchemy\engine\url.py", line 139, in _get_entrypoint
cls = registry.load(name)
File "C:\Python27\lib\site-packages\sqlalchemy\util\langhelpers.py", line 212, in load
(self.group, name))
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqlite3
What am I doing wrong to where it will not load the correct plugin?
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
e = create_engine("sqlite3:///salaries.db")
app = Flask(__name__)
api = Api(app)
class DepartmentsMeta(Resource):
def get(self):
conn = e.connect()
query = conn.execute("select distinct DEPARTMENT from salaries")
return {"departments": [i[0] for i in query.cursor.fetchall()]}
class DepartmentSalary(Resource):
def get(self, department_name):
conn = e.connect()
query = conn.execute("select * from salaries where Department='%s'" % department_name)
result = {"data": [dict(zip(tuple(query.keys()), i))] for i in query.cursor}
return result
api.add_resource(DepartmentSalary, "/dept/<string:department_name>")
api.add_resource(DepartmentsMeta, "/department")
if __name__ == "__main__":
app.run()
Please try replacing this line:
e = create_engine("sqlite3:///salaries.db")
with
e = create_engine("sqlite:///salaries.db")
I got the same problem. I've solved it by:
pip3 uninstall flask_sqlalchemy and pip3 install flask-sqlalchemy==2.5.1 because big changes with flask-sqlalchemy==3.0 SQLite DB in memory are not set as default in this version.
Hope it helps you.
Related
I have used sql-alchemy for so long but I don't know it suddnly stopped working and showing me errors
Code
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
# initialize the app with the extension
db.init_app(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
email = db.Column(db.String)
with app.app_context():
db.create_all()
this is code available on sqlalchemy documentation
Error
(venv) viral#viral-Lenovo:~/Desktop/sql-practice$ python main.py
Traceback (most recent call last):
File "/home/viral/Desktop/sql-practice/main.py", line 11, in <module>
db.init_app(app)
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 326, in init_app
engines[key] = self._make_engine(key, options, app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 614, in _make_engine
return sa.engine_from_config(options, prefix="")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 817, in engine_from_config
return create_engine(url, **options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in create_engine
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/util/deprecations.py", line 277, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 605, in create_engine
dbapi = dbapi_meth(**dbapi_args)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py", line 504, in import_dbapi
from sqlite3 import dbapi2 as sqlite
File "/usr/local/lib/python3.11/sqlite3/__init__.py", line 57, in <module>
from sqlite3.dbapi2 import *
File "/usr/local/lib/python3.11/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'
I expected that it will create a database by creating new folder called instance. but it's only creating instance folder but not database
I have tried creating new venv, reinstalling python and restarting pc but still it's showing the same error.
note: I am using Linux, Ubuntu Kde plasma
Good day.
I have one question. How to access a configuration item from another .py file
For example.
app/__init__.py
def create_app(config=None):
app = Flask(__name__, instance_relative_config=True)
app._static_folder = './static'
app.config.from_pyfile('flask.cfg')
app.app_context().push()
return app
wsgi.py
from app import create_app
from werkzeug.debug import DebuggedApplication
if __name__ == "__main__":
app = create_app()
application = DebuggedApplication(app, evalex=True)
app.logger.info("Debug status is: " + str(app.config['DEBUG']))
app.run(use_reloader=True, debug=True)
app/core/helper.py
from flask import current_app as app
def get_dir():
return app.config["PATH_CACHE_DIR"]
Try to call method app/core/cached.py
from flask_caching import Cache
from flask import current_app as app
from app.core.helper import get_dir
print get_dir()
So, i receive the following error
Traceback (most recent call last):
File "/home/stanislav/Python/mbgp/wsgi.py", line 1, in <module>
from app import create_app
File "/home/stanislav/Python/mbgp/app/__init__.py", line 4, in <module>
from app.core.cached import cache
File "/home/stanislav/Python/mbgp/app/core/cached.py", line 5, in <module>
print get_dir()
File "/home/stanislav/Python/mbgp/app/core/helper.py", line 14, in get_dir
return app.config["PATH_CACHE_DIR"]
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 51, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current applicat`enter code here`ion object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
Please tell me how to fix this, thank you very much.
I have written my unitest in flask like (with in memory database);
import unittest
import json
from lobdcapi import app
from dal.dbContext import db
from models.AtgSiteToPoll import *
class TestAtgSiteToPollEP(unittest.TestCase):
def setUp(self):
app.testing = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
self.app = app.test_client()
with app.app_context():
db.init_app(app)
db.drop_all()
db.create_all()
def tearDown(self):
pass
def test_atg_sitetopoll(self):
a = AtgSiteToPoll()
a.SiteId = 1
a.IPAddress = '10.10.10.10'
a.Port = 3000
a.Category = 1
a.UserId = 'test'
a.Password = 'test123'
a.ReceiveTimeoutInMilliSeconds = 60
db.session.add(a)
db.session.commit()
assert len(AtgSiteToPoll.query.all()) is 1
When running the test I get;
Traceback (most recent call last):
File "/Users/ratha/projects/test711/ATGWS/tests/TestAtgSitesToPollEP.py", line 31, in test_atg_sitetopoll
db.session.add(a)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2939, in __call__
return self.class_(**local_kw)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 141, in __init__
self.app = app = db.get_app()
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 912, in get_app
'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
What Im doing wrong here?
I'm building an API service with Flask, SQLAlchemy and more recently integrating the Flask-SQLAlchemy extension. While I can run the app standalone and make API calls successfully, I am hitting a problem attempting to run unittests. I believe the issue is with importing the db.Model types more than once.
The exception is this:
Error
Traceback (most recent call last):
File "/Users/james/.pyenv/versions/2.7.10/lib/python2.7/unittest/case.py", line 322, in run
self.setUp()
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/tests/test_users.py", line 28, in setUp
from trustmile.app.users.model import User, ConsumerUser, CourierUser, AuthSession, Location, UserAddress, db
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/users/model.py", line 23, in <module>
class User(db.Model, UniqueMixin, TableColumnsBase, References):
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 536, in __init__
DeclarativeMeta.__init__(self, name, bases, d)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/api.py", line 55, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 88, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 103, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 131, in __init__
self._setup_table()
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 394, in _setup_table
**table_kw)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 398, in __new__
"existing Table object." % key)
InvalidRequestError: Table 'tmuser' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
My init.py in /app/ (the top level) is like this:
__author__ = 'james'
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import config
from app.messaging import EmailHandler
app = Flask(__name__, static_folder='api/static', static_url_path='/static')
app.config.from_object(config)
db = SQLAlchemy(app)
EmailHandler.setup(config.EMAIL_API_KEY_DEV)
from app.api.consumer_v1 import bp as blueprint
app.register_blueprint(blueprint, url_prefix = '/consumer/v1')
app.test_request_context()
Running that with:
from app import app
app.run(debug=True, host='0.0.0.0', port=5001)
Works great.
The beginning of my test_users.py looks like this:
__author__ = 'james'
from trustmile.app.exc import InvalidEmailException
from trustmile.app.exc import InsecurePasswordException
from nose.tools import assert_true, raises
from trustmile.app.users.model import User, ConsumerUser, CourierUser, AuthSession, Location, UserAddress, db
from . import TransactionalTest
email_address = 'james#cloudadvantage.com.au'
test_password = 'mypassword'
class UserTest(TransactionalTest):
#classmethod
def setUpClass(cls):
super(UserTest, cls).setUpClass()
def setUp(self):
super(UserTest, self).setUp()
def test_create_user(self):
user = User()
db.session.add(user)
It must be fairly common way to do unit testing and yes I'm sharing the SQLAlchemy object between modules (which I'm sure is bad practice). I'm running it with nosetests and the error occurs as the code is initialised. Sorry for the lengthy question, hopefully someone can help me!
__table_args__ = {'extend_existing': True}
right below __tablename__
Database example.db is created but generates error !!!
Traceback (most recent call last):
File "db_testing.py", line 39, in admin.save()
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 2405, in save
new_pk = insert.execute()
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1721, in execute
return self.database.last_insert_id(self._execute(), self.model_class)
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1420, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1824, in execute_sql
res = cursor.execute(sql, params or ())
sqlite3.IntegrityError: column email is not unique
Code
import datetime
from flask import Flask
from flask_peewee.admin import Admin
from flask_peewee.auth import Auth
from flask_peewee.db import Database
from peewee import *
# configure our database
DATABASE = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = 'ssshhhh'
app = Flask(__name__)
app.config.from_object(__name__)
# instantiate the db wrapper
db = Database(app)
# create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db)
admin = Admin(app, auth)
class Note(db.Model):
message = TextField()
created = DateTimeField(default=datetime.datetime.now)
admin.register(Note)
admin.setup()
if __name__ == '__main__':
auth.User.create_table(fail_silently=True)
Note.create_table(fail_silently=True)
admin = auth.User(username='admin', email='aoeu#gmail.com', admin=True, active=True)
admin.set_password('admin')
admin.save()
app.run()
using example from
http://flask-peewee.readthedocs.org/en/latest/getting-started.html#setting-up-a-simple-base-template
Database was already created, deleting previous database solved it