What is model class of SQLAlchemy? - python

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
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
def __repr__(self):
return '<User %r>' % self.username
This code I have found in SQLAlchemy documentation. db=SQLAlchemy(app) It means that db is a object. class User(db.Model) by looking at the line it looks like that db is a module name.
what basically db is?can someone explain me.
https://developers.google.com/appengine/docs/python/datastore/modelclass
I have read this but not able to understand.

The db = SQLAlchemy(app) is the way to set the db variable with the correct app context, is basically to register the application on db instance, we use this to associate the application bound to the current context

Related

Issue deploying Python Flask Package, more specifically unable to open database file

The Error message that shows up is sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8)
And the Traceback stated the error as fighters = Fighter.query.all()
I have tried different methods of `
fighters.query.get(Fighter)
`
I just tried
fighters = Fighter.query.order_by('id').all()
And i had gotten the same error which leads me to think its an issue initializing the database or possibly the database path.
I am unsure whether it is creating the database is the issue or querying the results.
My code in the run.py file is as follows-
import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# DATABASE_URL is by default
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///tmp/test.db')
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, email):
self.email = email
def __repr__(self):
return '<User %r>' % self.email
class Fighter(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=True)
class Vote(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref=db.backref('votes', lazy='dynamic'))
fighter_id = db.Column(db.Integer, db.ForeignKey('fighter.id'))
fighter = db.relationship('Fighter', backref=db.backref('votes', lazy='dynamic'))
#app.route('/', methods=['GET', 'POST'])
def homepage():
fighters = Fighter.query.all()
return render_template('index.html', fighters=fighters)
if __name__ == '__main__':
app.run(debug=True)
And my init_db.py file goes as follows-
from run import db, Fighter
# Create all the tables
db.create_all()
# create fighters
conor = Fighter(name='Conor McGregor')
floyd = Fighter(name='Floyd Mayweather')
# add fighters to session
db.session.add(conor)
db.session.add(floyd)
# commit the fighters to database
db.session.commit()
try this
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'
instead of this
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///tmp/test.db')

Can't create the initial database with Flask-SQLAlchemy?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password#localhost/database'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
When I try to run it
>> from app.py import db
>> db.create_all()
Above is the complete error message
I have found in the Task Manager, the postgresql service is on.
The database password is correct and I can't find where the error is.
My computer is Win10 and I installed postgresql using the official installer
replace the word database with the name of your database
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password#localhost/database'
by default, your database name is likely 'postgres', you also need to provide your port number, default is 5432.
Try using the following:
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:password#localhost:5432/postgres"

How to create a User class for Flask-Login when using dynamodb?

I am following the tutorial at https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login for adding register/login features to a flask app, which uses Flask-Login with an SQLite database (using flask_sqlalchemy). As such, it has code like the following for initializing the SQLite database (from init.py):
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '9OLWxND4o83j4K4iuopO'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db.init_app(app)
And then creates a User class (as is required by Flask-Login) like this:
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
However, I want to store user information in a dynamodb table, not a SQLite table. How then should I write the User class? I want each User to have an email, password and name property like in this tutorial (along with other properties/methods required at https://flask-login.readthedocs.io/en/latest/#your-user-class as is handled by UserMixin), but am unsure how to write the class when using dynamodb.
I wrote the User class simply as follows:
class User(UserMixin):
def __init__(self, id, email, name, password):
self.id = id
self.email = email
self.name = name
self.password = password
I used the User class from ZhouW and you will also need a custom user_loader. This here should work:
class User(UserMixin):
def __init__(self, id, email, password):
self.id = id
self.email = email
self.password = password
#login_manager.user_loader
def loader(user_id):
response = table.query(
KeyConditionExpression=Key('id').eq(user_id))
if response["Count"] == 0:
return
user = User(id=response['Items'][0]["id"], email=response['Items'][0]["email"], password=response['Items'][0]["password"])
return user
Will need a table first, connect something like this:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
from boto3.dynamodb.conditions import Key

how to connect to mysql using SQLAlchemy

I am using the below code to connect mysql using SQLAlchemy, help me out with the proper code. My configuration as below:
username: root
password: ''
host: localhost
port: 3307
db: logdb
MySQL was configured as:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:#localhost/login'
code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:#localhost/logdb'
db = SQLAlchemy(app)
class User(db.Model):
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
def __repr__(self):
return '<User %r>' % self.username
admin = User('root', 'admin')
db.create_all() # In case user table doesn't exists already. Else remove it.
db.session.add(admin)
db.session.commit() # This is needed to write the changes to database
User.query.all()
User.query.filter_by(username='root').first()
You should install pymysql first.
pip install pymysql
and then config your mysql as :
mysql+pymysql://root:password#127.0.0.1/logdb

python flask sqlalchemy, i can'trun my db_create.py

Ame getting this error of TypeError: init() takes exactly 1 argument (5 given)...where have i gone wrong?? any help i will appreciate ,thanks
thats my db_create.py file
from app import db
from models import post
db.create_all()
db.session.add(post("Good", "i\m good","yes","hae"))
db.session.add(post("Good", "hahaha"))
db.session.add(post("Good", "you"))
db.session.add(post("Good", "hahaha"))
my model.py file is
from app import db
class post(db.Model):
# table name
__tablename__ = "signup"
#columns names
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
email= db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
confirm= db.Column(db.String, nullable=False)
def __init__(self, username, email, password, confirm):
self.username = username
self.email = email
self.pasword = password
self.confirm = confirm
def __repr__(self,*args, **kwargs):
return '<username {}'.format(self.username), 'email{}'.format(self.email),'password{}'.format(self.password)
this is my init
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = "my previous"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///signup.db'
db = SQLAlchemy(app)
from app import views
You don't need the __init__ method in your post model. Just use the __init__ method inherited from db.Model and you should be fine.
But then I believe you'd need to modify your db_create.py a bit:
For example:
db.session.add(post(username="User", email="user#email.com", password="password", confirm="Yes"))
Also you need to remember to commit your changes:
db.session.commit()

Categories