0

はじめまして。
現在以下の記事を参考に、Flaskを用いてinstagramユーザーの性別を推定しようと試みているのですが、エラーが出てしまいます。
http://codezine.jp/article/detail/8953

#エラー文
Traceback (most recent call last)
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/Users/Ryosuke/anaconda/lib/python3.5/site-packages/flask/app.py", line 1566, in make_response
raise ValueError('View function did not return a response')
ValueError: View function did not return a response

実際過去に私と同じようなエラーを発生している事例( https://stackoverflow.com/questions/25034123/flask-value-error-view-function-did-not-return-a-response )を見つけ、関数の最後にreturnを明示しなければならないことは分かったのですが、今回のコードではどこにreturnを明記してやればいいのか分かりません。

今回の場合、以下main.pyのどこにreturnを明記してやればよいでしょうか?
是非ともご教示のほどよろしくお願い致します。

#main.py
import os
from flask import Flask, render_template, request
from settings import instgram_access_token
from api import InstagramAPI
import pandas as pd
from sklearn.externals import joblib

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    try:
        if request.method == 'POST': # POST応答
            if request.form['message'] == '': #例外処理:ユーザー名未入力時
                message = "Please input your Instagram User name in the box"
                return render_template('index.html', title="Your gender?", method=request.method, message=message)
            else:
                message = "Your Instagram data"
                insta = InstagramAPI(access_token=instgram_access_token)
                user_name = request.form['message'] # ユーザー名を変数に代入
                user_id = insta.user_id(user_name=user_name) # ユーザー名からユーザーIDを取得
                profile_image = insta.profile_image(user_id) # プロフィール画像を取得
                user = {'user_name': user_name, 'user_id': user_id, 'image': profile_image} # ユーザー情報をまとめる
                user_summary = insta.user_info(user=user)
                # 特徴量ベクトルの整理
                test = {'nail': 0, 'hair': 0, 'person': 0, 'sport': 0, 'food': 0, 'night': 0, 'coffee': 0,
                        'wedding': 0, 'cake': 0, 'beer': 0, 'dog': 0, 'animal': 0, 'tree': 0, 'blossom': 0,
                        'cat': 0, 'flower': 0, 'sky': 0, 'nature': 0, 'cherry': 0, "user_name": "test", "user_id": "test"}
                X = pd.DataFrame([user_summary, test]).fillna(0)
                X['animal'] = X['animal']+X['dog']+X['cat']
                X['cosme'] = X['hair']+X['nail']
                X['nature'] = X['nature']+X['sky']+X['flower']+X['tree']+X['blossom']+X['cherry']
                X = X[X['user_name'] == user_name]
                X = X[['person', 'sport', 'food', 'night', 'coffee', 'wedding', 'cake', 'beer', 'animal', 'nature', 'cosme']]
                user_vec = X.values.tolist()[0]

                model_path = os.path.join(os.path.dirname(__file__), "clf/clf.pkl")
                clf = joblib.load(model_path) # 識別器の読み込み
                result = clf.predict(user_vec) # 性別推定

                return render_template('index.html', title="Your gender?", method=request.method, userinfo=user_summary, result=result, message=message)
        else: # GET応答
            return render_template('index.html', title="Your gender?", method=request.method)

    except Exception as e:
        print(e)


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(debug=True, port=port, host='IPアドレス省略')

(参考)
全体のソースコードは以下になります。
https://github.com/yiori-s/fit_instagram_gender/tree/codezine

1 件の回答 1

1

try句のどこかで例外が発生して、except句に処理が移った場合にreturnされていないのが原因でしょう。except句、またはtry/exceptから抜けた後でResponseオブジェクトをreturnする必要がありそうです。

try句が長すぎてどこでエラーが起きているのか分からなくなっているのが一番の問題です。try/except を削除してください。途中でエラーとなるのであれば、そのエラーが起きないように実装する必要があります。

3
  • ご回答ありがとうございます! try/exceptを外し、なおかつprint(result)をした結果、 {'error_message': 'The access_token provided is invalid.', 'code': 400, 'error_type': 'OAuthAccessTokenException'} というエラーのJSONが出て来ました。 "api.instagram.com/v1/users/search?q=ユーザーID省略&access_token=省略"単体でリダイレクトし‌​た場合は正常なJSONデータが返ってくるのですが(> <)汗
    – shinob
    2016年4月28日 7:52
  • とりあえず前進した感じですね。新しく出てきた課題が解決できなそうであれば、また別の質問を投稿されると良いかと思います。 2016年4月28日 8:37
  • ありがとうございます! ja.stackoverflow.com/questions/24410/… こちらに新しい質問を投稿していますので、お時間あれば是非覗いてやってくださいm(_ _)m
    – shinob
    2016年4月28日 11:10

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。