BigBoy1337
BigBoy1337

Reputation: 4973

Why do I have to include a return statement in my pyramid view callable?

I am trying to form the view callable for the home page of my pyramid application and am reading about the view callables here: http://docs.pylonsproject.org/projects/pyramid/en/1.0-branch/narr/views.html

But it seems like you always have to have a return statment at the end. I don't understand this. I don't want the view callable to return anything. If I was going to write it in english (not python code) I would put

@view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
    if 'form.submitted' in request.params:
        name= request.params['name']
        body = request.params['body']
        page=Page(name,body)
        DBSession.add(page)
        return HTTPFound(Location=request.route_url('view_page',pagename=name))
    return {the edit.pt template i mentioned in the first line}

but it doesn't seem like there is any way to do this. I have to return a string, or a dictionary, or something. How can i tell this to python. So if people submit that form, then return that HTTPFound statement, but if they don't just render the edit template.

Upvotes: 0

Views: 653

Answers (1)

Raj
Raj

Reputation: 1551

Firstly, use the latest Pyramid docs version (for Pyramid version 1.4) http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/views.html (since I assume you are using the latest Pyramid version).

As for the return statement, you usually return a dictionary, even if it's empty, because your Chameleon template file (edit.pt) is expecting it. @view_config(renderer='templates/edit.pt') tells the function on the next line to pass the dictionary to edit.pt, so the templating engine can replace the variables within the template.

HTTPFound(), on the other hand, bypasses the template (renderer argument of @view_config() is ignored, i.e. no template is used) and does an internal redirect to another route that your __init__.py will dictate. Now whether that new route uses a template/renderer in its @view_config is independent from the previous function that skipped the renderer.

Your return statement on the last line should be return {} if there are no variables in the template that you want filled.

Please let me know how I can make this even more clear for you, if needed.

Upvotes: 5

Related Questions