500使用Flask和Jinja时出现内部服务器错误



我目前正在使用一本名为《Head First:Python(第二版)》的书自学Python,到目前为止效果不错,但我目前还处于构建一个简单网络应用程序的早期阶段。网络应用程序允许输入短语和字母,然后输出两者的intersection。由于这本书的大部分内容都是基于这一点,所以我不能跳过这一点。我一直试图找出一个错误,但没有用。

所有代码由本书提供,网址为:http://python.itcarlow.ie/ed2/ch05/webapp/

文件夹中的文件vsearch4web.py是最终版本,所以不要使用它。这就是我的vsearch4web.py文件夹所在的位置:

from flask import Flask, render_template
from vsearch import search4letters
app = Flask(__name__)
@app.route('/')
def hello() -> str:
return 'Hello world from Flask!'
@app.route('/search4')
def do_search() -> str:
return str(search4letters('life, the universe, and everything','eiru,!'))
@app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html',the_title='Welcome to search4letters on the web!')
app.run()

我已经按照指示设置了文件夹结构:

webapp文件夹-->vsearch4web.pystatic文件夹(webapp的子文件夹)-->hf.css(来自"static")templates文件夹(webapp的子文件夹)-->base.html、entry.html和results.html(来自"template")

静态文件夹和模板文件夹中的文件可在书中提供的上述URL中下载。

但是,当我运行vsearch4web.py时,我会转到浏览器并输入环回地址(http://127.0.0.1:5000/entry),我得到一个"500内部服务器错误"。

两者http://127.0.0.1:5000/和http://127.0.0.1:5000/search4然而,工作。

我试过多次重新检查代码,但我不知道我遗漏了什么。

有人能帮忙吗?

谢谢。

Python中不需要

-> type语法。

您应该阅读服务器日志以查看def entry_page()的定义是否正确。

使用正确类型的render_template(我认为是Response),或者只是将其删除

从同一本书中学习。。。我也为此纠结了一两天。我的问题是,我用.html命名了模板,但它们保存为文本而不是html文件。要解决此问题,请打开模板,转到"另存为…"并检查下拉菜单,看看它是显示文本还是html——如果是文本,请切换到html,然后重新保存。

以下行导致问题:

def entry_page() -> 'html':

使用注释(->)仅适用于Python类型和派生类型(如strdictintfloat等)。

事实上,您甚至不必在Python:中使用注释

@app.route('/entry')
def entry_page():
return render_template('entry.html',the_title='Welcome to search4letters on the web!')

render_template返回的Response对象将具有正确的"类型",这是由响应标头中的Content-Type: text/html; charset=utf-8决定的(而不是由路由的返回值决定的)。

最新更新