2017-12-02 305 views
0

我仍在努力將Python中的字符串傳遞給另一個函數。Python瓶沒有返回cookie/ValueError:查看功能沒有返回響應

我試圖按照這裏給出的例子:https://www.tutorialspoint.com/flask/flask_cookies.htm

我已經試過落實到我的代碼,這但現在我得到以下回溯:

Traceback (most recent call last): 
    File "/Users/marcel/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app 
    response = self.full_dispatch_request() 
    File "/Users/marcel/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1615, in full_dispatch_request 
    return self.finalize_request(rv) 
    File "/Users/marcel/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1630, in finalize_request 
    response = self.make_response(rv) 
    File "/Users/marcel/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1725, in make_response 
    raise ValueError('View function did not return a response') 
ValueError: View function did not return a response 

這將意味着我我沒有返回任何東西,但我真的不知道我要去哪裏錯了,我不得不承認我很迷茫。

我完整的代碼看起來是這樣的:

from __future__ import print_function 
import tensorflow as tf 
import argparse 
import os 
from six.moves import cPickle 
from model import Model 
from six import text_type 
import flask 
from flask import jsonify, render_template, request, make_response 

app = flask.Flask(__name__) 


@app.route('/') 
def index(): 
    return render_template('index.html') 

@app.route('/test') 
def tester(): 
    return "This is a test" 

@app.route('/', methods = ['POST', 'GET']) 
def main(): 
    if request.method == 'POST': 
     parser = argparse.ArgumentParser(
          formatter_class=argparse.ArgumentDefaultsHelpFormatter) 
     parser.add_argument('--save_dir', type=str, default='save', 
          help='model directory to store checkpointed models') 
     parser.add_argument('-n', type=int, default=500, 
          help='number of characters to sample') 
     parser.add_argument('--prime', type=text_type, default=u' ', 
          help='prime text') 
     parser.add_argument('--sample', type=int, default=1, 
          help='0 to use max at each timestep, 1 to sample at ' 
           'each timestep, 2 to sample on spaces') 

     args = parser.parse_args() 

     resp = make_response(render_template('sample.html')) 
     resp.set_cookie('args', args) 

     return resp 


@app.route('/sampler', methods = ['POST', 'GET']) 
def sample(): 
    args = request.cookies.get('args') 
    with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f: 
     saved_args = cPickle.load(f) 
    with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f: 
     chars, vocab = cPickle.load(f) 
    model = Model(saved_args, training=False) 
    with tf.Session() as sess: 
     tf.global_variables_initializer().run() 
     saver = tf.train.Saver(tf.global_variables()) 
     ckpt = tf.train.get_checkpoint_state(args.save_dir) 
     if ckpt and ckpt.model_checkpoint_path: 
      saver.restore(sess, ckpt.model_checkpoint_path) 
      if request.method == 'POST': 
       text = model.sample(sess, chars, vocab, args.n, args.prime, 
            args.sample).encode('utf-8') 
       resp = make_response(render_template('text.html')) 
       resp.set_cookie('verse', text) 
       return resp 


@app.route('/text') 
def printer():  
    verse = request.cookies.get('verse') 
    return verse 


@app.errorhandler(404) 
def page_not_found(error): 
    return render_template('404.html'), 404 

if __name__ == '__main__': 
    main() 

之前,我曾試圖剛剛從我的樣本功能打印機功能發送Cookie,但它返回相同的錯誤。

我的代碼之前:

def sample(args): 
    with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f: 
     saved_args = cPickle.load(f) 
    with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f: 
     chars, vocab = cPickle.load(f) 
    model = Model(saved_args, training=False) 
    with tf.Session() as sess: 
     tf.global_variables_initializer().run() 
     saver = tf.train.Saver(tf.global_variables()) 
     ckpt = tf.train.get_checkpoint_state(args.save_dir) 
     if ckpt and ckpt.model_checkpoint_path: 
      saver.restore(sess, ckpt.model_checkpoint_path) 
      text = model.sample(sess, chars, vocab, args.n, args.prime, 
           args.sample).encode('utf-8') 
      resp = make_response(render_template('text.html')) 
      resp.set_cookie('verse', text) 
      return resp 


@app.route('/text') 
def printer():  
    verse = request.cookies.get('verse') 
    return verse 
+0

而不僅僅是錯誤消息,請發佈完整的回溯。此外,什麼時候發生這種錯誤 - 什麼端點和你正在做什麼樣的請求?謝謝。 – alecxe

+0

剛編輯完整的Traceback。當我嘗試打開http://127.0.0.1:5000/text時會發生這種情況。我得到一個內部服務器錯誤和上面的回溯。 – Marcel

+0

視圖函數必須在所有情況下返回有效的響應值。您顯示的代碼中的多個視圖都有返回「None」的路徑。 – davidism

回答

0

verse cookie的值不存在的價值verse變量將變爲None。這意味着您的text視圖將返回None,其中Flask不喜歡並理解爲「視圖函數未返回響應」。

您可能需要妥善處理這種情況下 - 例如,簡單地返回一個空字符串會解決這個問題(當然,這只是一個樣本簡單的解決方法來證明的差異):

@app.route('/text') 
def printer():  
    return request.cookies.get('verse', '') 

而且,並非sample()視圖中的所有代碼路徑都會返回有效的響應 - 請確保解決該問題(例如,向sample()視圖發出GET請求會導致相同的「視圖函數未返回響應」錯誤) 。

0

main,你將需要外部的請求參數校驗範圍返回值:

@app.route('/', methods = ['POST', 'GET']) 
def main(): 
    if request.method == 'POST': 
     parser = argparse.ArgumentParser(
     ....#statements follow    
     args = parser.parse_args() 

     resp = make_response(render_template('sample.html')) 
     resp.set_cookie('args', args) 

     return resp 
    return render_template('home.html') #need to return something here