문제

I am building an app using Web2py framework... I don't want to have to use the request object to get all of the querystring parameters, instead I'd like to build my controller with named parameters and have the router unpack the querystring (or form data) dictionary into the named parameters and call my controller.

so instead of a controller method of

create_user():

where I would use the global request() object and look through the vars list... I would prefer instead to have

create_user(first_name, last_name, email):

like I see in other MVC platforms.

is this possible in Web2py already? or is there a plugin for it? or do I need to add that myself?

도움이 되었습니까?

해결책

No. As stated in the book, an URL of the form

http://127.0.0.1:8000/a/c/f.html/x/y/z?p=1&q=2

maps to application (folder) a, controller (file) c.py, function f, and the additional arguments must be unpacked from the request object as

x, y, z = tuple(request.args)
p = request.vars['p'] # p=1
q = request.vars['q'] # q=2 

Furthermore, web2py specifically detects valid controller functions as those functions that have no arguments. AFAICR, this is opposite to Django which detects valid controller functions as those that have at least one argument.

다른 팁

I do

def create_user():
    try:
        first_name, last_name, email = request.args[:3]
    except:
        redirect('some_error_page')

but mind that first_name, last_name and email may contain chars that are not allowed in the path_info (web2py in picky when validating that only [\w\-\.] are allowed).

There is a circumstance in which web2py controllers can use parameters. When a controller function has the @service decorator, parameters can be used, depending on the service type, for example:

@service.jsonrpc
def somefunction(a=None, b='default'):
    ## whatever

This approach is for when a controller function is really an API, not a way to generate a web view. There are nice things you can do in terms of defining web-view and API-style functions in parallel, and having the web views call the API functions, to ensure you have a good separation of views & controllers.

Depending on how you choose to divide responsibilities among the web client / javascript, the web2py view, and the web2py controller, it can make sense to have controller functions that are truly APIs (with optional parameters) rather than building the parameter-unpacking logic in a web-view style controller.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top