2013-10-04 18 views
0

SQLAlchemy的 - 在飛行物體屏蔽值我有以下的SQLAlchemy類中定義

Base = sqlalchemy.ext.declarative.declarative_base() 
class NSASecrets(Base): 
    __tablename__ = 'nsasecrets'; 
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True); 
    text = sqlalchemy.Column(sqlalchemy.String); 
    author = sqlalchemy.Column(sqlalchemy.String); 

現在我想做的是能夠掩蓋「作者」字段取決於一些邏輯,像:

if (allowed): 
    nsasecrets = session.query(NSASecrets,**mask=False**); 
else: 
    nsasecrets = session.query(NSASecrets,**mask=True**); 
for nsasecret in nsasecrets: 
    print '{0} {1}'.format(author, text); 

所以根據這個「面具」的參數,我想輸出是「約翰·史密斯」的假案件 - 輸出沒有被屏蔽,或者「Ĵ*** * * H」時輸出屏蔽。現在很明顯,我可以在這個打印中做到這一點,但問題是打印散佈在代碼周圍,我看到以受控集中方式執行此操作的唯一方法是創建具有蒙版值的SQLAlchemy對象。那麼是否有任何衆所周知的解決方案?或者我應該創建自己的會話管理器來重載「查詢」接口,或者我錯過了一些其他可能的解決方案嗎?

感謝

+0

'nsasecret.author'和'nsasecret.text'應該是。在'格式' –

+0

,它只是'author'屬性的權利? –

回答

1

這通常是在Python,我們用一種叫做descriptors做那種事。將描述符與SQLAlchemy映射列組合在一起的一種簡單方法是使用synonym,雖然同義詞在這一點上有點過時,但贊成使用稱爲hybrids的「魔術」系統。可以在這裏使用,下面是一個混合的例子:

from sqlalchemy import * 
from sqlalchemy.orm import * 
from sqlalchemy.ext.declarative import declarative_base, synonym_for 
from sqlalchemy.ext.hybrid import hybrid_property 

Base = declarative_base() 

class NSASecrets(Base): 
    __tablename__ = 'nsasecrets' 

    id = Column(Integer, primary_key=True) 
    _text = Column("text", String) 
    _author = Column("author", String) 

    def _obfuscate(self, value): 
     return "%s%s" % (value[0], ("*" * (len(value) - 2))) 

    @hybrid_property 
    def text(self): 
     return self._obfuscate(self._text) 

    @text.setter 
    def text(self, value): 
     self._text = value 

    @text.expression 
    def text(cls): 
     return cls._text 

    @hybrid_property 
    def author(self): 
     return self._obfuscate(self._author) 

    @author.setter 
    def author(self, value): 
     self._author = value 

    @author.expression 
    def author(cls): 
     return cls._author 

n1 = NSASecrets(text='some text', author="some author") 

print n1.text 
print n1.author 

請注意,這與查詢沒有太大的關係。將數據格式化到行集中的想法是一種不同的方式,而且還有一些方法可以實現這一點,但如果您只關心引用「文本」和「作者」的打印語句,將它作爲python訪問模式可能會更方便。