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
Related
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')
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"
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()
I am working on a flask app based on http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982.
As part of the tut I'm trying to connect to a postgres server, with a structure as in the screenshot. I've added a db 'flask' which you can see.
Based on the tut I have the following code in my main file ('routes.py'):
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:123#localhost/flask"
db = SQLAlchemy(app)
from models import User
# db.init_app(app)
db.create_all()
db.session.commit()
admin = User('admin', 'admin#example.com', 'admin1', 'admin1#example.com')
guest = User('admi2', 'admin#ex1ample.com', 'admin', 'admin2#example.com')
# guest = User('guest', 'guest#example.com')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
models.py:
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
uid = db.Column(db.Integer, primary_key = True)
firstname = db.Column(db.String(100))
lastname = db.Column(db.String(100))
email = db.Column(db.String(120), unique=True)
pwdhash = db.Column(db.String(54))
def __init__(self, firstname, lastname, email, password):
self.firstname = firstname.title()
self.lastname = lastname.title()
self.email = email.lower()
self.set_password(password)
def set_password(self, password):
self.pwdhash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
When run the debugger gives:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "users" does not exist
LINE 1: INSERT INTO users (firstname, lastname, email, pwdhash) VALU...
^
[SQL: 'INSERT INTO users (firstname, lastname, email, pwdhash) VALUES (%(firstname)s, %(lastname)s, %(email)s, %(pwdhash)s) RETURNING users.uid'] [parameters: {'lastname': 'Admin#Example.Com', 'firstname': 'Admin', 'pwdhash': 'pbkdf2:sha1:1000$eZvJNKHO$64f59c34364e3d6094d126fa3ca2b327ab39e302', 'email': 'admin1'}]
What am I doing wrong?
You're initializing your database twice.
I'd suggest taking a good look at this: http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
Essentially, you'll want to split things up into a few more files to prevent import issues and make things a little more clean. I've done the below which seems to work. Note, I've used SQLite, since I do not have Postgres installed on this box.
app.py
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////test11.db'
models.py
from flask.ext.sqlalchemy import SQLAlchemy
from app import app
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
uid = db.Column(db.Integer, primary_key = True)
firstname = db.Column(db.String(100))
lastname = db.Column(db.String(100))
email = db.Column(db.String(120), unique=True)
pwdhash = db.Column(db.String(54))
def __init__(self, firstname, lastname, email, password):
self.firstname = firstname.title()
self.lastname = lastname.title()
self.email = email.lower()
self.set_password(password)
def set_password(self, password):
self.pwdhash = (password)
def check_password(self, password):
return password
routes.py
from models import User, db
db.create_all()
db.session.commit()
admin = User('admin', 'admin#example.com', 'admin1', 'admin1#example.com')
guest = User('admi2', 'admin#ex1ample.com', 'admin', 'admin2#example.com')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
I'd definitely suggest looking over some tutorials! You'll need it: you should learn about web vulnerabilities, best practices, and so on.
The tutorial you linked to has a section called "Create a User Model", under which it tells you how to use CREATE TABLE ... to create your users table. It gives some MySQL-specific syntax for this, although you are apparently using Postgres, so your command will be slightly different.
But the screenshot you posted (from pgAdmin?) clearly shows that the "public" schema in the flask database has zero tables, so obviously you have not created this table yet. You'll have to create this table, you should be able to do so through pgAdmin, something like:
CREATE TABLE users (
uid serial PRIMARY KEY,
firstname varchar(100) not null,
... follow the guide for the rest of the columns ...
);
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