the environmental background of the problems and what methods you have tried
there is a problem with role verification. The role verification code current_user.can (Permission.WRITE_ARTICLES) and
deletes that the website can run, but role verification is still invalid.
related codes
models partial code:
def can(self, permissions):
return self.role is not None and (self.role.permissions & permissions)
== permissions
def is_administrator(self):
return self.can(Permission.ADMINISTER)
def __repr__(self):
return "<User %r>" % self.username
class AnonymousUser(AnonymousUserMixin):
def can(self, permissions):
return False
def is_administrator(self):
return False
login_manager.anonymous_user = AnonymousUser
View function part code:
@main.route("/", methods=["GET", "POST"])
def index():
form = PostForm()
if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
post = Post(body=form.body.data,
author=current_user._get_current_object())
db.session.add(post)
db.session.commit()
return redirect(url_for(".index"))
page = request.args.get("page", 1, type=int)
show_followed = False
if current_user.is_authenticated:
show_followed = bool(request.cookies.get("show_followed", ""))
if show_followed:
query = current_user.followed_posts
else:
query = Post.query
pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config["FLASKY_POSTS_PER_PAGE"],error_out=False)
posts = pagination.items
return render_template("index.html", form=form, posts=posts, show_followed=show_followed, pagination=pagination,current_time=dateti
Test part of the code (the test can pass):
def test_user_role(self):
u = User(email="john@example.com", password="cat")
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE_ARTICLES))
flask appears AttributeError: "AnonymousUserMixin" object has no attribute" can"
when running without logging in to the home page. If you log in to u.can ()
the role verification function fails, there is the following code in the home page:
{% if current_user.can(Permission.WRITE) %}{{ wtf.quick_form(form) }}{% endif %}
but it didn"t work