烧瓶教程 - 404找不到 [英] Flask tutorial - 404 Not Found

查看:230
本文介绍了烧瓶教程 - 404找不到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



python flaskr.py



我得到的是 404找不到错误,说:

请求的URL在服务器上找不到。如果您手动输入网址,请检查您的拼写,然后重试。



这里是文件内的代码

  import os 
从flask导入导入sqlite3
烧瓶,请求,会话,g,重定向,url_for,abort,render_template,flash

#create app
app = Flask(__ name__)
app.config.from_object(__ name__)

# 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通用电器t_db():
打开一个新的数据库连接,如果还没有cyrrent应用程序
如果不是hasattr(g,'sqlite_db'):
g.sqlite_db = connect_db()
返回g.sqlite_db

@ app.teardown_appcontext $ b $ def def close_db(error):
在数据库的结尾再次关闭数据库请求。
如果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()。executedcript(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 =条目)

@ app.route('/ add',methods = ['POST'])
def add_entry():
if no t)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 posting posted')
返回重定向(url_for('show_entries'))

@ app.route('/ login',methods = ['GET','POST'])
def login ):
error = None
if request.method =='POST':$ b $如果request.form ['username']!= app.config ['USERNAME']:
错误='无效的用户名'
elif request.form ['password']!= app.config ['PASSWORD']:
error ='密码无效
else:
session ['logged_in'] = True
flash('You logged in')
return redirect(url_for('show_entries'))
return render_template('login.html',error =错误)

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

(加上3次尝试刷新页面):

$ $ $ $ $ p $ $ $ $ $用户@用户:〜/ Flask / flaskr $ python flaskr.py
*在http://127.0.0.1:5000/
上运行*使用重新加载程序
重新启动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.1404 -
127.0.0.1 - - [19 / Aug / 2014 15:23 :42]GET / HTTP / 1.1404 -

有什么可能出错的建议?

解决方案

您将 app.run()太早:

  if __name __ =='__main__':
app.run()

在任何路由注册之前执行编辑。移动这两行到你的文件的 end
$ b 接下来,你有 show_entries() 不正确:

  def show_entries():
db_get_db()

没有 db_gt_db()函数;这应该是 db = get_db()


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

python flaskr.py

what I get is a 404 Not Found error saying

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

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?

解决方案

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

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

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

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

def show_entries():
    db_get_db()

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

这篇关于烧瓶教程 - 404找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆