2

我正在关注这里的示例代码:http: //flask.pocoo.org/docs/views/#pluggable-views

我不认为这段代码是完整的,我无法让它工作并建立在它之上。

我正在尝试为以下功能重用代码:

添加数据库条目

@app.route('/add/category/', methods=['GET', 'POST'])
def addCategory():
    form = forms.AddCategory()
    if form.validate_on_submit():
        name = form.name.data
        database.addCategory(name)
        return redirect('/view/categories/')
    return render_template('add-category.html', form = form)


@app.route('/add/revision/', methods=['GET', 'POST'])
def addRevision():
    form = forms.AddRevision()
    if form.validate_on_submit():
        name = form.name.data
        version = form.version.data
        database.addRevision(name, version)
        return redirect('/view/revisions/')
    return render_template('add-revision.html', form = form)

编辑数据库条目

@app.route('/edit/category/<category>', methods=['GET', 'POST'])
def editCategory(category):
    form = forms.AddCategory()
    form.name.data = category
    if form.validate_on_submit():
        newName = form.name.data
        database.editCategory(name = category, newName = newName)
        #view single category?
        return redirect('/view/categories/')
    return render_template('edit-category.html', category = category, form = form)

@app.route('/edit/revision/<name>/<version>', methods=['GET', 'POST'])
def editRevision(name, version):
    form = forms.AddRevision()
    form.name.data = name
    form.version.data = version
    if form.validate_on_submit():
        newName = form.name.data
        newVersion = form.version.data
        database.editRevision(name, version, newName, newVersion)
        return redirect('/view/revisions/')
    return render_template('edit-revision.html', name = name, version = version, form = form)

这是我当前的代码

class ListView(View):
    def get_template_name(self):
        raise NotImplementedError()
    def render_template(self, context):
        return render_template(self.get_template_name(), **context)
    def dispatch_request(self):
        context = {'objects': self.get_objects()}
        return self.render_template(context)

class CategoryView(ListView):
    def get_template_name(self):
        return 'categories.html'
    def get_objects(self):
        return models.Category.query.all()

app.add_url_rule('/categories', view_func=RenderTemplateView.as_view('categories', template_name='categories.html'))

我在哪里指定在 app.add_url_rule 中使用 CategoryView 类?

4

1 回答 1

2

问题是文档在这两个代码块之间切换上下文-使用的第二组示例RenderTemplateView并不意味着“与”前面的条目草图“一起使用” ListView

app.add_url_rule('/categories', view_func=RenderTemplateView  # ... snip ...

应该:

app.add_url_rule('/categories', view_func=CategoryView.as_view("category"))

这将创建一个函数,该函数在调用时将创建您的实例CategoryView并调用其dispatch_request方法。

于 2013-02-26T02:08:01.720 回答