當前位置:首頁 » 編程語言 » pythonredis連接

pythonredis連接

發布時間: 2022-10-05 04:56:49

python怎麼將數據寫入到redis

代碼如下:
import redis

class Database:
def __init__(self):
self.host = 'localhost'
self.port = 6379

def write(self,website,city,year,month,day,deal_number):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
val = deal_number
r = redis.StrictRedis(host=self.host,port=self.port)
r.set(key,val)
except Exception, exception:
print exception

def read(self,website,city,year,month,day):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
r = redis.StrictRedis(host=self.host,port=self.port)
value = r.get(key)
print value
return value
except Exception, exception:
print exception

if __name__ == '__main__':
db = Database()
db.write('meituan','beijing',2013,9,1,8000)
db.read('meituan','beijing',2013,9,1)

Ⅱ python 虛擬環境里怎麼啟動redis

運行
打開Python解釋器:
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0) #如果設置了密碼,就加上password=密碼
>>> r.set('foo', 'bar') #或者寫成 r['foo'] = 'bar'
True
>>> r.get('foo')
'bar'
>>> r.delete('foo')
True
>>> r.dbsize() #庫里有多少key,多少條數據
0
>>> r['test']='OK!'

Ⅲ python怎麼測試與redis的連接

Redis服務端:192.168.100.132;port=6379
Redis客戶端:192.168.100.132
客戶端操作:
安裝python支持redis;
tar zxvf redis-2.9.1.tar.gz
cd redis-2.9.1
python setup.py install
服務端啟動redis
/root/redis-2.2.12/src/redis-server
客戶端測試:
[root@master ~]# python
>>> import redis
>>> r = redis.Redis(host='192.168.100.132',port=6379,db=0) //#如果設置了密碼,就加上password=密碼
>>> r.set('name','lansgg')
True
>>> r.get('name')
'lansgg'
>>> r.exists('name') //#看是否存在這個鍵值
True
>>> r.delete('name')
1
>>> r.dbsize() //#庫里有多少key,多少條數據
0L
>>> r.set('name','lansgg')
True
>>> r.flushdb() // #刪除當前資料庫的所有數據
True
>>> r.get('name')
>>> r.set('name','lansgg')
True
>>> r.set('wm','leo')
True
>>> r.set('tt','coffee')
True
>>> r.keys() // # 列出所有鍵值。
['tt', 'wm', 'name']
>>> r.save() // #強行把資料庫保存到硬碟。保存時阻塞
True
>>> r.dbsize()
3L
>>> dir(r)
['RESPONSE_CALLBACKS', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__mole__', '__new__', '__rece__', '__rece_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_zaggregate', 'append', 'bgrewriteaof', 'bgsave', 'bitcount', 'bitop', 'blpop', 'brpop', 'brpoplpush', 'client_getname', 'client_kill', 'client_list', 'client_setname', 'config_get', 'config_resetstat', 'config_set', 'connection_pool', 'dbsize', 'debug_object', 'decr', 'delete', 'mp', 'echo', 'eval', 'evalsha', 'execute_command', 'exists', 'expire', 'expireat', 'flushall', 'flushdb', 'from_url', 'get', 'getbit', 'getrange', 'getset', 'hdel', 'hexists', 'hget', 'hgetall', 'hincrby', 'hincrbyfloat', 'hkeys', 'hlen', 'hmget', 'hmset', 'hscan', 'hset', 'hsetnx', 'hvals', 'incr', 'incrby', 'incrbyfloat', 'info', 'keys', 'lastsave', 'lindex', 'linsert', 'llen', 'lock', 'lpop', 'lpush', 'lpushx', 'lrange', 'lrem', 'lset', 'ltrim', 'mget', 'move', 'mset', 'msetnx', 'object', 'parse_response', 'persist', 'pexpire', 'pexpireat', 'ping', 'pipeline', 'psetex', 'pttl', 'publish', 'pubsub', 'randomkey', 'register_script', 'rename', 'renamenx', 'response_callbacks', 'restore', 'rpop', 'rpoplpush', 'rpush', 'rpushx', 'sadd', 'save', 'scan', 'scard', 'script_exists', 'script_flush', 'script_kill', 'script_load', 'sdiff', 'sdiffstore', 'sentinel', 'sentinel_get_master_addr_by_name', 'sentinel_masters', 'sentinel_sentinels', 'sentinel_slaves', 'set', 'set_response_callback', 'setbit', 'setex', 'setnx', 'setrange', 'shutdown', 'sinter', 'sinterstore', 'sismember', 'slaveof', 'smembers', 'smove', 'sort', 'spop', 'srandmember', 'srem', 'sscan', 'strlen', 'substr', 'sunion', 'sunionstore', 'time', 'transaction', 'ttl', 'type', 'unwatch', 'watch', 'zadd', 'zcard', 'zcount', 'zincrby', 'zinterstore', 'zrange', 'zrangebyscore', 'zrank', 'zrem', 'zremrangebyrank', 'zremrangebyscore', 'zrevrange', 'zrevrangebyscore', 'zrevrank', 'zscan', 'zscore', 'zunionstore']
這只是一個簡單的測試,為了測試redis是否正常工作,我們安裝是否正確;

Ⅳ python-redis鏈接redis怎麼認證

利用r=reids.Redis(host='localhost', port=6379,db=0)也可以。
區別:Redis是StrictRedis的子類,用於向後兼容舊版本的redis-py。

Ⅳ 如何在linux上為Python語言安裝Redis客戶端

(1)下載好之後,使用命令進行解壓

(2)使用命令python ez_setup.py進行運行:

(3)使用命令python -m easy_install redis hiredis 來安裝redis包以及hireredis包:

由上圖可看出在安裝過程中出問題了,最終找到原因才是因為Linux上的Python版本(2.7)太低!!!所以我們接下來升級Python的版本:

a)首先還是在Python的官網上下載安裝包,下面給出下載的地址:

https://www.python.org/downloads/source/

我選擇的版本是Python-3.1.2版本,其他的版本也是可以,但至少要比2.7版本要高:

b)解壓安裝包:

d)在/usr/local下創建目錄python3,用於安裝python的路徑,以免覆蓋老的版本:

e)開始編譯安裝:
./configure --prefix = /usr/local/python3

make && make install

f)編譯安裝完成之後,此時沒有覆蓋原來的版本,再將原來/usr/bin/python鏈接改為別的名字:

mv /usr/bin/python /usr/bin/python_old

g)再建立新版本python的鏈接:

ln -s
/usr/local/python3/bin/python3
/usr/bin/python

至此python的安裝已經完成!!!!

PS:如果不建立新安裝路徑python3,而是直接默認安裝,則安裝後的新python應該會覆蓋linux下自帶的老版本,也有可能不覆蓋,具體看安裝過程了,這個大家可以自己試驗下,當然如果還想保留原來的版本,那麼這種方法最好不過了。

以上則就是python的新版本!!!!

然後再使用剛開始的命令:

(4)

(5)

至此我們已經完成了在Linux上為Python語言安裝Redis客戶端!!!!接下來我們進行驗證:

(6)首先開啟redis服務:

(7)查看伺服器開啟埠:

(8)開啟redis客戶端連接伺服器:

(9)下面我們使用python來測試redis,首先啟動python:

(10)導入redis客戶端:

(11)創建redis連接,並設置一個值,然後通過獲取返回值來判斷設置操作是否執行成功

Ⅵ python redis連接 線程安全么

在ConnectionPool之前,如果需要連接redis,我都是用StrictRedis這個類,在源碼中可以看到這個類的具體解釋:

redis.StrictRedis Implementation of the Redis protocol.This abstract class provides a Python interface to all Redis commands and an
implementation of the Redis protocol.Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server
使用的方法:

?

1
2

r=redis.StrictRedis(host=xxxx, port=xxxx, db=xxxx)
r.xxxx()

有了ConnectionPool這個類之後,可以使用如下方法

?

1
2

pool = redis.ConnectionPool(host=xxx, port=xxx, db=xxxx)
r = redis.Redis(connection_pool=pool)

這里Redis是StrictRedis的子類
簡單分析如下:
在StrictRedis類的__init__方法中,可以初始化connection_pool這個參數,其對應的是一個ConnectionPool的對象:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class StrictRedis(object):
........
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
socket_connect_timeout=None,
socket_keepalive=None, socket_keepalive_options=None,
connection_pool=None, unix_socket_path=None,
encoding='utf-8', encoding_errors='strict',
charset=None, errors=None,
decode_responses=False, retry_on_timeout=False,
ssl=False, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None):
if not connection_pool:
..........
connection_pool = ConnectionPool(**kwargs)
self.connection_pool = connection_pool

在StrictRedis的實例執行具體的命令時會調用execute_command方法,這里可以看到具體實現是從連接池中獲取一個具體的連接,然後執行命令,完成後釋放連接:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# COMMAND EXECUTION AND PROTOCOL PARSING
def execute_command(self, *args, **options):
"Execute a command and return a parsed response"
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options) #調用ConnectionPool.get_connection方法獲取一個連接
try:
connection.send_command(*args) #命令執行,這里為Connection.send_command
return self.parse_response(connection, command_name, **options)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
finally:
pool.release(connection) #調用ConnectionPool.release釋放連接

在來看看ConnectionPool類:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

class ConnectionPool(object):
...........
def __init__(self, connection_class=Connection, max_connections=None,
**connection_kwargs): #類初始化時調用構造函數
max_connections = max_connections or 2 ** 31
if not isinstance(max_connections, (int, long)) or max_connections < 0: #判斷輸入的max_connections是否合法
raise ValueError('"max_connections" must be a positive integer')
self.connection_class = connection_class #設置對應的參數
self.connection_kwargs = connection_kwargs
self.max_connections = max_connections
self.reset() #初始化ConnectionPool 時的reset操作
def reset(self):
self.pid = os.getpid()
self._created_connections = 0 #已經創建的連接的計數器
self._available_connections = [] #聲明一個空的數組,用來存放可用的連接
self._in_use_connections = set() #聲明一個空的集合,用來存放已經在用的連接
self._check_lock = threading.Lock()
.......
def get_connection(self, command_name, *keys, **options): #在連接池中獲取連接的方法
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop() #獲取並刪除代表連接的元素,在第一次獲取connectiong時,因為_available_connections是一個空的數組,
會直接調用make_connection方法
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection) #向代表正在使用的連接的集合中添加元素
return connection
def make_connection(self): #在_available_connections數組為空時獲取連接調用的方法
"Create a new connection"
if self._created_connections >= self.max_connections: #判斷創建的連接是否已經達到最大限制,max_connections可以通過參數初始化
raise ConnectionError("Too many connections")
self._created_connections += 1 #把代表已經創建的連接的數值+1
return self.connection_class(**self.connection_kwargs) #返回有效的連接,默認為Connection(**self.connection_kwargs)
def release(self, connection): #釋放連接,鏈接並沒有斷開,只是存在鏈接池中
"Releases the connection back to the pool"
self._checkpid()
if connection.pid != self.pid:
return
self._in_use_connections.remove(connection) #從集合中刪除元素
self._available_connections.append(connection) #並添加到_available_connections 的數組中
def disconnect(self): #斷開所有連接池中的鏈接
"Disconnects all connections in the pool"
all_conns = chain(self._available_connections,
self._in_use_connections)
for connection in all_conns:
connection.disconnect()

execute_command最終調用的是Connection.send_command方法,關閉鏈接為 Connection.disconnect方法,而Connection類的實現:

?

1
2
3
4
5
6
7

class Connection(object):
"Manages TCP communication to and from a Redis server"
def __del__(self): #對象刪除時的操作,調用disconnect釋放連接
try:
self.disconnect()
except Exception:
pass

核心的鏈接建立方法是通過socket模塊實現:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

def _connect(self):
err = None
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
family, socktype, proto, canonname, socket_address = res
sock = None
try:
sock = socket.socket(family, socktype, proto)
# TCP_NODELAY
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# TCP_KEEPALIVE
if self.socket_keepalive: #構造函數中默認 socket_keepalive=False,因此這里默認為短連接
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
for k, v in iteritems(self.socket_keepalive_options):
sock.setsockopt(socket.SOL_TCP, k, v)
# set the socket_connect_timeout before we connect
sock.settimeout(self.socket_connect_timeout) #構造函數中默認socket_connect_timeout=None,即連接為blocking的模式
# connect
sock.connect(socket_address)
# set the socket_timeout now that we're connected
sock.settimeout(self.socket_timeout) #構造函數中默認socket_timeout=None
return sock
except socket.error as _:
err = _
if sock is not None:
sock.close()
.....

關閉鏈接的方法:

?

1
2
3
4
5
6
7
8
9
10
11

def disconnect(self):
"Disconnects from the Redis server"
self._parser.on_disconnect()
if self._sock is None:
return
try:
self._sock.shutdown(socket.SHUT_RDWR) #先shutdown再close
self._sock.close()
except socket.error:
pass
self._sock = None

可以小結如下
1)默認情況下每創建一個Redis實例都會構造出一個ConnectionPool實例,每一次訪問redis都會從這個連接池得到一個連接,操作完成後會把該連接放回連接池(連接並沒有釋放),可以構造一個統一的ConnectionPool,在創建Redis實例時,可以將該ConnectionPool傳入,那麼後續的操作會從給定的ConnectionPool獲得連接,不會再重復創建ConnectionPool。
2)默認情況下沒有設置keepalive和timeout,建立的連接是blocking模式的短連接。
3)不考慮底層tcp的情況下,連接池中的連接會在ConnectionPool.disconnect中統一銷毀。

Ⅶ window系python連接linux伺服器上Redis

你來錯地方了,去逼乎或者貼吧

Ⅷ python 用redis做什麼功能

redis-py提供兩個類Redis和StrictRedis用於實現Redis的命令,StrictRedis用於實現大部分官方的命令,
並使用官方的語法和命令,Redis是StrictRedis的子類,用於向後兼容舊版本的redis-py。
import redis 導入redis模塊,通過python操作redis 也可以直接在redis主機的服務端操作緩存資料庫
r = redis.Redis(host='192.168.19.130', port=6379) host是redis主機,需要redis服務端和客戶端都起著 redis默認埠是6379
r.set('foo', 'Bar') key是"foo" value是"bar" 將鍵值對存入redis緩存
print r.get('foo') Bar 取出鍵foo對應的值!

Ⅸ python 的 redis 庫,連接池怎麼用

連接池的作用是當前連接斷掉了自動重連
使用方法 https://github.com/andymccurdy/redis-py#connection-pools
你可以全局都公用一個 redis client

By default, each Redis instance you create will in turn create its own connection pool.
你可以不用自己手動使用連接池

Redis 的連接池是多線程安全的、多進程安全的、自動重連的。

你扔 flask.g 之類的全局的地方當然也行,反正 Redis 總是會使用連接池(不指定它每次就用一個新的)。顯式指定連接池的話差異不大,反正你總是要手動在某個全局的地方存一樣東西(連接池對象或者 Redis 對象)。

Ⅹ python把字典存到redis怎麼使用

python把字典存到redis怎麼使用
先寫個測試redis是否正常連接上
import redis
cache = redis.StrictRedis('172.20.0.227',6379)

存儲字元串
key = "javaman_test"
value = "test_string_yy"
cachevalue = cache.get(key)

存儲Dict對象,取出來為字元串
value = {"id":1,"name":"sunxy"}
cache.set(key,value,60)
cachevalue = cache.get(key)
print type(value),type(cachevalue)

這時使用eval()對獲取的結果轉換成dict
cachevalue = cache.get(key)
trans_value = eval(cachevalue)
print type(trans_value),trans_value.get("name")

如果不是一個dict,直接是一個對象呢?
之前用了django中的對象,來看一下
取出來仍然是字元串,如何把對象存進去呢

eval()只是將結果轉換成字典,這個肯定不行,我們應該需要將對象存到redis中。

使用pickle模塊,在存入到redis中時調用mps函數,獲取後調用loads函數
import pickleredis.set(key,pickle.mps(xt_instry),180)
pickle.loads(result)

熱點內容
浙江萬里的伺服器地址 發布:2024-04-20 21:16:59 瀏覽:406
ndklinux下載 發布:2024-04-20 21:05:22 瀏覽:565
王者榮耀解壓資源包97 發布:2024-04-20 20:46:10 瀏覽:396
蘋果手機沒有密碼怎麼打開 發布:2024-04-20 20:45:25 瀏覽:92
如何用濃硝酸配置百分之2的硝酸 發布:2024-04-20 20:44:39 瀏覽:796
微信商城java源碼下載 發布:2024-04-20 20:27:35 瀏覽:121
用友軟體sql 發布:2024-04-20 20:10:01 瀏覽:933
python倒著循環 發布:2024-04-20 20:09:52 瀏覽:759
雲伺服器遠程電腦版 發布:2024-04-20 20:09:12 瀏覽:259
ps資料庫 發布:2024-04-20 19:52:43 瀏覽:522