繁体   English   中英

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

[英]500 Internal Server Error When Using Flask and Jinja

我目前正在使用一本名为《 Head First:Python(第二版)》的书来自学Python,到目前为止,它还不错,但是我目前仍停留在构建简单Web应用程序的早期阶段。 Webapp允许一个人输入短语和字母,然后输出两者的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.py静态文件夹(webapp的子文件夹)-> hf.css(来自“静态”)模板文件夹(webapp的子文件夹)-> base.html,entry.html和results.html(来自“模板”)

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

但是,当我运行vsearch4web.py并进入浏览器并输入回送地址( http://127.0.0.1:5000/entry )时,出现“ 500 Internal Server Error”。

但是, http: //127.0.0.1:5000/http://127.0.0.1:5000/search4都可以工作。

我已经尝试过多次检查代码,但是我不知道自己缺少什么。

有人可以帮忙吗?

谢谢。

-> type 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确定Content-Type: text/html; charset=utf-8 响应标头中的Content-Type: text/html; charset=utf-8 (而不是路由的返回值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM