Reputation: 11
This the my code, when I learnt Flask by following a book of Miguel Grinberg.
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_bootstrap import Bootstrap
from datetime import datetime
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager, Server
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMENT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
old_name = session.get('name')
if old_name is not None and old_name != form.name.data:
flash('We have a new visitor!')
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'),
current_time=datetime.utcnow())
manager = Manager(app)
manager.add_command("server", Server())
@manager.shell
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
@property
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
@property
def __repr__(self):
return '<User %r>' % self.username
if __name__ == '__main__':
manager.run()
After that, I established two tables (models) in the console.
db.drop_all()
db.create_all()
admin_role = Role(name='Admin')
mod_role = Role(name='Moderator')
user_role = Role(name='User')
user_john = User(username='john', role=admin_role)
user_susan = User(username='susan', role=user_role)
user_david = User(username='david', role=user_role)
db.session.add_all([admin_role, mod_role, user_role, user_john, user_susan, user_david])
db.session.commit()
admin_role.name = 'Administrator'
db.session.add(admin_role)
db.session.commit()
db.session.delete(mod_role)
db.session.commit()
Everything went very well so far. But when I tried to query something from the Model Role. It just didn't work.
>>> Role.query.all()
[Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'str' object is not callable
There are already a few explanations about the 'str' problem. However, it seems none of them matches my situation perfectly.
Could anyone help me? I would appropriate that.
Upvotes: 0
Views: 1549
Reputation: 11
I would like to thank the answer here https://stackoverflow.com/a/34781856/2681632 Just delete the @property in following section of both moduls
@property
def __repr__(self):
return '<Role %r>' % self.name
Upvotes: 1