AttributeError: 'SQLAlchemy' object has no attribute 'datetime' - python

Im following a youtube tutorial on using Flask and when i run this code by using python -m flask run it shows this AttributeError: 'SQLAlchemy' object has no attribute 'datetime'. How can I fix it?
from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime as dt
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.datetime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)

Column types are classes and capitalized. Try this:
db.Column(db.DateTime, default=datetime.utcnow)
Notice DateTime, not datetime.

Related

NameError: name 'SQLAlchemy' is not defined

I've installed SQLAlchemy by adding it through project settings but am getting this error which i can't seem to figure out:
Traceback (most recent call last):
File "/Users/backup/PycharmProjects/pythonProject/app.py", line 5, in
db=SQLAlchemy(app)
NameError: name 'SQLAlchemy' is not defined
app.py:
from flask import Flask, render_template
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed=db.Column(db.integer, default=0)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
You've forgot to import sqlalchemy module in the beginning:
from flask_sqlalchemy import SQLAlchemy

Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'db' is not defined

'''
import db.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app =Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
class Question(db.model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db,Text, nullable=False)
Date_Posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return 'Question' + str(self.id)
#app.route('/mainpage' , methods = ['GET'])
def mainpage():
return render_template("main.html")
#app.route('/askdaiwik')
def ask():
return render_template("ask.html" , ask = all_ask)
if __name__ == "__main__":
app.run(debug=True)
'''
If I'm not wrong you are trying to use SQLAlchemy object as db. But you didn't create the object and hence db is undefined.
wrap your app with SQLAlchemy to create the object and assign the variable db to the instance.
db = SQLAlchemy(app)
In db.py where you can store the code db = SQLAlchemy().
Then import it in app.py. Now you can call db.
or just remove APP in db=SQLAlchemy(app)

Need Help: AttributeError: "SQLAlchemy" object has no attribute 'Models'

AttributeError: sqlalchemy object has no attribute "Models" error is occurring. I already installed all requirements like pip install sqlalchemy, flask-sqlalchemy, psycopy2-binary. this file name is create.py
import os
from flask import Flask, render_template, request
from models import *
app = Flask(__name__)
app.config["SQLALchemy_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALchemy_TRACK_MODIFICATIONS"] = False
db.init_app(app)
def main():
db.create_all()
if __name__ == "__main__":
with app.app_context():
main()
this file is models.py
from flask_sqlalchemy import SQLAlchemy
db=SQLAlchemy()
class Flight(db.Models):
__tablename__ = "flights"
id = db.Column(db.Integer, primary_key=True)
origin = db.Column(db.String, nullable=False)
destination = db.Column(db.String, nullable=False)
duration = db.Column(db.Integer, nullable=False)
class Passenger(db.Models):
__tablename__ = "passengers"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
flight_id = db.Column(db.Integer, db.ForeignKey("flights.id",
nullable=False))
output is:
Traceback (most recent call last):
File "create.py", line 4, in
from models import *
File "D:\web\flaskrun\models.py", line 5, in
class Flight(db.Models):
AttributeError: 'SQLAlchemy' object has no attribute 'Models'
As mentioned in the flask-sqlalchemy docs your models need to derive from db.Model without the trailing s
Furthermore it provides a class called Model that is a declarative base which can be used to declare models:
It should be db.Model instead of db.Models.
I got this same error because there was typing mistake I made the s small in string method for datatype like
db.String()--->correct
db.string()--->Incorrect
name=db.Column(db.String(),nullable=False)
Hope this helps someone

Create all tables with Flask-SQLAlchemy

I have some difficulties with the library lask-sqlalchemy, I tried to create my database with the code bellow, i have no error but no table created.
_init.py
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
app.app_context().push()
db.py
from flask_sqlalchemy import SQLAlchemy
from api_lab import app
db = SQLAlchemy(app)
member.py
from api_lab.models.db import db
class Member(db.Model):
__table_args__ = {"schema": "public"}
id = db.Column(db.BigInteger,
primary_key=True,
autoincrement=True)
id_company = db.Column(db.BigInteger,
db.ForeignKey("compagny.id"),
index=True,
nullable=False)
nom = db.Column(db.String(80), unique=True, nullable=False)
age = db.Column(db.Integer, unique=True, nullable=False)
def __repr__(self):
return '<Member %r>' % self.nom
run_api.py
from api_lab import app
from api_lab.models.db import db
def main():
host = app.config["ENV"]["HOST"]
port = app.config["ENV"]["PORT"]
debug = app.config["ENV"]["DEBUG"]
app.run(host=host, port=port, debug= debug)
if __name__ == '__main__':
db.create_all()
#main()
You should put all initialization related logic into init.py
Use SQLAlchemy to setup a db connection with your app.config
init.py
from api_lab import app
from api_lab.models.db import db
from flask_sqlalchemy import SQLAlchemy
app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
app.app_context().push()
db = SQLAlchemy(app)
# initialize the DB
db.create_all()

Could not load the module

I am new to Python and Flask module. I got an error after running my code. My code look like this:
from flask import Flask, render_template, url_for
from sqlalchemy import sql
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = sql(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
I need to proceed this code to create a website. However, I got an error from line 7, that is:
TypeError: 'module' object is not callable
You should not directly use the sqlalchemy package (and you are doing it wrong, anyway). The correct way of using SQLAlchemy with Flask is:
from flask_sqlalchemy import SQLAlchemy
...
db = SQLAlchemy(app)
You can change your code like this, use flask_sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)

Categories

Resources