Python Flask 教程 - 404 Not Found

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25383187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:08:28  来源:igfitidea点击:

Flask tutorial - 404 Not Found

pythonpython-2.7flaskhttp-status-code-404

提问by

I just finished the Flask basic tutorial (here) and even though I've done completed every step, when I am trying

我刚刚完成了 Flask 基础教程(这里),即使我已经完成了每一步,当我尝试

python flaskr.py

python flaskr.py

what I get is a 404 Not Founderror saying

我得到的是一个404 Not Found错误说

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

here is the code inside the file

这是文件中的代码

import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash

#create app
app = Flask(__name__)
app.config.from_object(__name__)

#load default conf and override config from an env var
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.db'),
    DEBUG=True,
    SECRET_KEY = 'dev key',
    USERNAME = 'admin',
    PASSWORD = 'admin'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def connect_db():
    """connect to the specific db"""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

if __name__== '__main__':
    app.run()


def get_db():
    """opens a new db connection if there is none yet for the cyrrent app"""
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
        return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    """closes the db again at the end of the request."""
if hasattr(g, 'sqlite_db'):
    g.sqlite_db.close()

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()


@app.route('/')
def show_entries():
    db_get_db()
    cur = db.execute('select title, text from entries order by id desc')
    entries = cur.fetchall()
    return render_template('show_entries.html', entries=entries)

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    db = get_db()
    db.execute('insert into entries (title, text) values (?,?)',
        [request.form['title'], request.form['text']])
    db.commit()
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

This is the console message I get (plus 3 attempts to refresh page):

这是我得到的控制台消息(加上 3 次刷新页面的尝试):

user@user:~/Flask/flaskr$ python flaskr.py
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader
127.0.0.1 - - [19/Aug/2014 15:23:40] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Aug/2014 15:23:41] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Aug/2014 15:23:42] "GET / HTTP/1.1" 404 -

Any suggestions on what might be going wrong?

关于可能出什么问题的任何建议?

采纳答案by Martijn Pieters

You put your app.run()call too early:

太早app.run()打电话

if __name__== '__main__':
    app.run()

This is executed before any of your routes are registered. Move these two lines to the endof your file.

这是在注册任何路由之前执行的。将这两行移到文件的末尾

Next, you have the first line in show_entries()is incorrect:

接下来,您输入的第一行show_entries()不正确:

def show_entries():
    db_get_db()

There is no db_get_db()function; this should be db = get_db()instead.

没有db_get_db()功能;这应该是db = get_db()

回答by Salman Haseeb Sheikh

Happened to me also while following Flask Application Setup here. The error was gone after appending a trailing slash at the end of the route.

在此处遵循 Flask 应用程序设置时也发生在我身上。在路径末尾附加斜杠后,错误消失了。

@app.route('/hello')
    def hello():
        return 'Hello, World!'

was changed to

改为

@app.route('/hello/')
    def hello():
        return 'Hello, World!'

and the problem was solved. Hope it helps for anyone who is searching for a problem like this.

问题就解决了。希望它对任何正在寻找此类问题的人有所帮助。