簡體   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