Flask-SQLAlchemy invalid identifier on ID column - python-3.x

I am trying to use the Python Terminal to add a user using the following commands:
from app import db
from app.models import User, Post
u = User(username='Jordan',email='jtest#test.net')
db.session.add(u)
db.session.commit()
Below is my model:
class User(db.Model):
id = db.Column(db.Integer, db.Sequence('id_seq'), primary_key=True)
username = db.Column(db.String(64), unique=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(128))
posts = db.relationship('Post', backref='author',lazy='dynamic')
def __repr__(self):
return 'User {}'.format(self.username)
Init script:
from flask import Flask
from config import Config, SnowflakeImpl
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# Creates an instance of the flask application
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from app import routes, models
sqlalchemy.exc.StatementError: (sqlalchemy.exc.ProgrammingError) (snowflake.connector.errors.ProgrammingError) 000904 (42000): SQL compilation error: error line 1 at position 7
invalid identifier 'ID_SEQ.NEXTVAL' [SQL: 'INSERT INTO user (id, username, email, password) VALUES (%(id)s, %(username)s, %(email)s, %(password_hash)s)'] [parameters: [{'email': 'jtest#test.net', 'username': 'Jordan', 'password': None}]] (Background on this error at: http://sqlalche.me/e/f405)
This is the error I am receiving, from what I've read online this should work but it's feeding back an 'invalid identifier' error.

Found the solution, since I am using the flask migrate package I went into the versions folder and observed in the migrate script for my User table my 'Sequence' function was not being included. It was causing my ID to have an Invalid Identifier error.
def upgrade():
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('username')
)

Related

SQLAlchemy : NoForeignKeysError: Could not determine join condition

I'm writing a site for a Flask,and I made a mistake when I want to connect migrations, shows this error
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Users.roles - there are no foreign keys
linking these tables via secondary table 'сайт.role_users'. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or
specify 'primaryjoin' and 'secondaryjoin' expressions.
Here is my code:
from flask import Flask, render_template, request, flash, \
redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_migrate import Migrate
from flask_security import RoleMixin
import os
css_file = 'static/css/main.css'
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lib.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
db = SQLAlchemy(app)
manager = LoginManager(app)
migrate = Migrate(app, db)
role_users = db.Table('role_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')),
)
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(75), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
roles = db.relationship('Roles', secondary=role_users, backref=db.backref('users',
lazy='dynamic'))
def __repr__(self):
return f'<User> -----> {self.login}'
class Roles(db.Model, RoleMixin):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), unique=True, nullable=False)
def __repr__(self):
return f'<Role> ----> {self.title}'
Although there were no such errors during the first migration
.......
Help solve this problem

raise exc.NoSuchModuleError( sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgresql

I created a sample flask application, I want to connect PostgreSQL database to my project.
I installed flask_sqlalchemy.
here is my Code
from flask import Flask, url_for, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://michealscott:dwight#localhost:5432/michealscott'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
#app.route('/')
def hello_world():
return render_template("index.html")
I cd-ed into my src directory and executed:
python
>> from app import db
>> db.create_all()
then the above error shows up.
After searching over internet. I also did
pip install psycopg2
still no luck.
there is a same question on stack overflow and couple of answers/suggestions. I was not able to comment on the post so asking it again pardon me!
Please help.
Thank you in advance.

Flask-Dance SQLAlchemy integration not working

I'm using Flask-Dance to use Google to login to my application. I am also using SQLAlchemy and Flask-Login.
Everything regarding the Google login is working perfectly but it is supposed to save the token data in a table created by SQLAlchemy (flask_dance_oauth) but it isn't. Every time I login, it doesn't save the token data in the table, even though I specified it.
from app import db
from flask_dance.contrib.google import make_google_blueprint
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
from flask_login import current_user
from Tables import OAuth
blueprint = make_google_blueprint(
client_id="clientid",
client_secret="secret",
scope=['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email',
'openid'],
storage=SQLAlchemyStorage(OAuth, db.session, user=current_user))
And my SQLAlchemy class:
from app import db
from datetime import *
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from flask_login import UserMixin
class Users(UserMixin, db.Model):
__bind_key__ = 'users'
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(50), index=True, unique=True)
email = db.Column(db.String(100), unique=True)
fname = db.Column(db.String(20))
lname = db.Column(db.String(20))
authenticated = db.Column(db.Boolean, default=True)
class OAuth(OAuthConsumerMixin, db.Model):
__bind_key__ = 'users'
user_id = db.Column(db.String(50), db.ForeignKey(Users.uuid))
user = db.relationship(Users)
The curious part is that I did this exact same code in another project and it worked perfectly. But in this one it won't. Could it be because of the way the User table is built? The one here has first name and last name, but the User table in the other project I made only has the UUID and the email. Any help will be appreciated.
Did you resolve this? What is the OAuth table name in your database? If it isn't flask_dance_oauth, then it seems to me you are missing the table name for the OAuth table. It should be:
class OAuth(OAuthConsumerMixin, db.Model):
__bind_key__ = 'users'
__tablename__ = 'flask_dance_oauth'
user_id = db.Column(db.String(50), db.ForeignKey(Users.uuid))
user = db.relationship(Users)
Flask Dance expects this table in your database and updates the token for that user in there for reuse, etc.

Flask migration fails

I'm making migrations in Flask using unsurprisingly Flask-Migrate.
once I execute python manage.py db init it creates directory migrations with initial migrations file. Then
I execute python manage.py db migrate and I get this:
...
...
target_metadata = current_app.extensions['migrate'].db.metadata
AttributeError: 'NoneType' object has no attribute 'metadata'
I understand from this output that 'migrate' is None hence I'm getting an attribute error.
models.py:
from sqlalchemy.sql import func
from project import db, bcrypt
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(128), nullable=False, unique=True)
email = db.Column(db.String(128), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False)
active = db.Column(db.Boolean(), default=True, nullable=False)
created_date = db.Column(db.DateTime, default=func.now(), nullable=False)
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = bcrypt.generate_password_hash(password).decode()
def to_json(self):
return {
'id': self.id,
'username': self.username,
'email': self.email,
'active': self.active,
}
The question is why nothing is being passed to it ? I'm following a tutorial and I'm not supposed to have this error.
I've got this from similar topic:
NoneType means that instead of an instance of whatever Class or Object
you think you're working with, you've actually got None. That usually
means that an assignment or function call up above failed or returned
an unexpected result.
this is what I've found in env.py file in the migrations directory:
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
current_app is being imported from Flask but doesn't contain the extension migrate from which I need to use the metadata.
There's no reason for it to be throwing None though because the extension is correctly initilised in __init__.py file:
...
...
from flask_migrate import Migrate
db = SQLAlchemy()
toolbar = DebugToolbarExtension()
cors = CORS()
migrate = Migrate()
bcrypt = Bcrypt()
def create_app(script_info=None):
app = Flask(__name__)
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
app.config.from_object('project.config.DevelopmentConfig')
toolbar.init_app(app)
cors.init_app(app)
db.init_app(app)
migrate.init_app(app) # <--
bcrypt.init_app(app)
from project.api.users import users_blueprint
app.register_blueprint(users_blueprint)
#app.shell_context_processor
def ctx():
return {'app': app, 'db': db}
return app
I had a missing argument in the initialization of the migrate extension. Migrate takes in the app instance and the instance of db.
def create_app(script_info=None):
app = Flask(__name__)
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
app.config.from_object('project.config.DevelopmentConfig')
toolbar.init_app(app)
cors.init_app(app)
db.init_app(app)
migrate.init_app(app, db) # <--
bcrypt.init_app(app)
from project.api.users import users_blueprint
app.register_blueprint(users_blueprint)
#app.shell_context_processor
def ctx():
return {'app': app, 'db': db}
return app

ImportError: cannot import name 'Task' from 'app.models'

Ok so I am new to flask and i am trying to set up a simple task manager. And I have a problem with importing my database.
When I made my first import my db was named User and it had fields like email, username, ...
Now all I did was renaming the call of database form User to Task and changed some fields or added more.
and now when I run a command:
>>> from app.models import Task
I get an error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ImportError: cannot import name 'Task' from 'app.models' (/Users/janzaplatil/Desktop/taskmanager/app/models.py)
but if I run a >>> from app.models import User all is fine. But it makes no sense to me since there is no class User, only Task
My model python file:
from datetime import datetime
from app import db
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
task = db.Column(db.String(64), index=True, unique=True)
description = db.Column(db.String(120), index=True, unique=True)
start = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<Task {}>'.format(self.task)
My flask app:
from app import app, db
from app.models import Task
#app.shell_context_processor
def make_shell_context():
return {'db': db, 'Task': Task}

Resources