Search code examples
pythonpyramid

python pyramid, render user dashboard at root url when logged in


How is it possible within a pyramid app to render a logged in users dashboard at the root url? When not logged in the root url shows a sign in form.

After searching I've only found examples for other frameworks.


Solution

  • You can simply do:

    @view_config(route_name='home', renderer='dashboard.jinja2')
    def home_view(request):
        if request.authenticated_userid is None:
            # most people would probably opt to redirect to the login url
            # here instead of rendering a response, but you asked
            return render_to_response('login.jinja2', {}, request=request)
        # user is logged in, so use the dashboard renderer
        return {}
    

    HOWEVER, pyramid is cool and has predicates. Neat. So we can use the effective_principals predicate to dispatch between 2 different views based on whether the user is logged in:

    from pyramid.security import Authenticated
    
    @view_config(route_name='home', effective_principals=Authenticated, renderer='dashboard.jinja2')
    def dashboard_view(request):
        return {}
    
    @view_config(route_name='home', renderer='login.jinja2')
    def login_from_home_view(request):
        return {}