Quantcast
Viewing all articles
Browse latest Browse all 9596

Lintel Technologies: txRedis

txredis is a non-blocking client for the redis database, written in python. It uses twisted for the asynchronous communication with redis.

Install

pipinstalltxredis

Now to check if txredis is properly installed or not goto python prompt and import txredis :

5520:~/test$ python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] onlinux2 Type "help", "copyright", "credits" or "license" for moreinformation. >>> importtxredis Example :

Using redis-cli, add list of user’s in redis-server with hmset :

127.0.0.1:6379> hmsetuserabc 123 OK 127.0.0.1:6379> hmsetuserpqr 456 OK 127.0.0.1:6379> hmsetuserxyz 789 OK

hmset, set key to value within hash name for each corresponding key and value from the mapping dict.

Now, using python twisted get user’s :

rediscreator = protocol.ClientCreator(reactor, RedisClient) df = rediscreator.connectTCP("127.0.0.1", 6379) df.addCallback(self.onRedisConnect) df.addErrback(self.errRedisConnect)

Above code do connection with redis-server.

Here, rediscreator.connectTCP return defer and register appropriate method in addCallback, addErrback

deferrRedisConnect(self, error): log.info("Error redis") print "error" log.error("Failed to connect redsi") log.error(error) defonRedisConnect(self, result): log.info("result") res = result.ping() res.addCallback(self.onSuccess) res.addErrback(self.onFailer) self.rediscon = result

Here, define callback function onRedisConnect and errRedisConnect.

self.rdsdf = self.rdscon.hget("user", "abc") self.rdsdf.addCallback(self.onSuccess) self.rdsdf.addErrback(self.onFailur)

Here, hget return the value of key within the hase name and return defer

defonSuccess(self, result): log.info("success") log.debug(result) defonFailur(self, result): log.info("fail")

Here, define callback function onSuccess and onFailur and log the appropriate result.

1) "123"

It give output 123, it is correspond to user abc


Viewing all articles
Browse latest Browse all 9596

Trending Articles