Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kind of TransMeta Mongo/Flask
def get_fieldname(field, lang):
return "{}_{}".format(field, lang)
def safe_get_value(field):
def get_value(self):
field_name = lambda x: get_fieldname(field, x)
from flask import request
lang = request.accept_languages[0][0][:2]
print "Got lang: {}".format(lang)
if getattr(self, field_name(lang), None):
print "{} found, value: {}" \
.format(field_name(lang), getattr(self, field_name(field)))
return getattr(self, field_name(field))
else:
print "{} not found, default value: " \
.format(field_name(lang), getattr(self, field))
return getattr(self, field)
return get_value
class TransMeta(type):
def __new__(mcs, name, bases, attrs):
fields = ()
if 'Meta' in attrs and hasattr(attrs['Meta'], 'translate'):
fields = attrs['Meta'].translate
if not isinstance(fields, tuple):
raise ValueError("Meta translate value must be a tuple")
init_func = attrs.get('__init__')
def init_wrapper(self, *args, **kwargs):
if init_func:
init_func(self, *args, **kwargs)
for field in fields:
if field not in self.__dict__:
raise ValueError("There is no attribute {field} in the "
"class {cls_name} as specified in "
"the Meta's translate attribute."
.format(field=field, cls_name=name))
delattr(self, field)
attrs[field] = property(safe_get_value(field))
attrs['__init__'] = init_wrapper
return super(TransMeta, mcs).__new__(mcs, name, bases, attrs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.