forked from redis/redis-py
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommands.py
3141 lines (2678 loc) · 119 KB
/
commands.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import time
import warnings
import hashlib
from redis.exceptions import (
ConnectionError,
DataError,
NoScriptError,
RedisError,
)
def list_or_args(keys, args):
# returns a single new list combining keys and args
try:
iter(keys)
# a string or bytes instance can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, (bytes, str)):
keys = [keys]
else:
keys = list(keys)
except TypeError:
keys = [keys]
if args:
keys.extend(args)
return keys
class Commands:
"""
A class containing all of the implemented redis commands. This class is
to be used as a mixin.
"""
# SERVER INFORMATION
# ACL methods
def acl_cat(self, category=None):
"""
Returns a list of categories or commands within a category.
If ``category`` is not supplied, returns a list of all categories.
If ``category`` is supplied, returns a list of all commands within
that category.
"""
pieces = [category] if category else []
return self.execute_command('ACL CAT', *pieces)
def acl_deluser(self, username):
"Delete the ACL for the specified ``username``"
return self.execute_command('ACL DELUSER', username)
def acl_genpass(self):
"Generate a random password value"
return self.execute_command('ACL GENPASS')
def acl_getuser(self, username):
"""
Get the ACL details for the specified ``username``.
If ``username`` does not exist, return None
"""
return self.execute_command('ACL GETUSER', username)
def acl_list(self):
"Return a list of all ACLs on the server"
return self.execute_command('ACL LIST')
def acl_log(self, count=None):
"""
Get ACL logs as a list.
:param int count: Get logs[0:count].
:rtype: List.
"""
args = []
if count is not None:
if not isinstance(count, int):
raise DataError('ACL LOG count must be an '
'integer')
args.append(count)
return self.execute_command('ACL LOG', *args)
def acl_log_reset(self):
"""
Reset ACL logs.
:rtype: Boolean.
"""
args = [b'RESET']
return self.execute_command('ACL LOG', *args)
def acl_load(self):
"""
Load ACL rules from the configured ``aclfile``.
Note that the server must be configured with the ``aclfile``
directive to be able to load ACL rules from an aclfile.
"""
return self.execute_command('ACL LOAD')
def acl_save(self):
"""
Save ACL rules to the configured ``aclfile``.
Note that the server must be configured with the ``aclfile``
directive to be able to save ACL rules to an aclfile.
"""
return self.execute_command('ACL SAVE')
def acl_setuser(self, username, enabled=False, nopass=False,
passwords=None, hashed_passwords=None, categories=None,
commands=None, keys=None, reset=False, reset_keys=False,
reset_passwords=False):
"""
Create or update an ACL user.
Create or update the ACL for ``username``. If the user already exists,
the existing ACL is completely overwritten and replaced with the
specified values.
``enabled`` is a boolean indicating whether the user should be allowed
to authenticate or not. Defaults to ``False``.
``nopass`` is a boolean indicating whether the can authenticate without
a password. This cannot be True if ``passwords`` are also specified.
``passwords`` if specified is a list of plain text passwords
to add to or remove from the user. Each password must be prefixed with
a '+' to add or a '-' to remove. For convenience, the value of
``passwords`` can be a simple prefixed string when adding or
removing a single password.
``hashed_passwords`` if specified is a list of SHA-256 hashed passwords
to add to or remove from the user. Each hashed password must be
prefixed with a '+' to add or a '-' to remove. For convenience,
the value of ``hashed_passwords`` can be a simple prefixed string when
adding or removing a single password.
``categories`` if specified is a list of strings representing category
permissions. Each string must be prefixed with either a '+' to add the
category permission or a '-' to remove the category permission.
``commands`` if specified is a list of strings representing command
permissions. Each string must be prefixed with either a '+' to add the
command permission or a '-' to remove the command permission.
``keys`` if specified is a list of key patterns to grant the user
access to. Keys patterns allow '*' to support wildcard matching. For
example, '*' grants access to all keys while 'cache:*' grants access
to all keys that are prefixed with 'cache:'. ``keys`` should not be
prefixed with a '~'.
``reset`` is a boolean indicating whether the user should be fully
reset prior to applying the new ACL. Setting this to True will
remove all existing passwords, flags and privileges from the user and
then apply the specified rules. If this is False, the user's existing
passwords, flags and privileges will be kept and any new specified
rules will be applied on top.
``reset_keys`` is a boolean indicating whether the user's key
permissions should be reset prior to applying any new key permissions
specified in ``keys``. If this is False, the user's existing
key permissions will be kept and any new specified key permissions
will be applied on top.
``reset_passwords`` is a boolean indicating whether to remove all
existing passwords and the 'nopass' flag from the user prior to
applying any new passwords specified in 'passwords' or
'hashed_passwords'. If this is False, the user's existing passwords
and 'nopass' status will be kept and any new specified passwords
or hashed_passwords will be applied on top.
"""
encoder = self.connection_pool.get_encoder()
pieces = [username]
if reset:
pieces.append(b'reset')
if reset_keys:
pieces.append(b'resetkeys')
if reset_passwords:
pieces.append(b'resetpass')
if enabled:
pieces.append(b'on')
else:
pieces.append(b'off')
if (passwords or hashed_passwords) and nopass:
raise DataError('Cannot set \'nopass\' and supply '
'\'passwords\' or \'hashed_passwords\'')
if passwords:
# as most users will have only one password, allow remove_passwords
# to be specified as a simple string or a list
passwords = list_or_args(passwords, [])
for i, password in enumerate(passwords):
password = encoder.encode(password)
if password.startswith(b'+'):
pieces.append(b'>%s' % password[1:])
elif password.startswith(b'-'):
pieces.append(b'<%s' % password[1:])
else:
raise DataError('Password %d must be prefixeed with a '
'"+" to add or a "-" to remove' % i)
if hashed_passwords:
# as most users will have only one password, allow remove_passwords
# to be specified as a simple string or a list
hashed_passwords = list_or_args(hashed_passwords, [])
for i, hashed_password in enumerate(hashed_passwords):
hashed_password = encoder.encode(hashed_password)
if hashed_password.startswith(b'+'):
pieces.append(b'#%s' % hashed_password[1:])
elif hashed_password.startswith(b'-'):
pieces.append(b'!%s' % hashed_password[1:])
else:
raise DataError('Hashed %d password must be prefixeed '
'with a "+" to add or a "-" to remove' % i)
if nopass:
pieces.append(b'nopass')
if categories:
for category in categories:
category = encoder.encode(category)
# categories can be prefixed with one of (+@, +, -@, -)
if category.startswith(b'+@'):
pieces.append(category)
elif category.startswith(b'+'):
pieces.append(b'+@%s' % category[1:])
elif category.startswith(b'-@'):
pieces.append(category)
elif category.startswith(b'-'):
pieces.append(b'-@%s' % category[1:])
else:
raise DataError('Category "%s" must be prefixed with '
'"+" or "-"'
% encoder.decode(category, force=True))
if commands:
for cmd in commands:
cmd = encoder.encode(cmd)
if not cmd.startswith(b'+') and not cmd.startswith(b'-'):
raise DataError('Command "%s" must be prefixed with '
'"+" or "-"'
% encoder.decode(cmd, force=True))
pieces.append(cmd)
if keys:
for key in keys:
key = encoder.encode(key)
pieces.append(b'~%s' % key)
return self.execute_command('ACL SETUSER', *pieces)
def acl_users(self):
"Returns a list of all registered users on the server."
return self.execute_command('ACL USERS')
def acl_whoami(self):
"Get the username for the current connection"
return self.execute_command('ACL WHOAMI')
def bgrewriteaof(self):
"Tell the Redis server to rewrite the AOF file from data in memory."
return self.execute_command('BGREWRITEAOF')
def bgsave(self):
"""
Tell the Redis server to save its data to disk. Unlike save(),
this method is asynchronous and returns immediately.
"""
return self.execute_command('BGSAVE')
def client_kill(self, address):
"Disconnects the client at ``address`` (ip:port)"
return self.execute_command('CLIENT KILL', address)
def client_kill_filter(self, _id=None, _type=None, addr=None,
skipme=None, laddr=None):
"""
Disconnects client(s) using a variety of filter options
:param id: Kills a client by its unique ID field
:param type: Kills a client by type where type is one of 'normal',
'master', 'slave' or 'pubsub'
:param addr: Kills a client by its 'address:port'
:param skipme: If True, then the client calling the command
:param laddr: Kills a cient by its 'local (bind) address:port'
will not get killed even if it is identified by one of the filter
options. If skipme is not provided, the server defaults to skipme=True
"""
args = []
if _type is not None:
client_types = ('normal', 'master', 'slave', 'pubsub')
if str(_type).lower() not in client_types:
raise DataError("CLIENT KILL type must be one of %r" % (
client_types,))
args.extend((b'TYPE', _type))
if skipme is not None:
if not isinstance(skipme, bool):
raise DataError("CLIENT KILL skipme must be a bool")
if skipme:
args.extend((b'SKIPME', b'YES'))
else:
args.extend((b'SKIPME', b'NO'))
if _id is not None:
args.extend((b'ID', _id))
if addr is not None:
args.extend((b'ADDR', addr))
if laddr is not None:
args.extend((b'LADDR', laddr))
if not args:
raise DataError("CLIENT KILL <filter> <value> ... ... <filter> "
"<value> must specify at least one filter")
return self.execute_command('CLIENT KILL', *args)
def client_info(self):
"""
Returns information and statistics about the current
client connection.
"""
return self.execute_command('CLIENT INFO')
def client_list(self, _type=None, client_id=None):
"""
Returns a list of currently connected clients.
If type of client specified, only that type will be returned.
:param _type: optional. one of the client types (normal, master,
replica, pubsub)
"""
"Returns a list of currently connected clients"
args = []
if _type is not None:
client_types = ('normal', 'master', 'replica', 'pubsub')
if str(_type).lower() not in client_types:
raise DataError("CLIENT LIST _type must be one of %r" % (
client_types,))
args.append(b'TYPE')
args.append(_type)
if client_id is not None:
args.append(b"ID")
args.append(client_id)
return self.execute_command('CLIENT LIST', *args)
def client_getname(self):
"Returns the current connection name"
return self.execute_command('CLIENT GETNAME')
def client_id(self):
"Returns the current connection id"
return self.execute_command('CLIENT ID')
def client_setname(self, name):
"Sets the current connection name"
return self.execute_command('CLIENT SETNAME', name)
def client_unblock(self, client_id, error=False):
"""
Unblocks a connection by its client id.
If ``error`` is True, unblocks the client with a special error message.
If ``error`` is False (default), the client is unblocked using the
regular timeout mechanism.
"""
args = ['CLIENT UNBLOCK', int(client_id)]
if error:
args.append(b'ERROR')
return self.execute_command(*args)
def client_pause(self, timeout):
"""
Suspend all the Redis clients for the specified amount of time
:param timeout: milliseconds to pause clients
"""
if not isinstance(timeout, int):
raise DataError("CLIENT PAUSE timeout must be an integer")
return self.execute_command('CLIENT PAUSE', str(timeout))
def client_unpause(self):
"""
Unpause all redis clients
"""
return self.execute_command('CLIENT UNPAUSE')
def readwrite(self):
"Disables read queries for a connection to a Redis Cluster slave node"
return self.execute_command('READWRITE')
def readonly(self):
"Enables read queries for a connection to a Redis Cluster replica node"
return self.execute_command('READONLY')
def config_get(self, pattern="*"):
"Return a dictionary of configuration based on the ``pattern``"
return self.execute_command('CONFIG GET', pattern)
def config_set(self, name, value):
"Set config item ``name`` with ``value``"
return self.execute_command('CONFIG SET', name, value)
def config_resetstat(self):
"Reset runtime statistics"
return self.execute_command('CONFIG RESETSTAT')
def config_rewrite(self):
"Rewrite config file with the minimal change to reflect running config"
return self.execute_command('CONFIG REWRITE')
def dbsize(self):
"Returns the number of keys in the current database"
return self.execute_command('DBSIZE')
def debug_object(self, key):
"Returns version specific meta information about a given key"
return self.execute_command('DEBUG OBJECT', key)
def echo(self, value):
"Echo the string back from the server"
return self.execute_command('ECHO', value)
def flushall(self, asynchronous=False):
"""
Delete all keys in all databases on the current host.
``asynchronous`` indicates whether the operation is
executed asynchronously by the server.
"""
args = []
if asynchronous:
args.append(b'ASYNC')
return self.execute_command('FLUSHALL', *args)
def flushdb(self, asynchronous=False):
"""
Delete all keys in the current database.
``asynchronous`` indicates whether the operation is
executed asynchronously by the server.
"""
args = []
if asynchronous:
args.append(b'ASYNC')
return self.execute_command('FLUSHDB', *args)
def swapdb(self, first, second):
"Swap two databases"
return self.execute_command('SWAPDB', first, second)
def info(self, section=None):
"""
Returns a dictionary containing information about the Redis server
The ``section`` option can be used to select a specific section
of information
The section option is not supported by older versions of Redis Server,
and will generate ResponseError
"""
if section is None:
return self.execute_command('INFO')
else:
return self.execute_command('INFO', section)
def lastsave(self):
"""
Return a Python datetime object representing the last time the
Redis database was saved to disk
"""
return self.execute_command('LASTSAVE')
def migrate(self, host, port, keys, destination_db, timeout,
copy=False, replace=False, auth=None):
"""
Migrate 1 or more keys from the current Redis server to a different
server specified by the ``host``, ``port`` and ``destination_db``.
The ``timeout``, specified in milliseconds, indicates the maximum
time the connection between the two servers can be idle before the
command is interrupted.
If ``copy`` is True, the specified ``keys`` are NOT deleted from
the source server.
If ``replace`` is True, this operation will overwrite the keys
on the destination server if they exist.
If ``auth`` is specified, authenticate to the destination server with
the password provided.
"""
keys = list_or_args(keys, [])
if not keys:
raise DataError('MIGRATE requires at least one key')
pieces = []
if copy:
pieces.append(b'COPY')
if replace:
pieces.append(b'REPLACE')
if auth:
pieces.append(b'AUTH')
pieces.append(auth)
pieces.append(b'KEYS')
pieces.extend(keys)
return self.execute_command('MIGRATE', host, port, '', destination_db,
timeout, *pieces)
def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
return self.execute_command('OBJECT', infotype, key, infotype=infotype)
def memory_stats(self):
"Return a dictionary of memory stats"
return self.execute_command('MEMORY STATS')
def memory_usage(self, key, samples=None):
"""
Return the total memory usage for key, its value and associated
administrative overheads.
For nested data structures, ``samples`` is the number of elements to
sample. If left unspecified, the server's default is 5. Use 0 to sample
all elements.
"""
args = []
if isinstance(samples, int):
args.extend([b'SAMPLES', samples])
return self.execute_command('MEMORY USAGE', key, *args)
def memory_purge(self):
"Attempts to purge dirty pages for reclamation by allocator"
return self.execute_command('MEMORY PURGE')
def ping(self):
"Ping the Redis server"
return self.execute_command('PING')
def quit(self):
"""Ask the server to close the connection.
https://redis.io/commands/quit
"""
return self.execute_command('QUIT')
def save(self):
"""
Tell the Redis server to save its data to disk,
blocking until the save is complete
"""
return self.execute_command('SAVE')
def shutdown(self, save=False, nosave=False):
"""Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set, no data flush will be
attempted. The "save" and "nosave" options cannot both be set.
"""
if save and nosave:
raise DataError('SHUTDOWN save and nosave cannot both be set')
args = ['SHUTDOWN']
if save:
args.append('SAVE')
if nosave:
args.append('NOSAVE')
try:
self.execute_command(*args)
except ConnectionError:
# a ConnectionError here is expected
return
raise RedisError("SHUTDOWN seems to have failed.")
def slaveof(self, host=None, port=None):
"""
Set the server to be a replicated slave of the instance identified
by the ``host`` and ``port``. If called without arguments, the
instance is promoted to a master instead.
"""
if host is None and port is None:
return self.execute_command('SLAVEOF', b'NO', b'ONE')
return self.execute_command('SLAVEOF', host, port)
def slowlog_get(self, num=None):
"""
Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items.
"""
args = ['SLOWLOG GET']
if num is not None:
args.append(num)
decode_responses = self.connection_pool.connection_kwargs.get(
'decode_responses', False)
return self.execute_command(*args, decode_responses=decode_responses)
def slowlog_len(self):
"Get the number of items in the slowlog"
return self.execute_command('SLOWLOG LEN')
def slowlog_reset(self):
"Remove all items in the slowlog"
return self.execute_command('SLOWLOG RESET')
def time(self):
"""
Returns the server time as a 2-item tuple of ints:
(seconds since epoch, microseconds into this second).
"""
return self.execute_command('TIME')
def wait(self, num_replicas, timeout):
"""
Redis synchronous replication
That returns the number of replicas that processed the query when
we finally have at least ``num_replicas``, or when the ``timeout`` was
reached.
"""
return self.execute_command('WAIT', num_replicas, timeout)
# BASIC KEY COMMANDS
def append(self, key, value):
"""
Appends the string ``value`` to the value at ``key``. If ``key``
doesn't already exist, create it with a value of ``value``.
Returns the new length of the value at ``key``.
"""
return self.execute_command('APPEND', key, value)
def bitcount(self, key, start=None, end=None):
"""
Returns the count of set bits in the value of ``key``. Optional
``start`` and ``end`` parameters indicate which bytes to consider
"""
params = [key]
if start is not None and end is not None:
params.append(start)
params.append(end)
elif (start is not None and end is None) or \
(end is not None and start is None):
raise DataError("Both start and end must be specified")
return self.execute_command('BITCOUNT', *params)
def bitfield(self, key, default_overflow=None):
"""
Return a BitFieldOperation instance to conveniently construct one or
more bitfield operations on ``key``.
"""
return BitFieldOperation(self, key, default_overflow=default_overflow)
def bitop(self, operation, dest, *keys):
"""
Perform a bitwise operation using ``operation`` between ``keys`` and
store the result in ``dest``.
"""
return self.execute_command('BITOP', operation, dest, *keys)
def bitpos(self, key, bit, start=None, end=None):
"""
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` defines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to look at the first three bytes.
"""
if bit not in (0, 1):
raise DataError('bit must be 0 or 1')
params = [key, bit]
start is not None and params.append(start)
if start is not None and end is not None:
params.append(end)
elif start is None and end is not None:
raise DataError("start argument is not set, "
"when end is specified")
return self.execute_command('BITPOS', *params)
def copy(self, source, destination, destination_db=None, replace=False):
"""
Copy the value stored in the ``source`` key to the ``destination`` key.
``destination_db`` an alternative destination database. By default,
the ``destination`` key is created in the source Redis database.
``replace`` whether the ``destination`` key should be removed before
copying the value to it. By default, the value is not copied if
the ``destination`` key already exists.
"""
params = [source, destination]
if destination_db is not None:
params.extend(["DB", destination_db])
if replace:
params.append("REPLACE")
return self.execute_command('COPY', *params)
def decr(self, name, amount=1):
"""
Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount``
"""
# An alias for ``decr()``, because it is already implemented
# as DECRBY redis command.
return self.decrby(name, amount)
def decrby(self, name, amount=1):
"""
Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount``
"""
return self.execute_command('DECRBY', name, amount)
def delete(self, *names):
"Delete one or more keys specified by ``names``"
return self.execute_command('DEL', *names)
def __delitem__(self, name):
self.delete(name)
def dump(self, name):
"""
Return a serialized version of the value stored at the specified key.
If key does not exist a nil bulk reply is returned.
"""
return self.execute_command('DUMP', name)
def exists(self, *names):
"Returns the number of ``names`` that exist"
return self.execute_command('EXISTS', *names)
__contains__ = exists
def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = int(time.total_seconds())
return self.execute_command('EXPIRE', name, time)
def expireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(time.mktime(when.timetuple()))
return self.execute_command('EXPIREAT', name, when)
def get(self, name):
"""
Return the value at key ``name``, or None if the key doesn't exist
"""
return self.execute_command('GET', name)
def getdel(self, name):
"""
Get the value at key ``name`` and delete the key. This command
is similar to GET, except for the fact that it also deletes
the key on success (if and only if the key's value type
is a string).
"""
return self.execute_command('GETDEL', name)
def getex(self, name,
ex=None, px=None, exat=None, pxat=None, persist=False):
"""
Get the value of key and optionally set its expiration.
GETEX is similar to GET, but is a write command with
additional options. All time parameters can be given as
datetime.timedelta or integers.
``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
``exat`` sets an expire flag on key ``name`` for ``ex`` seconds,
specified in unix time.
``pxat`` sets an expire flag on key ``name`` for ``ex`` milliseconds,
specified in unix time.
``persist`` remove the time to live associated with ``name``.
"""
opset = set([ex, px, exat, pxat])
if len(opset) > 2 or len(opset) > 1 and persist:
raise DataError("``ex``, ``px``, ``exat``, ``pxat``",
"and ``persist`` are mutually exclusive.")
pieces = []
# similar to set command
if ex is not None:
pieces.append('EX')
if isinstance(ex, datetime.timedelta):
ex = int(ex.total_seconds())
pieces.append(ex)
if px is not None:
pieces.append('PX')
if isinstance(px, datetime.timedelta):
px = int(px.total_seconds() * 1000)
pieces.append(px)
# similar to pexpireat command
if exat is not None:
pieces.append('EXAT')
if isinstance(exat, datetime.datetime):
s = int(exat.microsecond / 1000000)
exat = int(time.mktime(exat.timetuple())) + s
pieces.append(exat)
if pxat is not None:
pieces.append('PXAT')
if isinstance(pxat, datetime.datetime):
ms = int(pxat.microsecond / 1000)
pxat = int(time.mktime(pxat.timetuple())) * 1000 + ms
pieces.append(pxat)
if persist:
pieces.append('PERSIST')
return self.execute_command('GETEX', name, *pieces)
def __getitem__(self, name):
"""
Return the value at key ``name``, raises a KeyError if the key
doesn't exist.
"""
value = self.get(name)
if value is not None:
return value
raise KeyError(name)
def getbit(self, name, offset):
"Returns a boolean indicating the value of ``offset`` in ``name``"
return self.execute_command('GETBIT', name, offset)
def getrange(self, key, start, end):
"""
Returns the substring of the string value stored at ``key``,
determined by the offsets ``start`` and ``end`` (both are inclusive)
"""
return self.execute_command('GETRANGE', key, start, end)
def getset(self, name, value):
"""
Sets the value at key ``name`` to ``value``
and returns the old value at key ``name`` atomically.
As per Redis 6.2, GETSET is considered deprecated.
Please use SET with GET parameter in new code.
"""
return self.execute_command('GETSET', name, value)
def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
return self.incrby(name, amount)
def incrby(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
# An alias for ``incr()``, because it is already implemented
# as INCRBY redis command.
return self.execute_command('INCRBY', name, amount)
def incrbyfloat(self, name, amount=1.0):
"""
Increments the value at key ``name`` by floating ``amount``.
If no key exists, the value will be initialized as ``amount``
"""
return self.execute_command('INCRBYFLOAT', name, amount)
def keys(self, pattern='*'):
"Returns a list of keys matching ``pattern``"
return self.execute_command('KEYS', pattern)
def lmove(self, first_list, second_list, src="LEFT", dest="RIGHT"):
"""
Atomically returns and removes the first/last element of a list,
pushing it as the first/last element on the destination list.
Returns the element being popped and pushed.
"""
params = [first_list, second_list, src, dest]
return self.execute_command("LMOVE", *params)
def blmove(self, first_list, second_list, timeout,
src="LEFT", dest="RIGHT"):
"""
Blocking version of lmove.
"""
params = [first_list, second_list, src, dest, timeout]
return self.execute_command("BLMOVE", *params)
def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
from redis.client import EMPTY_RESPONSE
args = list_or_args(keys, args)
options = {}
if not args:
options[EMPTY_RESPONSE] = []
return self.execute_command('MGET', *args, **options)
def mset(self, mapping):
"""
Sets key/values based on a mapping. Mapping is a dictionary of
key/value pairs. Both keys and values should be strings or types that
can be cast to a string via str().
"""
items = []
for pair in mapping.items():
items.extend(pair)
return self.execute_command('MSET', *items)
def msetnx(self, mapping):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping is a dictionary of key/value pairs. Both keys and values
should be strings or types that can be cast to a string via str().
Returns a boolean indicating if the operation was successful.
"""
items = []
for pair in mapping.items():
items.extend(pair)
return self.execute_command('MSETNX', *items)
def move(self, name, db):
"Moves the key ``name`` to a different Redis database ``db``"
return self.execute_command('MOVE', name, db)
def persist(self, name):
"Removes an expiration on ``name``"
return self.execute_command('PERSIST', name)
def pexpire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` milliseconds.
``time`` can be represented by an integer or a Python timedelta
object.
"""
if isinstance(time, datetime.timedelta):
time = int(time.total_seconds() * 1000)
return self.execute_command('PEXPIRE', name, time)
def pexpireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
ms = int(when.microsecond / 1000)
when = int(time.mktime(when.timetuple())) * 1000 + ms
return self.execute_command('PEXPIREAT', name, when)
def psetex(self, name, time_ms, value):
"""
Set the value of key ``name`` to ``value`` that expires in ``time_ms``
milliseconds. ``time_ms`` can be represented by an integer or a Python
timedelta object
"""
if isinstance(time_ms, datetime.timedelta):
time_ms = int(time_ms.total_seconds() * 1000)
return self.execute_command('PSETEX', name, time_ms, value)
def pttl(self, name):
"Returns the number of milliseconds until the key ``name`` will expire"
return self.execute_command('PTTL', name)
def hrandfield(self, key, count=None, withvalues=False):
"""
Return a random field from the hash value stored at key.
count: if the argument is positive, return an array of distinct fields.
If called with a negative count, the behavior changes and the command
is allowed to return the same field multiple times. In this case,
the number of returned fields is the absolute value of the
specified count.
withvalues: The optional WITHVALUES modifier changes the reply so it
includes the respective values of the randomly selected hash fields.
"""
params = []
if count is not None:
params.append(count)
if withvalues:
params.append("WITHVALUES")
return self.execute_command("HRANDFIELD", key, *params)
def randomkey(self):
"Returns the name of a random key"
return self.execute_command('RANDOMKEY')
def rename(self, src, dst):
"""
Rename key ``src`` to ``dst``
"""
return self.execute_command('RENAME', src, dst)
def renamenx(self, src, dst):
"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"