Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created August 28, 2018 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseatroy/db0e70391a48333d7456e825b2cc2fb4 to your computer and use it in GitHub Desktop.
Save chelseatroy/db0e70391a48333d7456e825b2cc2fb4 to your computer and use it in GitHub Desktop.
Example of Proxy Model Metaprogramming Antipattern
from __future__ import unicode_literals
from django.shortcuts import render
from models import Visualization
from exceptions import IncompleteDataException, ConstantizeException
from .forms import VisualizationForm
from django.contrib.auth.decorators import login_required
import inspect, re
ClassRegex = re.compile("[a-zA-Z_][a-zA-Z0-9_]*")
def constantize(string):
if not ClassRegex.match(string):
raise ConstantizeException("`%s' contains illegal characters." % str(string))
klass = eval(str(string))
if not inspect.isclass(klass): raise ConstantizeException("`%s' does not refer to a class." % str(string))
return klass
def snake_to_camel(word):
import re
return ''.join(x.capitalize() or '_' for x in word.split('_'))
@login_required
def transform(request):
name = request.GET['script']
if request.POST and request.FILES:
form = VisualizaionForm(request.POST, request.FILES)
if form.is_valid():
input_file = request.FILES['file']
image = None
try:
vizualization = constantize(snake_to_camel(name)).objects.get(pk=name)
image = vizualization.from_data(name, input_file)
except IncompleteDataException as e:
return render(request, 'visualizations/form.html', {'error': e.message()})
return render(request, 'visualizations/results.html', {'image': image})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment