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)
Related
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
'''
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)
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.
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()
I'm having trouble creating a modular application using Flask using blueprints. I'm not sure how to migrate models defined in blueprints.
My app looks as follows:
- app
- __init__.py
- user
__init__.py
models.py
app.__init__.py looks as follows:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config
from flask_migrate import Migrate
from app.auth import bp as user_bp
db = SQLAlchemy()
app = Flask(__name__)
app.config.from_object(Config)
app.register_blueprint(user_bp, url_prefix='/user')
migrate = Migrate(app, db)
from app.auth.models import User
user/.__init__.py:
from flask import Blueprint
bp = Blueprint('user', __name__)
user/models.py:
from app import db
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(128))
last_name = db.Column(db.String(128))
user_name = db.Column(db.String(120))
password_hash = db.Column(db.String(220))
def __repr__(self):
return '<User {}>'.format(self.email)
When trying to run flask db migrate... no models are being detected and I think I have some sort of circular dependency.
Can someone please explain how to do this properly?
The User model (user/models.py) should be imported somewhere in the application, try to import into the blueprint file (user/__init__.py)
from flask import Blueprint
from app.user.models import User
bp = Blueprint('user', __name__)
app.py
from flask import Flask
from flask_restful import Resource, Api
from user import user_blueprint
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
app.register_blueprint(user_blueprint)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
if __name__ == '__main__':
app.run(debug=True)
model/user.py
from sqlalchemy import Column, INTEGER, String
class User(Base):
__tablename__ = 'USER'
__table_args__ = {'schema': 'MAPPING'}
ID = Column(INTEGER(11), primary_key=True)
FIRST_NAME = Column(String(255), nullable=False, server_default=text("''"))
LAST_NAME = Column(String(255), nullable=False, server_default=text("''"))
EMAIL = Column(String(255), nullable=False, server_default=text("''"))
route/user_route
from flask import Blueprint, jsonify, request
from flask_restful import Resource, Api
user_blueprint = Blueprint('app/', __name__)
user_api = Api(user_blueprint, prefix='/')
class User(Resource):
def get(self):
db_conn = //db connection Object
results = // your query
db_conn.close()
return jsonify(results)
user_api.add_resource(User, '/user')