0

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.

4
  • What is the output of >>> Role? Commented Apr 8, 2018 at 16:14
  • __repr__ is supposed to be a method, not a property. Now your shell is trying to represent your objects, looks up the method, but is served a string instead. Remove the @property decorator. Commented Apr 8, 2018 at 17:21
  • stackoverflow.com/a/34781856/2681632 Commented Apr 8, 2018 at 17:47
  • The link in LAST comment is direct the solution of the problem. Thanks! Commented Apr 8, 2018 at 18:28

1 Answer 1

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.