web-dev-qa-db-ja.com

Flaskチュートリアル-404が見つかりません

Flask基本チュートリアル( こちら )を終了しました。すべてのステップを完了したにもかかわらず、

python flaskr.py

私が得るものは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.

これがファイル内のコードです

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'))

これは私が受け取るコンソールメッセージです(さらに、ページを更新するための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 -

何がうまくいかないのかについての提案はありますか?

11
user3725561

あなたはapp.run()コールを入れます早すぎる

_if __name__== '__main__':
    app.run()
_

これは、ルートが登録される前に実行されます。これらの2行をファイルのendに移動します。

次に、show_entries()の最初の行が間違っています:

_def show_entries():
    db_get_db()
_

db_get_db()関数はありません。代わりに、これはdb = get_db()である必要があります。

20
Martijn Pieters

Flask Application Setup here )を実行しているときにも、ルートの最後にスラッシュを追加するとエラーが発生しました。

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

に変更されました

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

そして問題は解決されました。このような問題を探している人にとって役立つことを願っています。