SQLAlchemy has no attribute Column - python-3.x

Below this is my code i'm learning flask and at this step i'm creating database with flask_sqlachemy. i created an instance of SQLAlchemy that is User, actually i coded like the tutor did but in my case i have this problem, i code this in Pycharm. 'Unresolve attribute refrence Column for class SQLAlchemy' but when i run it there is no error. In the video i saw there is no problem about this. Please help me why pycharm did that!
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = '2bd147089908273bb6fd4fd4ce75cf7d'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)

PyCharm just checks if class SQLAlchemy has an attribute "Column" which it does not. You can resolve your PyCham issue by adding # noinspection PyUnresolvedReferences before your class, i.e.:
# noinspection PyUnresolvedReferences
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
Also, as soon as you use an application factory pattern PyCharm will find the 'Column' attributes.
But why are the attributes missing? The answer is in the docstring of the SQLAlchemy object.
This class also provides access to all the SQLAlchemy functions and classes
from the :mod:sqlalchemy and :mod:sqlalchemy.orm modules. So you can
declare models like this:
class User(db.Model):
username = db.Column(db.String(80), unique=True)
pw_hash = db.Column(db.String(80))
[...] If you use these
interfaces through :mod:sqlalchemy and :mod:sqlalchemy.orm directly,
the default query class will be that of :mod:sqlalchemy.

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

Syntax error def __repr__(self)

I'm just working my way through the book Flask Web Development. I'm stuck now and can't help myself.
This is the part of my code which makes the problem.
import os
from flask_script import Manager
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_wtf import FlaskForm
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from wtforms import StringField, SubmitField, validators
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
class NameForm(FlaskForm):
name = StringField('What is your name?', validators=[Required()])
submit = SubmitField('Submit')
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.Column('User',backref='role')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Interger, db.ForeignKey('roles.id')
def __repr__(self):
return '<User %r>' % self.username
When I try to start the shell, I get the following error message:
line 30
def __repr__(self):
^
SyntaxError: invalid syntax
Guys where is the problem?
You are missing a closing brace ()) in this line:
role_id = db.Column(db.Interger, db.ForeignKey('roles.id')

Resources