Django redis连接后端或如何实现一个

时间:2010-12-28 10:44:28

标签: python django redis

是否有任何插件或第三方后端来管理Django中的redis连接,因此view.py中的方法不必为每个请求显式连接到redis?

如果没有,您将如何开始实施?一个新的插件?一个新的后端?一个新的django中间件?

谢谢。

1 个答案:

答案 0 :(得分:5)

我认为非可靠性数据库的新兴标准是django-nonrel。我不知道django-nonrel是生产就绪还是支持redis,但他们有writing a custom no-sql backend的指南。

不幸的是,我不认为在编写DatabaseBackend时,在标准django上编写对redis的支持很容易。 django模型的机制和工作流程中有很多假设ACID数据库。那么syncdb呢?关于Querysets

但是,您可以尝试使用models.Manager编写一个穷人方法,并对您的模型进行大量调整。例如:

# helper   
def fill_model_instance(instance, values):
    """ Fills an model instance with the values from dict values """                                    
    attributes = filter(lambda x: not x.startswith('_'), instance.__dict__.keys())

    for a in attributes:
        try:
            setattr(instance, a, values[a.upper()])
            del values[a.upper()]
        except:
            pass

    for v in values.keys():
        setattr(instance, v, values[v])

    return instance




class AuthorManager( models.Manager ):

    # You may try to use the default methods.
    # But should be freaking hard...
    def get_query_set(self):
        raise NotImplementedError("Maybe you can write a Non relational Queryset()! ")

    def latest(self, *args, **kwargs):
        # redis Latest query
        pass

    def filter(self, *args, **kwargs):
       # redis filter query
       pass

    # Custom methods that you may use, instead of rewriting
    # the defaults ones.
    def open_connection(self):
        # Open a redis connection
        pass

    def search_author( self, *args, **kwargs ):
        self.open_connection()

        # Write your query. I don't know how this shiny non-sql works.
        # Assumes it returns a dict for every matched author.
        authors_list = [{'name': 'Leibniz',   'email': 'iinventedcalculus@gmail.com'},
                         'name': 'Kurt Godel','email': 'self.consistent.error@gmail.com'}]

        return [fill_instance(Author(), author) for author in authors_list]



class Author( models.Model ):
    name      = models.CharField( max_length = 255 )
    email     = models.EmailField( max_length = 255 )

     def save(self):
         raise NotImplementedError("TODO: write a redis save")

     def delete(self):
         raise NotImplementedError(""TODO: write a delete save")

     class Meta:
          managed = False

请注意,我只是简要介绍了如何调整django模型。我还没有 测试并运行此代码。我首先建议你调查django-nonrel。