我试图在一个名为poemBot.py的文件中显示python函数输出的一些数据,并使用一个简单的flask应用程序在网页中显示该输出。这里是到github repo的链接:https://github.com/nditanaka/flask_poembot_app我的路由设置如下:
import time
from flask import Flask, request, render_template, jsonify
from poemBot import tap
app = Flask(__name__)
@app.route('/')
def hello():
return tap()
@app.route('/time')
def get_current_time():
return {'time': time.time()}
@app.route('/api/about')
def about():
return 'This is the about page'
@app.route('/api/poem')
def get_random_poem():
return tap()
调用tap()函数的poemBot文件如下所示:
#!/usr/bin/python
# main.py
from __future__ import print_function
import subprocess
import time
import socket
import csv
import textwrap
import random
def printPoem():
# get a random poem
randPoem = random.choice(allPoems)
# nicely wrap the content for the printer
# Title and Author are printed in 'M' medium font, limit is 32 character per line
# poem is printed in 'S' small font, limit is 32 characters per line
# book and publisher are in "fontB", limit is 42 character per line
wrappedTitle = textwrap.fill(randPoem[1], width=32)
wrappedAuthor = textwrap.fill(randPoem[2], width=32)
wrappedPoem = ""
for line in randPoem[3].splitlines():
wrappedLine = textwrap.fill(line, width=32, subsequent_indent=" ")
wrappedPoem += wrappedLine + "\n"
# print the poem
# return (wrappedTitle, '\n', wrappedPoem, '\n',
# wrappedAuthor, '\n', randPoem[4], '\n', randPoem[0])
years = str(randPoem[4])
author = str(wrappedTitle)
poem = wrappedAuthor
url = str(randPoem[3])
return {author, poem, years, url}
# Print random poem, called on tap
def tap():
# print a random poem
return printPoem()
def hold():
return ('Goodbye!')
# Load up all poems from CSV
# poem CSV is structured with the columns: number,title,author,poem,book
# goldenTreasuryPoems.csv was parsed from the text of Project Gutenberg EBook #19221
# http://www.gutenberg.org/ebooks/19221
# the poem column contains the full text of the poem with no markup, only \n
# the CSV is in PC437 encoding since the printer only supports this character set
with open('poembot_poems_2020.csv') as csvPoems:
allPoems = list(csv.reader(csvPoems, delimiter=','))
# Start printing
print('Hello!')
print('Ready to print')
tap()
poemBot.py文件的工作原理是读取csv文件,然后通过printpoom()函数输出该文件的内容。我怀疑我的printpooth()返回了错误类型的对象,或者我在main.py中的routes中调用tap()的方式是错误的
当我使用flask run运行flask应用程序时,得到的错误是
"The view function did not return a valid response. The" TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
编辑:修改了文件,现在的错误是:
TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).
您的代码中有许多内容需要更改:
1)创建路由函数时,它必须返回渲染模板对象或字符串。 应该是这样的:
2)如果知道将导入文件,则应使用“名称””变量:
3)使用逗号“”返回值时,它将类型转换为元组。如果希望它是字符串,则必须使用操作数“+”
希望对你有帮助
相关问题 更多 >
编程相关推荐