2013-12-19 51 views
0

我正在開發基於瓶和SQLAlchemy的網站奇怪AttributeError的基於網站

  1. ss由sessionmaker創造sqlalchemy.orm

  2. 動漫,ActorQuote,AnimeComment是基於數據庫模型結構

```

@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 - 除了捕獲錯誤,它會引發另一UnboundLocalError。

```

什麼是更奇怪的是該網站仍然有效,以及什麼都沒有發生。

  1. /page/化物語這顯示了預期沒有錯誤的頁面。

  2. /page/劍風傳奇這顯示了預期的頁面,但有錯誤。

+0

你可以在你的except塊內顯示代碼嗎? – aIKid

+0

@alKid我已經添加了try-except從句,還有Tracebck msg。 – kxxoling

回答

3

在你行

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

變量animeNone,如果試圖訪問None時未找到(如你在數據庫空說的),因此AttributeErrorid

順便說一句我建議你使用Flask-SQLAlchemy擴展處理所有的數據庫連接邏輯,並公開一些有用的函數,如`.first_or_404'。 有了它,你的代碼就會變成

anime = Anime.query.filter_by(anime_name=anime_name).first_or_404() 
+0

對不起,誤導你,我的意思是說actor_quotes表是空的,而不是整個分貝。我可以確認它不是由空表引起的,至少不僅是:case1:表anime_comments和actor_quotes是空的,但它沒有錯誤地工作(http://i.imgur.com/CvKry0O.png)。 case2:與case1幾乎相同,它會導致錯誤,但正常頁面如預期。 – kxxoling

+1

@kxxoling ok,但爲了拋出該錯誤(NoneType沒有屬性),唯一的解釋是'anime'對象是'None'。當查詢找不到記錄時,就會發生這種情況。無論出於何種原因:) –

+0

是的,這是最奇怪的地方,因爲頁面總是呈現成功,所以動漫對象可以是空的。我想這些線可能會執行兩次,第一次一切都好,第二次一切都是空的。 – kxxoling