Created
May 14, 2015 18:38
-
-
Save MarcDufresne/32ede3551081772e4425 to your computer and use it in GitHub Desktop.
Kind of TransMeta Mongo/Flask
This file contains 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
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