这是我的代码,当我通过阅读Miguel Grinberg的书来学习Flask时。
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()
之后,我在控制台中建立了两个表(模型)。
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()
到目前为止,一切都很顺利。但是当我尝试从模型 角色 中查询某些内容时。它只是没有用。
>>> Role.query.all()
[Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'str' object is not callable
关于&#39; str&#39;已经有一些解释。问题。然而,似乎没有一个完全符合我的情况。
有人能帮帮我吗?我愿意这样做。
答案 0 :(得分:0)
我要感谢这里的答案https://stackoverflow.com/a/34781856/2681632 只需删除两个模块的以下部分中的 @property
即可@property
def __repr__(self):
return '<Role %r>' % self.name