Skip to content

Instantly share code, notes, and snippets.

@otbzi
Created February 22, 2013 06:40
Show Gist options
  • Save otbzi/5011270 to your computer and use it in GitHub Desktop.
Save otbzi/5011270 to your computer and use it in GitHub Desktop.
# corelib.mixin.props.__init__
# -*- coding: utf-8 -*-
"""
提供props常见操作支持,需要对应的类支持get_uuid, 目前是IData
"""
import time
import datetime
from corelib.json import encode, decode
from corelib.doubandb import db
from corelib.local_cache import lc
class PropsMixin(object):
@property
def _props_name(self):
'''
为了保证能够与corelib.mixin.wrapper能和谐的工作
需要不同的class有不同的__props以免冲突
'''
return '__%s/props_cached' % self.get_uuid()
@property
def _props_db_key(self):
return '%s/props' % self.get_uuid()
def _get_props(self):
props = lc.get(self._props_name)
if props is None:
props = db.get(self._props_db_key, '')
props = props and decode(props) or {}
lc.set(self._props_name, props)
return props
def _set_props(self, props):
db.set(self._props_db_key, encode(props))
lc.delete(self._props_name, props)
def _destory_props(self):
db.delete(self._props_db_key)
lc.delete(self._props_name)
get_props = _get_props
set_props = _set_props
props = property(_get_props, _set_props)
def set_props_item(self, key, value):
props = self.props
props[key] = value
self.props = props
def delete_props_item(self, key):
props = self.props
props.pop(key, None)
self.props = props
def get_props_item(self, key, default=None):
return self.props.get(key, default)
def incr_props_item(self, key):
n = self.get_props_item(key, 0)
n += 1
self.set_props_item(key, n)
return n
def decr_props_item(self, key, min=0):
n = self.get_props_item(key, 0)
n -= 1
n = n > 0 and n or 0
self.set_props_item(key, n > min and n or min)
return n
def update_props(self, data):
props = self.props
props.update(data)
self.props = props
class PropsItem(object):
def __init__(self, name, default=None, output_filter=None):
self.name = name
self.default = default
self.output_filter = output_filter
def __get__(self, obj, objtype):
r = obj.get_props_item(self.name, None)
if r is None:
return self.default
elif self.output_filter:
return self.output_filter(r)
else:
return r
def __set__(self, obj, value):
obj.set_props_item(self.name, value)
def __delete__(self, obj):
obj.delete_props_item(self.name)
datetime_outputfilter = lambda v: datetime.datetime.strptime(v, '%Y-%m-%d %H:%M:%S')
date_outputfilter = lambda v: datetime.datetime.strptime(v, '%Y-%m-%d').date()
class DatetimePropsItem(PropsItem):
def __init__(self, name, default=None):
super(DatetimePropsItem, self).__init__(name, default, datetime_outputfilter)
class DatePropsItem(PropsItem):
def __init__(self, name, default=None):
super(DatePropsItem, self).__init__(name, default, date_outputfilter)
@otbzi
Copy link
Author

otbzi commented Feb 22, 2013

使用的时候就

class Foo(PropsMixin):
some_prop = PropsItem('some_prop')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment