我正在关注此处的示例代码: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类?
答案 0 :(得分:2)
问题是文档在这两个代码块之间切换上下文 - 使用RenderTemplateView
的第二组示例并不意味着“使用”前面的条目草图ListView
。
app.add_url_rule('/categories', view_func=RenderTemplateView # ... snip ...
应该是:
app.add_url_rule('/categories', view_func=CategoryView.as_view("category"))
调用后creates a function会创建CategoryView
的实例并调用其dispatch_request
方法。