Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django redis connection backend or how to implement one

Is there any plugin or 3rd party backend to manage redis connections in Django, so the methods in view.py don't have to explicitly connect to redis for every request?

If not, how would you start implementing one? A new plugin? a new backend? a new django middleware?

Thank you.

like image 312
simao Avatar asked Dec 28 '10 10:12

simao


1 Answers

I think the emerging standard for non-rel databases is django-nonrel . I don't know if django-nonrel is production ready or if support redis, but they have a guide on writing a custom no-sql backend.

Unfortunately, i don't think that writing support for a redis on standard django is easy as writing a DatabaseBackend. There's a lot in django models mechanics and workflow that simply assumes an ACID database. What about syncdb ? And about Querysets?

However, you may try to write a poor-mans approach using models.Manager and a lot of tweaking on your model. For example:

# 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': '[email protected]'},
                         'name': 'Kurt Godel','email': '[email protected]'}]

        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

Please not that i've only made an sketch of how you can tweak the django models. I have not tested and run this code. I first suggest you to investigate django-nonrel.

like image 87
Frangossauro Avatar answered Sep 23 '22 15:09

Frangossauro