Restricting an exposed URL to either POST or GET

April 17, 2010
  • forms usually use ‘POST’ by default
  • When you refresh a page that contains a form, then if you found that the page asks you for a confirmation to re-submit the form contents then you know that this’s a form that used ‘POST’ .
  • web2py forms usually use ‘POST’ too.
  • sometimes you need to restrict your actions[controller functions] to either POST/GET methods
  • in web2py you can do something like :

    def index():
        form = FORM(INPUT(_type='submit'), _method='GET')
        if form.accepts(request.get_vars,session):
            response.flash = T('form accepted')
        return dict(form=form)
    

    in your index.html, just do:

    {{=form}}
    
  • Now by submitting form, you get in URL something like :
    http://127.0.0.1/test/default/index?_formkey=43c71638-2dbe-4667-a07c-404999afb4c9&_formname=default
    
  • See the URL ‘this indicates that form is using GET’ since request variables are all sent in URL itself
  • in the form definition up there can you see the :
    _method='GET'
    
  • also when accepting the form we use :
    if form.accepts(request.get_vars)
    

    instead of:

    form.accepts(request.vars)
    
  • The same goes for POST, but it will be trivial to do such a thing since web2py forms usually use POST for submitting forms
  • In fact at any time , if you want to get the function used by a form, you can do
    form = SQLFORM(db.my_table)
    method=form.attributes['_method']
    
  • P.S
    You can use LiveHttpHeader firefox extension while doing your tests