0
I Use This!
Activity Not Available

Project Summary

The APDecorator class, and helpers, for processing arguments to views.

The APDecorator class is a general abstraction which allows the arguments to view functions to be altered before the view is called. Usually, due to the way Django handles its URLs, arguments parsed out via the URLconfs are passed as-is (as unaltered strings) to the view functions, whose job it then is to manipulate them (i.e. converting object ids to integers so they may be used to look up primary keys). APDecorator instances, and their enclosed APs, may be used to take some of the boilerplate code away from this. 'AP' here stands for 'Argument Processor', as the job of these functions is to process the arguments to Django view functions.

Usage of APDecorator may be summed up in the following three steps:

Define your argument processors (APs). These are functions which should accept a variable number of positional and keyword arguments, and return a two-tuple of the altered positional and keyword arguments respectively. For example:

def id_to_int(*args, **kwargs):
p_kwargs = kwargs.copy()
if 'id' in p_kwargs:
p_kwargs['id'] = int(p_kwargs['id'])
return args, p_kwargs Define your APDecorator instance, using an ordered sequence of APs. For example: ap_decorator = APDecorator(
id_to_int,
some_other_ap,
...
)Use this instance as a decorator for your Django view function. For example: @ap_decorator
def my_view(request, id=None):
# do something here
...This module includes two validation functions which validate both a single AP and a set of APs. validate_processor and validate_processors may be given one and a sequence of APs respectively, and will return None if they are valid, and will raise an error otherwise.

Also provided is a decorator function, no_request. This should be used on APs, not views, and will replace the APs with a wrapper function (with the same name and docstring) which will carry out the task of stripping the HTTP request from the positional arguments given to the AP, and then prepend it to the returned arguments afterwards.

An example use case for no_request is when you don't want your AP to alter the request object. Such alterations are preferably kept to Django middleware, and so an AP will want to restrict itself to altering the other positional and keyword arguments only. Say, for example, you wished to convert all positional arguments to integers. If we call int() on the request, an error will be raised. But, this means we need to separate the request out from the other positional arguments, and put it back on afterwards. no_request handles this for you. Without no_request, the function would look somewhat like this (boilerplate code is marked by a comment):

def args_to_ints(*args, **kwargs):
request, x_args = args[0], args[1:] # Boilerplate
x_args = map(int, x_args)
x_args = tuple([request] + x_args) # Boilerplate
return x_args, kwargsWith no_request, it looks like this::

@no_request
def args_to_ints(*args, **kwargs):
return tuple(map(int, args)), kwargsThe function therefore becomes a simple line of code. In addition, when the function is called without a request as its first argument, then all arguments are passed as normal, again removing some of the boilerplate and stress from writing APs. For more information on using no_request, consult its docstring and source code.

Two AP factory functions are provided in this module. pos_filter is an AP factory which accepts a list index and a function as arguments (along with an optional name for the returned AP). An AP is returned which, when passed some positional arguments, tries (if there are enough) to replace the value at the specified index with the result of calling the function on the value at that index. The returned AP is also wrapped with no_request, meaning the request object is not modifiable, and that the 0th index is actually the first positional argument after the request.

An example use case for pos_filter could be coercing a string into an integer. This would be done like this:

arg_to_int = pos_filter(0, int, name='arg_to_int')By using int as the filter function, it will be called on a string (which might be specified in the URLconf as something like r'^([\d]+)/$') and should try to return an integer.

kw_filter is very similar in operation to pos_filter, only it accepts a keyword instead of a list index, and manipulates the keyword arguments passed through it. Let's assume that the URLconf looks like this:

urlpatterns = patterns('',
...
(r'^(?P [\d]+)/$', my_app.my_view),
...
)Here, named groups are used in the URLconf, which means the integer will be passed to my_view as a keyword argument (i.e. my_view(id=...)). In order to achieve the same as the previous pos_filter example, one would create an AP like this:

arg_to_int = kw_filter('id', int, name='arg_to_int')As you can see, the index 0 has been replaced by the string 'id', and kw_filter is used instead of pos_filter.

As with all other APs, the functions returned by pos_filter and kw_filter may be grouped sequentially into APDecorator instances, and applied then to view functions. For more information on each of these functions, take a look at their respective docstrings and source code.

Finally, you will see a small example of a URLconf, a view, and an AP set which could be used to display info on an object.

To begin with, the URLconf:

from django.conf.urls.defaults import *

urlpatterns = patterns('myapp',
(r'^/object/([\d]+)/$', views.details),
)The AP definitions::

from myapp import models

id_to_int = pos_filter(0, int)

@no_request
def id_to_object(*args, **kwargs):
return (models.Object.objects.get(pk=args[0]),), kwargs

detail_deco = APDecorator(
id_to_int,
id_to_object
)The view::

from django.shortcuts import render_to_response

@detail_deco
def details(request, object):
return render_to_response('object_details.html', {'object': object})And there you have it: from URL to HTML in only a few lines of code, using APs. Whilst Django's generic object_detail view could also do this in just the URLconf, this is a striking example of how APs could save some of the boilerplate that would otherwise go into the view: turning the id into an integer, looking up the object, and then rendering. Also, this would have to be replicated for several different views: APs may be reused, and so are a more efficient (and DRY) way of factoring out some of the patterns in development.

Tags

argumentprocessor django mtv mvc python views

In a Nutshell, django-argprocessor...

 No code available to analyze

Open Hub computes statistics on FOSS projects by examining source code and commit history in source code management systems. This project has no code locations, and so Open Hub cannot perform this analysis

Is this project's source code hosted in a publicly available repository? Do you know the URL? If you do, click the button below and tell us so that Open Hub can generate statistics! It's fast and easy - try it and see!

Add a code location

GNU General Public License v2.0 or later
Permitted

Commercial Use

Modify

Distribute

Place Warranty

Forbidden

Sub-License

Hold Liable

Required

Distribute Original

Disclose Source

Include Copyright

State Changes

Include License

These details are provided for information only. No information here is legal advice and should not be used as such.

This Project has No vulnerabilities Reported Against it

Did You Know...

  • ...
    use of OSS increased in 65% of companies in 2016
  • ...
    you can embed statistics from Open Hub on your site
  • ...
    65% of companies leverage OSS to speed application development in 2016
  • ...
    data presented on the Open Hub is available through our API

 No code available to analyze

Open Hub computes statistics on FOSS projects by examining source code and commit history in source code management systems. This project has no code locations, and so Open Hub cannot perform this analysis

Is this project's source code hosted in a publicly available repository? Do you know the URL? If you do, click the button below and tell us so that Open Hub can generate statistics! It's fast and easy - try it and see!

Add a code location

Community Rating

Be the first to rate this project
Click to add your rating
   Spinner
Review this Project!
Sample ohloh analysis