控制器如何在web2py中工作?

ash*_*him 1 python web2py

我有一个关于控制器和表单如何在web2py中工作的问题.考虑下一个控制器功能(来自we2py book):

def display_form():
form=FORM('Your name:',
          INPUT(_name='name', requires=IS_NOT_EMPTY()),
          INPUT(_type='submit'))
if form.accepts(request,session):
    response.flash = 'form accepted'
elif form.errors:
    response.flash = 'form has errors'
else:
    response.flash = 'please fill the form'
return dict(form=form)
Run Code Online (Sandbox Code Playgroud)

这个功能有两个目标:第一个是返回一个表单,第二个是告诉在提交按钮上做什么.我无法理解它是如何可能的.被叫两次吗?第一次视图需要知道什么是形式,第二次按下提交按钮时?直观地说这件作品:

if form.accepts(request,session):
    response.flash = 'form accepted'
elif form.errors:
    response.flash = 'form has errors'
else:
    response.flash = 'please fill the form'
Run Code Online (Sandbox Code Playgroud)

应该是一些负责后期处理的不同功能.

它是如何工作的?

Ant*_*ony 5

是的,该函数被调用两次.如果在未发布任何表单值的情况下调用该函数的URL,则该form.accepts()函数将失败(即返回False),因为尚未提交任何数据.在这种情况下,返回的所有内容都是新的空白表单.当用户最终提交表单时,表单值将发布到同一个函数中.在这种情况下,form.accepts()查找已发布的表单数据request.post_vars.然后验证数据,如果验证通过,则返回True并response.flash设置为'form accepted'.

这被称为回发或自我提交.如需更多信息,请参见这里.