1

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
0

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

@LAI In that case simply use flask_sqlalchemy. I have updated the answer. You should install it using pip if you haven't already done so: flask-sqlalchemy.palletsprojects.com/en/2.x
@LAI It is flask-sqlalchemy (with a dash instead of an underscore). Please also read the documentation as we can't provide all the information here as comments.
For your information @Selcuk, I still cannot install the module by using the command. Any solution can solve it? Is it version problem or anything?
It is certainly on PyPI. You must be doing something wrong. Double check your command: pypi.org/project/Flask-SQLAlchemy
0

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)

2 Comments

My Flask library don't have this flask_sqlalchemy module, I have tried this way before, but still cannot work.
OK, another answer is quite good, I think that is just the right answer you want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.