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"
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')
I am trying to use this code to add a table to a database in a Flask app on localhost - but it does not work. What should I do?
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:123#localhost:5432/postgres'
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
db.create_all()
I changed my app name from "flask-hello-app" to "app"
and typed these 3 commands in terminal:
python
from app import db
db.create_all()
and it worked for me.
db.session.commit()
Good luck.
I just try your code using both Postgres and MySQL
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://root:55665566#localhost:5432/test'
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)
# from yourapplication import db
db.create_all()
Since I have created the table successfully,
I suggest you check some details below
Check the role attribute for the account.
Check the connection to the database, using command \du to confirm your accounts info, suppose you need to create a user 'postgres' which should show up in the table above.
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
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()
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