pythonformsroutespyramiddeform

using query string in Python Pyramid route configuration


this is very specific to what I am trying to do so I start describing what it is:

I figured out all the pieces like rendering using Matplotlib etc. but I am new to Pyramid and Deform. I also have a working view that serves the plot from file. The deform form kind of works, too. At the moment it is unclear to me how to best structure the ULRs to distinguish the serve, edit and render usecases. I guess in Pyramid talk this means how to configure the routes for serve_view and edit_view.

__init__.py:
    config.add_route('serve_route', 
        '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
    config.add_route('edit_route', 
        '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
# can I use query strings like "?action=edit" here to distinguish the difference?


views.py:
@view_config(context=Root, route_name='serve_route')
def plot_view(context, request):
... 
@view_config(context=Root, renderer='bunseki:templates/form.pt', route_name='edit_route')
def edit_view(request):
...

I the Pyramid manual I could not find reference how to set parameters in the route. I guess a pointer to some documentation or sample would be sufficient and I can figure out the details myself. Thank you!


Solution

  • There are two ways to do this depending on what you prefer for separating your code.

    1. Put all of the logic into your view, separated by 'if' statements on request.GET.get('action').

      config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
      config.scan()
      
      @view_config(route_name='plot')
      def plot_view(request):
          action = request.GET('action')
          if action == 'edit':
              # do something
              return render_to_response('bunseki:templates/form.pt', {}, request)
      
          # return the png
      
    2. Register multiple views and delegate between them using Pyramid's view lookup mechanics.

      config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
      config.scan()
      
      @view_config(route_name='plot')
      def plot_image_view(request):
          # return the plot image
      
      @view_config(route_name='plot', request_param='action=edit',
                   renderer='bunseki:templates/form.pt')
      def edit_plot_view(request):
          # edit the plot
          return {}
      
      # etc..
      

    Hope this helps. It's an excellent example of registering a single url pattern, and using different views for different types of requests on that url.