简体   繁体   English

peewee.OperationalError:在“ AS”附近:语法错误

[英]peewee.OperationalError: near “AS”: syntax error

So I don't quite understand what exactly the problem here is. 所以我不太明白这里到底是什么问题。 I'm working with python-flask and currently trying to call certain posts from my Post model. 我正在使用python-flask,目前正在尝试从我的Post模型调用某些帖子。 However, I always get this "peewee.OperationalError: near "AS": syntax error" error message which is caused by the following class method in my User model: 但是,我总是收到此“ peewee.OperationalError:在“ AS”附近:语法错误”的错误消息,这是由我的用户模型中的以下类方法引起的:

    @classmethod 
    def get_stream(self):
        return Post.select().where(Post.user == self)

I call this method in the following route to define stream, which is then passed to the template: 我在以下路由中调用此方法以定义流,然后将其传递到模板:

@app.route('/stream')
@app.route('/stream/<username>')
def stream(username=None):
    template = 'stream.html'
    if username and username != current_user.username:
        user = social.User.select().where(social.User.username**username).get()
        stream = user.posts.limit(100)
    else:
        stream = current_user.get_stream().limit(100)
        user = current_user
    if username:
        template = "user_stream.html"
#   stream = social.Post.select().where(social.Post.user == current_user.id)
    return render_template(template, stream=stream, user=user)

Using the line that is currently commented it works just fine, but without it I get the error. 使用当前被注释的行可以正常工作,但是没有它我得到了错误。 So it is for sure a problem 所以可以肯定的是有问题

Anyone an idea what the issue is? 任何人都知道问题是什么吗?

For reference, here are the User and Post models: 作为参考,以下是User和Post模型:

class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = USER_DB
        order_by = ('joined_at',)

    @classmethod 
    def get_stream(self):
        return Post.select().where(Post.user == self)

    @classmethod
    def create_user(cls, username, email, password, admin=False):
        try:
            with USER_DB.transaction():
                cls.create(
                    username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
        except IntegrityError:
            raise ValueError("User already exists.")


class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
        )
    content = TextField()

    class Meta:
        database = USER_DB
        order_by = ('-timestamp',)

Traceback (most recent call last) 追溯(最近一次通话)

File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/SuperMario/Desktop/treehouse/flask_track/simple_app.py", line 49, in stream
return render_template(template, stream=stream, user=user)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/templating.py", line 128, in render_template
context, ctx.app)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/flask/templating.py", line 110, in _render
rv = template.render(context)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/Users/SuperMario/Desktop/treehouse/flask_track/templates/user_stream.html", line 1, in top-level template code
{% extends "stream.html" %}
File "/Users/SuperMario/Desktop/treehouse/flask_track/templates/stream.html", line 1, in top-level template code
{% extends "layout.html" %}
File "/Users/SuperMario/Desktop/treehouse/flask_track/templates/layout.html", line 25, in top-level template code
{% block content %}     {% endblock %}
File "/Users/SuperMario/Desktop/treehouse/flask_track/templates/user_stream.html", line 26, in block "content"
{{ super() }}
File "/Users/SuperMario/Desktop/treehouse/flask_track/templates/stream.html", line 5, in block "content"
{% for post in stream %}
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 2866, in __iter__
return iter(self.execute())
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 2859, in execute
self._qr = ResultWrapper(model_class, self._execute(), query_meta)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 2555, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 3366, in execute_sql
Open an interactive python shell in this frameself.commit()
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 3212, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 125, in reraise
raise value.with_traceback(tb)
File "/Users/SuperMario/Desktop/treehouse/treehouse_flask_track/lib/python3.4/site-packages/peewee.py", line 3359, in execute_sql
cursor.execute(sql, params or ())

Decorating a method with @classmethod tells Python to pass the class rather than the instance as the first argument. @classmethod装饰方法告诉Python将类而不是实例作为第一个参数。 Typically, you name the first argument cls in that case to keep things clear. 通常,在这种情况下,您将第一个参数命名为cls以使情况保持清楚。

Your method is trying to get all Post s with the user instance it's called from, but instead calling that method passes the User class. 您的方法尝试获取具有调用它的用户实例的所有Post ,但是调用该方法将传递User类。 Remove the @classmethod decorator. 删除@classmethod装饰器。

def get_stream(self):
    return Post.select().where(Post.user == self)

Now self is a user instance, and the relation Post.user == self makes sense. 现在self是一个用户实例,关系Post.user == self很有意义。

The @classmethod before defining the method in my User model prevented it from working. 在我的User模型中定义方法之前, @classmethod阻止了该方法工作。 I still have to figure out why, but for now it works. 我仍然必须弄清楚为什么,但是现在可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM