Last active
August 29, 2015 14:00
-
-
Save amitittyerah/11233004 to your computer and use it in GitHub Desktop.
Django web service helpers to iterate through and return expected parameters from the request object. Static methods can be left generic doing overrides on certain getattrs instead of having to redefine attributes at every stage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# service_helpers.py | |
def create_img_name(identifier): | |
return '%s%s%s' % (identifier, to_unix.to_unix(datetime.now()), randomstring.get_random_string()) | |
def get_params(obs, params, struct='dict'): | |
if struct == 'dict': | |
values = dict([ (param, obs.get(param)) for param in params if param in obs]) | |
else: | |
values = [(param, obs.get(param)) for param in params] | |
return values | |
def get_post_params(request, params): | |
return get_params(request.POST, params) | |
def get_get_params(request, params): | |
return get_params(request.GET, params) | |
def get_file_params(request, params, path, identifier): | |
files = get_params(request.FILES, params, struct='list') | |
paths = [] | |
for file in files: | |
file_name = '%s/%s' % (path, create_img_name(identifier)) | |
file_path = '%s/%s' % (settings.MEDIA_ROOT, file_name) | |
destination = open(file_path, 'w') | |
if file[1].multiple_chunks(): | |
for chunk in file[1].chunks(): | |
destination.write(chunk) | |
else: | |
destination.write(file[1].read()) | |
destination.close() | |
paths.append({file[0]: file_name}) | |
print paths | |
return paths | |
# service.py | |
def register(request): | |
post_params = ['uname', 'password'] | |
file_params = ['icon'] | |
user = User.register(service_helpers.get_post_params(request, post_params)) | |
user.add_icons(service_helpers.get_file_params(request, file_params, User.ICON_PATH)) | |
return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment