Skip to content

Instantly share code, notes, and snippets.

@NetAngels
Created February 25, 2011 06:42
Show Gist options
  • Save NetAngels/843447 to your computer and use it in GitHub Desktop.
Save NetAngels/843447 to your computer and use it in GitHub Desktop.
CSD parser decorator
"""
Simplified decorator which is used to convert raw POST data in CSD (comma-separated dict) format to the list of dicts and then store this list as `request.csd` variable
For example, data like:
user=netangels,site=netangels.ru,hits=1234
user=example,site=example.com,hits=4567
stored in the file data.csd and sent by curl with a command like this:
curl --data-binary @data.csd http://...
will be converted by the decorator to the structure as follows
[{'hits': '1234', 'site': 'netangels.ru', 'user': 'netangels'},
{'hits': '4567', 'site': 'example.com', 'user': 'example'}]
"""
def parse_csd(view):
def decorator(request, *args, **kwargs):
data = request.raw_post_data or ''
lines = data.splitlines()
csd = []
for line in lines:
chunks = line.split(',')
element = dict(map(lambda chunk: chunk.split('=', 1), chunks))
csd.append(element)
request.csd = csd
return view(request, *args, **kwargs)
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment