基于Flask的网站中的奇怪AttributeError

时间:2013-12-19 05:03:33

标签: python postgresql sqlalchemy flask

我正在开发一个基于Flask和SQLAlchemy的网站

  1. ss由sqlalchemy.orm中的sessionmaker创建

  2. 动漫,ActorQuote,AnimeComment是基于数据库结构的模型

  3. ```

    @app.route('/page/<anime_name>', methods=['GET', 'POST'])
    def show_page(anime_name):
        if request.method == 'GET':
            anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
            actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
            anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
            return render_template('page.html', anime=anime, actor_lines=actor_quotes, comments=anime_comments)
    

    除了它之外,它会返回一个带有这些参数的页面 - 动漫,actor_quotes,anime_comments,它确实会抛出属性错误。

    ```

    Traceback (most recent call last):
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
        return self.wsgi_app(environ, start_response)
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
        response = self.make_response(self.handle_exception(e))
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
        response = self.full_dispatch_request()
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
        rv = self.dispatch_request()
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/Users/windrunner/hiacg/index.py", line 138, in show_page
        actor_lines = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
    AttributeError: 'NoneType' object has no attribute 'id'
    

    当我使用try-except来捕获错误时,它会抛出另一个UnboundLocalError。

    ```

    try:
        anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
        actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
        anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
    except AttibuteError:
        print 'AttibuteError occurs again!'
    

    更奇怪的是,网站仍然运作良好,没有任何反复发生。

    1. /page/化物语这会显示预期的页面而不会出现错误。

    2. /page/剑风传奇这会按预期显示页面但有错误。

1 个答案:

答案 0 :(得分:3)

在你的行

anime = ss.query(Anime).filter_by(anime_name=anime_name).first()

变量anime如果找不到None(正如您在数据库中所说的那样),那么AttributeError在尝试访问None时就会idanime = Anime.query.filter_by(anime_name=anime_name).first_or_404()

顺便说一句,我建议你使用Flask-SQLAlchemy扩展来解决所有数据库连接逻辑,并公开一些有用的函数,如`.first_or_404'。 有了它,您的代码将成为

{{1}}