This repository has been archived by the owner on Sep 11, 2019. It is now read-only.
forked from jamesls/fakeredis
-
Notifications
You must be signed in to change notification settings - Fork 5
/
fakenewsredis.py
2347 lines (2002 loc) · 79.1 KB
/
fakenewsredis.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
# -*- coding: utf-8 -*-
import random
import warnings
import copy
from ctypes import CDLL, POINTER, c_double, c_char_p, pointer
from ctypes.util import find_library
import fnmatch
from collections import MutableMapping
from datetime import datetime, timedelta
import operator
import sys
import threading
import time
import types
import re
import functools
from itertools import count
import redis
from redis.exceptions import ResponseError
import redis.client
try:
# Python 2.6, 2.7
from Queue import Queue, Empty
except:
# Python 3
from queue import Queue, Empty
PY2 = sys.version_info[0] == 2
__version__ = '0.10.0'
if PY2:
DEFAULT_ENCODING = 'utf-8'
text_type = unicode # noqa: F821
string_types = (str, unicode) # noqa: F821
redis_string_types = (str, unicode, bytes) # noqa: F821
byte_to_int = ord
def to_bytes(x, charset=DEFAULT_ENCODING, errors='strict'):
if isinstance(x, unicode): # noqa: F821
return x.encode(charset, errors)
if isinstance(x, float):
return repr(x)
if isinstance(x, (bytes, bytearray, buffer)) or hasattr(x, '__str__'): # noqa: F821
return bytes(x)
if hasattr(x, '__unicode__'):
return unicode(x).encode(charset, errors) # noqa: F821
raise TypeError('expected bytes or unicode, not ' + type(x).__name__)
def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
if x is None or isinstance(x, str):
return x
return x.encode(charset, errors)
def iteritems(d):
return d.iteritems()
from urlparse import urlparse
else:
DEFAULT_ENCODING = sys.getdefaultencoding()
long = int
basestring = str
text_type = str
string_types = (str,)
redis_string_types = (bytes, str)
def byte_to_int(b):
if isinstance(b, int):
return b
raise TypeError('an integer is required')
def to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
if isinstance(x, (bytes, bytearray, memoryview)): # noqa: F821
return bytes(x)
if isinstance(x, str):
return x.encode(charset, errors)
if isinstance(x, float):
return repr(x).encode(charset, errors)
if hasattr(x, '__str__'):
return str(x).encode(charset, errors)
raise TypeError('expected bytes or str, not ' + type(x).__name__)
def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
if x is None or isinstance(x, str):
return x
return x.decode(charset, errors)
def iteritems(d):
return iter(d.items())
from urllib.parse import urlparse
DATABASES = {}
_libc_library = find_library('c') or find_library('msvcrt')
if not _libc_library:
raise ImportError('fakenewsredis: unable to find libc or equivalent')
_libc = CDLL(_libc_library)
_libc.strtod.restype = c_double
_libc.strtod.argtypes = [c_char_p, POINTER(c_char_p)]
_strtod = _libc.strtod
_WRONGTYPE_MSG = \
"WRONGTYPE Operation against a key holding the wrong kind of value"
def timedelta_total_seconds(delta):
return delta.days * 86400 + delta.seconds + delta.microseconds / 1E6
class _StrKeyDict(MutableMapping):
def __init__(self, *args, **kwargs):
self._dict = dict(*args, **kwargs)
def __getitem__(self, key):
return self._dict[to_bytes(key)]
def __setitem__(self, key, value):
self._dict[to_bytes(key)] = value
def __delitem__(self, key):
del self._dict[to_bytes(key)]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def copy(self):
new_copy = self.__class__()
new_copy.update(self._dict)
return new_copy
class _ExpiringDict(_StrKeyDict):
def __getitem__(self, key):
bytes_key = to_bytes(key)
value, expiration = self._dict[bytes_key]
if expiration is not None and datetime.now() > expiration:
del self._dict[bytes_key]
raise KeyError(key)
return value
def __setitem__(self, key, value):
self._dict[to_bytes(key)] = (value, None)
def expire(self, key, timestamp):
bytes_key = to_bytes(key)
value = self._dict[bytes_key][0]
self._dict[bytes_key] = (value, timestamp)
def setx(self, key, value, src=None):
"""Set a value, keeping the existing expiry time if any. If
`src` is specified, it is used as the source of the expiry
"""
if src is None:
src = key
try:
_, expiration = self._dict[to_bytes(src)]
except KeyError:
expiration = None
self._dict[to_bytes(key)] = (value, expiration)
def persist(self, key):
bytes_key = to_bytes(key)
try:
value, _ = self._dict[bytes_key]
except KeyError:
return
self._dict[bytes_key] = (value, None)
def expiring(self, key):
return self._dict[to_bytes(key)][1]
class _ZSet(_StrKeyDict):
redis_type = b'zset'
class _Hash(_StrKeyDict):
redis_type = b'hash'
def DecodeGenerator(gen):
for item in gen:
yield _decode(item)
def _decode(value):
if isinstance(value, text_type):
return value
elif isinstance(value, bytes):
value = value.decode(DEFAULT_ENCODING)
elif isinstance(value, dict):
value = dict((_decode(k), _decode(v)) for k, v in value.items())
elif isinstance(value, (list, set, tuple)):
value = value.__class__(_decode(x) for x in value)
elif isinstance(value, types.GeneratorType):
value = DecodeGenerator(value)
return value
def _make_decode_func(func):
def decode_response(*args, **kwargs):
val = _decode(func(*args, **kwargs))
return val
return decode_response
def _patch_responses(obj):
for attr_name in dir(obj):
attr = getattr(obj, attr_name)
if not callable(attr) or attr_name.startswith('_'):
continue
func = _make_decode_func(attr)
setattr(obj, attr_name, func)
def _lua_bool_ok(lua_runtime, value):
# Inverse of bool_ok wrapper from redis-py
return lua_runtime.table(ok='OK')
def _lua_reply(converter):
def decorator(func):
func._lua_reply = converter
return func
return decorator
def _remove_empty(func):
@functools.wraps(func)
def wrapper(self, key, *args, **kwargs):
ret = func(self, key, *args, **kwargs)
self._remove_if_empty(key)
return ret
return wrapper
class _Lock(object):
def __init__(self, redis, name, timeout):
self.redis = redis
self.name = name
self.lock = threading.Lock()
redis.set(name, self, ex=timeout)
def __enter__(self):
self.acquire()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.release()
def acquire(self, blocking=True, blocking_timeout=None):
return self.lock.acquire(blocking)
def release(self):
self.lock.release()
self.redis.delete(self.name)
class FakeStrictRedis(object):
@classmethod
def from_url(cls, url, db=None, **kwargs):
url = urlparse(url)
if db is None:
try:
db = int(url.path.replace('/', ''))
except (AttributeError, ValueError):
db = 0
return cls(db=db, **kwargs)
def __init__(self, db=0, charset='utf-8', errors='strict',
decode_responses=False, singleton=True, **kwargs):
if singleton:
self._dbs = DATABASES
else:
self._dbs = {}
if db not in self._dbs:
self._dbs[db] = _ExpiringDict()
self._db = self._dbs[db]
self._db_num = db
self._encoding = charset
self._encoding_errors = errors
self._pubsubs = []
self._decode_responses = decode_responses
if decode_responses:
_patch_responses(self)
@_lua_reply(_lua_bool_ok)
def flushdb(self):
self._db.clear()
return True
@_lua_reply(_lua_bool_ok)
def flushall(self):
for db in self._dbs.values():
db.clear()
del self._pubsubs[:]
return True
def _remove_if_empty(self, key):
try:
value = self._db[key]
except KeyError:
pass
else:
if not value:
del self._db[key]
def _get_string(self, name, default=b''):
value = self._db.get(name, default)
# Allow None so that default can be set as None
if not isinstance(value, bytes) and value is not None:
raise redis.ResponseError(_WRONGTYPE_MSG)
return value
def _setdefault_string(self, name):
value = self._db.setdefault(name, b'')
if not isinstance(value, bytes):
raise redis.ResponseError(_WRONGTYPE_MSG)
return value
# Basic key commands
def append(self, key, value):
self._setdefault_string(key)
self._db[key] += to_bytes(value)
return len(self._db[key])
def bitcount(self, name, start=0, end=-1):
if end == -1:
end = None
else:
end += 1
try:
s = self._get_string(name)[start:end]
return sum([bin(byte_to_int(l)).count('1') for l in s])
except KeyError:
return 0
def decr(self, name, amount=1):
try:
value = int(self._get_string(name, b'0')) - amount
self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not an integer or out of "
"range.")
return value
def exists(self, name):
return name in self._db
__contains__ = exists
def expire(self, name, time):
return self._expire(name, time)
def pexpire(self, name, millis):
return self._expire(name, millis, 1000)
def _expire(self, name, time, multiplier=1):
if isinstance(time, timedelta):
time = int(timedelta_total_seconds(time) * multiplier)
if not isinstance(time, int):
raise redis.ResponseError("value is not an integer or out of "
"range.")
if self.exists(name):
self._db.expire(name, datetime.now() +
timedelta(seconds=time / float(multiplier)))
return True
else:
return False
def expireat(self, name, when):
return self._expireat(name, when)
def pexpireat(self, name, when):
return self._expireat(name, when, 1000)
def _expireat(self, name, when, multiplier=1):
if not isinstance(when, datetime):
when = datetime.fromtimestamp(when / float(multiplier))
if self.exists(name):
self._db.expire(name, when)
return True
else:
return False
def echo(self, value):
if isinstance(value, text_type):
return value.encode('utf-8')
return value
def get(self, name):
value = self._get_string(name, None)
if value is not None:
return to_bytes(value)
def __getitem__(self, name):
return self.get(name)
def getbit(self, name, offset):
"""Returns a boolean indicating the value of ``offset`` in ``name``"""
val = self._get_string(name)
byte = offset // 8
remaining = offset % 8
actual_bitoffset = 7 - remaining
try:
actual_val = byte_to_int(val[byte])
except IndexError:
return 0
return 1 if (1 << actual_bitoffset) & actual_val else 0
def getset(self, name, value):
"""
Set the value at key ``name`` to ``value`` if key doesn't exist
Return the value at key ``name`` atomically
"""
val = self._get_string(name, None)
self._db[name] = to_bytes(value)
return val
def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
try:
if not isinstance(amount, int):
raise redis.ResponseError("value is not an integer or out "
"of range.")
value = int(self._get_string(name, b'0')) + amount
self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not an integer or out of "
"range.")
return value
def incrby(self, name, amount=1):
"""
Alias for command ``incr``
"""
return self.incr(name, amount)
def incrbyfloat(self, name, amount=1.0):
try:
value = float(self._get_string(name, b'0')) + amount
self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not a valid float.")
return value
def keys(self, pattern=None):
return [key for key in self._db
if not key or not pattern or
fnmatch.fnmatch(to_native(key), to_native(pattern))]
def mget(self, keys, *args):
all_keys = self._list_or_args(keys, args)
found = []
if not all_keys:
raise redis.ResponseError(
"wrong number of arguments for 'mget' command")
for key in all_keys:
value = self._db.get(key)
# Non-strings are returned as nil
if not isinstance(value, bytes):
value = None
found.append(value)
return found
@_lua_reply(_lua_bool_ok)
def mset(self, *args, **kwargs):
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise redis.RedisError(
'MSET requires **kwargs or a single dict arg')
kwargs.update(args[0])
for key, val in iteritems(kwargs):
self.set(key, val)
return True
def msetnx(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value if
none of the keys are already set
"""
if not any(k in self._db for k in mapping):
for key, val in iteritems(mapping):
self.set(key, val)
return True
return False
def move(self, name, db):
pass
def persist(self, name):
self._db.persist(name)
def ping(self):
return True
def randomkey(self):
pass
@_lua_reply(_lua_bool_ok)
def rename(self, src, dst):
try:
value = self._db[src]
except KeyError:
raise redis.ResponseError("No such key: %s" % src)
self._db.setx(dst, value, src=src)
del self._db[src]
return True
def renamenx(self, src, dst):
if dst in self._db:
return False
else:
return self.rename(src, dst)
def set(self, name, value, ex=None, px=None, nx=False, xx=False):
if (not nx and not xx) or (nx and self._db.get(name, None) is None) \
or (xx and not self._db.get(name, None) is None):
if ex is not None:
if isinstance(ex, timedelta):
ex = ex.seconds + ex.days * 24 * 3600
if ex <= 0:
raise ResponseError('invalid expire time in SETEX')
self._db[name] = to_bytes(value)
self._db.expire(name, datetime.now() +
timedelta(seconds=ex))
elif px is not None:
if isinstance(px, timedelta):
ms = int(px.microseconds / 1000)
px = (px.seconds + px.days * 24 * 3600) * 1000 + ms
if px <= 0:
raise ResponseError('invalid expire time in SETEX')
self._db[name] = to_bytes(value)
self._db.expire(name, datetime.now() +
timedelta(milliseconds=px))
else:
self._db[name] = to_bytes(value)
return True
else:
return None
__setitem__ = set
def setbit(self, name, offset, value):
val = self._get_string(name, b'\x00')
byte = offset // 8
remaining = offset % 8
actual_bitoffset = 7 - remaining
if len(val) - 1 < byte:
# We need to expand val so that we can set the appropriate
# bit.
needed = byte - (len(val) - 1)
val += b'\x00' * needed
if value == 1:
new_byte = byte_to_int(val[byte]) | (1 << actual_bitoffset)
else:
new_byte = byte_to_int(val[byte]) ^ (1 << actual_bitoffset)
reconstructed = bytearray(val)
reconstructed[byte] = new_byte
self._db.setx(name, bytes(reconstructed))
def setex(self, name, time, value):
if isinstance(time, timedelta):
time = int(timedelta_total_seconds(time))
if not isinstance(time, int):
raise ResponseError(
'value is not an integer or out of range')
return self.set(name, value, ex=time)
def psetex(self, name, time_ms, value):
if isinstance(time_ms, timedelta):
time_ms = int(timedelta_total_seconds(time_ms) * 1000)
if time_ms == 0:
raise ResponseError("invalid expire time in SETEX")
return self.set(name, value, px=time_ms)
def setnx(self, name, value):
result = self.set(name, value, nx=True)
# Real Redis returns False from setnx, but None from set(nx=...)
if not result:
return False
return result
def setrange(self, name, offset, value):
val = self._get_string(name, b"")
if len(val) < offset:
val += b'\x00' * (offset - len(val))
val = val[0:offset] + to_bytes(value) + val[offset+len(value):]
self._db.setx(name, val)
return len(val)
def strlen(self, name):
return len(self._get_string(name))
def substr(self, name, start, end=-1):
if end == -1:
end = None
else:
end += 1
try:
return self._get_string(name)[start:end]
except KeyError:
return b''
# Redis >= 2.0.0 this command is called getrange
# according to the docs.
getrange = substr
def ttl(self, name):
return self._ttl(name)
def pttl(self, name):
return self._ttl(name, 1000)
def _ttl(self, name, multiplier=1):
if name not in self._db:
return -2
exp_time = self._db.expiring(name)
if not exp_time:
return -1
now = datetime.now()
if now > exp_time:
return None
else:
return long(round(((exp_time - now).days * 3600 * 24 +
(exp_time - now).seconds +
(exp_time - now).microseconds / 1E6) * multiplier))
def type(self, name):
key = self._db.get(name)
if hasattr(key.__class__, 'redis_type'):
return key.redis_type
if isinstance(key, redis_string_types):
return b'string'
elif isinstance(key, list):
return b'list'
elif isinstance(key, set):
return b'set'
else:
assert key is None
return b'none'
@_lua_reply(_lua_bool_ok)
def watch(self, *names):
pass
@_lua_reply(_lua_bool_ok)
def unwatch(self):
pass
def delete(self, *names):
deleted = 0
for name in names:
try:
del self._db[name]
deleted += 1
except KeyError:
continue
return deleted
def sort(self, name, start=None, num=None, by=None, get=None, desc=False,
alpha=False, store=None):
"""Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
"""
if (start is None and num is not None) or \
(start is not None and num is None):
raise redis.RedisError(
"RedisError: ``start`` and ``num`` must both be specified")
try:
data = self._db[name]
if not isinstance(data, (list, set, _ZSet)):
raise redis.ResponseError(_WRONGTYPE_MSG)
data = list(data)
if by is not None:
# _sort_using_by_arg mutates data so we don't
# need need a return value.
self._sort_using_by_arg(data, by=by)
elif not alpha:
data.sort(key=self._strtod_key_func)
else:
data.sort()
if desc:
data = list(reversed(data))
if not (start is None and num is None):
data = data[start:start + num]
if store is not None:
self._db[store] = data
return len(data)
else:
return self._retrieve_data_from_sort(data, get)
except KeyError:
return []
def eval(self, script, numkeys, *keys_and_args):
from lupa import LuaRuntime, LuaError
if any(
isinstance(numkeys, t) for t in (text_type, str, bytes)
):
try:
numkeys = int(numkeys)
except ValueError:
# Non-numeric string will be handled below.
pass
if not(isinstance(numkeys, int)):
raise ResponseError("value is not an integer or out of range")
elif numkeys > len(keys_and_args):
raise ResponseError("Number of keys can't be greater than number of args")
elif numkeys < 0:
raise ResponseError("Number of keys can't be negative")
keys_and_args = [to_bytes(v) for v in keys_and_args]
lua_runtime = LuaRuntime(unpack_returned_tuples=True)
set_globals = lua_runtime.eval(
"""
function(keys, argv, redis_call, redis_pcall)
redis = {}
redis.call = redis_call
redis.pcall = redis_pcall
redis.error_reply = function(msg) return {err=msg} end
redis.status_reply = function(msg) return {ok=msg} end
KEYS = keys
ARGV = argv
end
"""
)
expected_globals = set()
set_globals(
[None] + keys_and_args[:numkeys],
[None] + keys_and_args[numkeys:],
functools.partial(self._lua_redis_call, lua_runtime, expected_globals),
functools.partial(self._lua_redis_pcall, lua_runtime, expected_globals)
)
expected_globals.update(lua_runtime.globals().keys())
try:
result = lua_runtime.execute(script)
except LuaError as ex:
raise ResponseError(ex)
self._check_for_lua_globals(lua_runtime, expected_globals)
return self._convert_lua_result(result, nested=False)
def _convert_redis_result(self, lua_runtime, result):
if isinstance(result, dict):
return [
i
for item in result.items()
for i in item
]
elif isinstance(result, set):
converted = sorted(
self._convert_redis_result(lua_runtime, item)
for item in result
)
return lua_runtime.table_from(converted)
elif isinstance(result, (list, set, tuple)):
converted = [
self._convert_redis_result(lua_runtime, item)
for item in result
]
return lua_runtime.table_from(converted)
elif isinstance(result, bool):
return int(result)
elif isinstance(result, float):
return to_bytes(result)
elif result is None:
return False
else:
return result
def _convert_lua_result(self, result, nested=True):
from lupa import lua_type
if lua_type(result) == 'table':
for key in ('ok', 'err'):
if key in result:
msg = self._convert_lua_result(result[key])
if not isinstance(msg, bytes):
raise ResponseError("wrong number or type of arguments")
if key == 'ok':
return msg
elif nested:
return ResponseError(msg)
else:
raise ResponseError(msg)
# Convert Lua tables into lists, starting from index 1, mimicking the behavior of StrictRedis.
result_list = []
for index in count(1):
if index not in result:
break
item = result[index]
result_list.append(self._convert_lua_result(item))
return result_list
elif isinstance(result, text_type):
return to_bytes(result)
elif isinstance(result, float):
return int(result)
elif isinstance(result, bool):
return 1 if result else None
return result
def _check_for_lua_globals(self, lua_runtime, expected_globals):
actual_globals = set(lua_runtime.globals().keys())
if actual_globals != expected_globals:
raise ResponseError(
"Script attempted to set a global variables: %s" % ", ".join(
actual_globals - expected_globals
)
)
def _lua_redis_pcall(self, lua_runtime, expected_globals, op, *args):
try:
return self._lua_redis_call(lua_runtime, expected_globals, op, *args)
except Exception as ex:
return lua_runtime.table_from({"err": str(ex)})
def _lua_redis_call(self, lua_runtime, expected_globals, op, *args):
# Check if we've set any global variables before making any change.
self._check_for_lua_globals(lua_runtime, expected_globals)
# These commands aren't necessarily all implemented, but if op is not one of these commands, we expect
# a ResponseError for consistency with Redis
commands = [
'append', 'auth', 'bitcount', 'bitfield', 'bitop', 'bitpos', 'blpop', 'brpop', 'brpoplpush',
'decr', 'decrby', 'del', 'dump', 'echo', 'eval', 'evalsha', 'exists', 'expire', 'expireat',
'flushall', 'flushdb', 'geoadd', 'geodist', 'geohash', 'geopos', 'georadius', 'georadiusbymember',
'get', 'getbit', 'getrange', 'getset', 'hdel', 'hexists', 'hget', 'hgetall', 'hincrby',
'hincrbyfloat', 'hkeys', 'hlen', 'hmget', 'hmset', 'hscan', 'hset', 'hsetnx', 'hstrlen', 'hvals',
'incr', 'incrby', 'incrbyfloat', 'info', 'keys', 'lindex', 'linsert', 'llen', 'lpop', 'lpush',
'lpushx', 'lrange', 'lrem', 'lset', 'ltrim', 'mget', 'migrate', 'move', 'mset', 'msetnx',
'object', 'persist', 'pexpire', 'pexpireat', 'pfadd', 'pfcount', 'pfmerge', 'ping', 'psetex',
'psubscribe', 'pttl', 'publish', 'pubsub', 'punsubscribe', 'rename', 'renamenx', 'restore',
'rpop', 'rpoplpush', 'rpush', 'rpushx', 'sadd', 'scan', 'scard', 'sdiff', 'sdiffstore', 'select',
'set', 'setbit', 'setex', 'setnx', 'setrange', 'shutdown', 'sinter', 'sinterstore', 'sismember',
'slaveof', 'slowlog', 'smembers', 'smove', 'sort', 'spop', 'srandmember', 'srem', 'sscan',
'strlen', 'subscribe', 'sunion', 'sunionstore', 'swapdb', 'touch', 'ttl', 'type', 'unlink',
'unsubscribe', 'wait', 'watch', 'zadd', 'zcard', 'zcount', 'zincrby', 'zinterstore', 'zlexcount',
'zrange', 'zrangebylex', 'zrangebyscore', 'zrank', 'zrem', 'zremrangebylex', 'zremrangebyrank',
'zremrangebyscore', 'zrevrange', 'zrevrangebylex', 'zrevrangebyscore', 'zrevrank', 'zscan',
'zscore', 'zunionstore'
]
op = op.lower()
if op not in commands:
raise ResponseError("Unknown Redis command called from Lua script")
special_cases = {
'del': FakeStrictRedis.delete,
'decrby': FakeStrictRedis.decr,
'incrby': FakeStrictRedis.incr
}
func = special_cases[op] if op in special_cases else getattr(FakeStrictRedis, op)
result = func(self, *args)
converter = getattr(func, '_lua_reply', self._convert_redis_result)
return converter(lua_runtime, result)
def _retrieve_data_from_sort(self, data, get):
if get is not None:
if isinstance(get, string_types):
get = [get]
new_data = []
for k in data:
for g in get:
single_item = self._get_single_item(k, g)
new_data.append(single_item)
data = new_data
return data
def _get_single_item(self, k, g):
g = to_bytes(g)
if b'*' in g:
g = g.replace(b'*', k)
if b'->' in g:
key, hash_key = g.split(b'->')
single_item = self._db.get(key, {}).get(hash_key)
else:
single_item = self._db.get(g)
elif b'#' in g:
single_item = k
else:
single_item = None
return single_item
def _strtod_key_func(self, arg):
# str()'ing the arg is important! Don't ever remove this.
arg = to_bytes(arg)
end = c_char_p()
val = _strtod(arg, pointer(end))
# real Redis also does an isnan check, not sure if
# that's needed here or not.
if end.value:
raise redis.ResponseError(
"One or more scores can't be converted into double")
else:
return val
def _sort_using_by_arg(self, data, by):
by = to_bytes(by)
def _by_key(arg):
key = by.replace(b'*', arg)
if b'->' in by:
key, hash_key = key.split(b'->')
return self._db.get(key, {}).get(hash_key)
else:
return self._db.get(key)
data.sort(key=_by_key)
def _get_list(self, name):
value = self._db.get(name, [])
if not isinstance(value, list):
raise redis.ResponseError(_WRONGTYPE_MSG)
return value
def _get_list_or_none(self, name):
"""Like _get_list, but default value is None"""
try:
value = self._db[name]
if not isinstance(value, list):
raise redis.ResponseError(_WRONGTYPE_MSG)
return value
except KeyError:
return None
def _setdefault_list(self, name):
value = self._db.setdefault(name, [])
if not isinstance(value, list):
raise redis.ResponseError(_WRONGTYPE_MSG)
return value
def lpush(self, name, *values):
self._setdefault_list(name)[0:0] = list(reversed(
[to_bytes(x) for x in values]))
return len(self._db[name])
def lrange(self, name, start, end):
if end == -1:
end = None
else:
end += 1
return self._get_list(name)[start:end]
def llen(self, name):
return len(self._get_list(name))
@_remove_empty
def lrem(self, name, count, value):
value = to_bytes(value)
a_list = self._get_list(name)
found = []
for i, el in enumerate(a_list):
if el == value:
found.append(i)
if count > 0:
indices_to_remove = found[:count]
elif count < 0:
indices_to_remove = found[count:]
else:
indices_to_remove = found
# Iterating in reverse order to ensure the indices
# remain valid during deletion.
for index in reversed(indices_to_remove):
del a_list[index]
return len(indices_to_remove)