一尘不染

为什么我在Flask中遇到404错误?

flask

我是学习Flask的Django开发人员。我对Flask中的工作方式还很陌生。访问时,我得到的404包含以下代码localhost:5000。有人可以解释为什么我得到这个:

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

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////media/workdrive/workspace/purkinje/temp.db'
app.debug = True
db = SQLAlchemy(app)

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

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category', backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title

class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Category %r> % self.name'

@app.route('/')
def index():
    posts = Post().query.all()
    return render_template('templates/index.html', posts=posts)

阅读 636

收藏
2020-04-08

共1个答案

一尘不染

app.run()在注册处理程序之前先打电话。你应该将整个if __name__ == '__main__'块移到脚本的底部。

2020-04-08