memcache.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. #!/usr/bin/env python
  2. """
  3. client module for memcached (memory cache daemon)
  4. Overview
  5. ========
  6. See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
  7. Usage summary
  8. =============
  9. This should give you a feel for how this module operates::
  10. import memcache
  11. mc = memcache.Client(['127.0.0.1:11211'], debug=0)
  12. mc.set("some_key", "Some value")
  13. value = mc.get("some_key")
  14. mc.set("another_key", 3)
  15. mc.delete("another_key")
  16. mc.set("key", "1") # note that the key used for incr/decr must be a string.
  17. mc.incr("key")
  18. mc.decr("key")
  19. The standard way to use memcache with a database is like this::
  20. key = derive_key(obj)
  21. obj = mc.get(key)
  22. if not obj:
  23. obj = backend_api.get(...)
  24. mc.set(key, obj)
  25. # we now have obj, and future passes through this code
  26. # will use the object from the cache.
  27. Detailed Documentation
  28. ======================
  29. More detailed documentation is available in the L{Client} class.
  30. """
  31. import socket
  32. import sys
  33. import time
  34. import os
  35. import re
  36. import six
  37. try:
  38. import cPickle as pickle
  39. except ImportError:
  40. import pickle
  41. from binascii import crc32 # zlib version is not cross-platform
  42. def cmemcache_hash(key):
  43. return (((crc32(key) & 0xffffffff) >> 16) & 0x7fff) or 1
  44. serverHashFunction = cmemcache_hash
  45. def useOldServerHashFunction():
  46. """Use the old python-memcache server hash function."""
  47. global serverHashFunction
  48. serverHashFunction = crc32
  49. try:
  50. # noinspection PyUnresolvedReferences
  51. from zlib import compress, decompress
  52. _supports_compress = True
  53. except ImportError:
  54. _supports_compress = False
  55. # quickly define a decompress just in case we recv compressed data.
  56. def decompress(val):
  57. raise SocketRecvDataError("received compressed data but I don't support compression (import error)")
  58. try:
  59. from cStringIO import StringIO
  60. except ImportError:
  61. from StringIO import StringIO
  62. valid_key_chars_re = re.compile('[\x21-\x7e\x80-\xff]+$')
  63. # Original author: Evan Martin of Danga Interactive
  64. __author__ = "Sean Reifschneider <jafo-memcached@tummy.com>"
  65. __version__ = "1.53"
  66. __copyright__ = "Copyright (C) 2003 Danga Interactive"
  67. # http://en.wikipedia.org/wiki/Python_Software_Foundation_License
  68. __license__ = "Python Software Foundation License"
  69. SERVER_MAX_KEY_LENGTH = 250
  70. # Storing values larger than 1MB requires recompiling memcached. If you do,
  71. # this value can be changed by doing "memcache.SERVER_MAX_VALUE_LENGTH = N"
  72. # after importing this module.
  73. SERVER_MAX_VALUE_LENGTH = 1024 * 1024
  74. class SocketRecvDataError(Exception):
  75. pass
  76. class ConnectionDeadError(Exception):
  77. pass
  78. class MemcachedNoServerError(Exception):
  79. pass
  80. try:
  81. # Only exists in Python 2.4+
  82. from threading import local
  83. except ImportError:
  84. # TODO: add the pure-python local implementation
  85. class local(object):
  86. pass
  87. _DEAD_RETRY = 0 # number of seconds before retrying a dead server.
  88. _SOCKET_TIMEOUT = 3 # number of seconds before sockets timeout.
  89. class Client(local):
  90. """
  91. Object representing a pool of memcache servers.
  92. See L{memcache} for an overview.
  93. In all cases where a key is used, the key can be either:
  94. 1. A simple hashable type (string, integer, etc.).
  95. 2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid
  96. making this module calculate a hash value. You may prefer, for
  97. example, to keep all of a given user's objects on the same memcache
  98. server, so you could use the user's unique id as the hash value.
  99. @group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog
  100. @group Insertion: set, add, replace, set_multi
  101. @group Retrieval: get, get_multi
  102. @group Integers: incr, decr
  103. @group Removal: delete, delete_multi
  104. @sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog,\
  105. set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi
  106. """
  107. _FLAG_COMPRESSED = 1 << 3
  108. _FLAG_PICKLE = 1 << 0
  109. _FLAG_UNICODE = 1 << 6
  110. # to main compatibility with java memcache
  111. _FLAG_INTEGER = 1 << 2
  112. _FLAG_INTEGER_OLD = 1 << 1
  113. _FLAG_STRING = 1 << 5
  114. _FLAG_LONG = 1 << 14
  115. _SERVER_RETRIES = 10 # how many times to try finding a free server.
  116. # exceptions for Client
  117. class MemcachedKeyError(Exception):
  118. pass
  119. class MemcachedKeyLengthError(MemcachedKeyError):
  120. pass
  121. class MemcachedKeyCharacterError(MemcachedKeyError):
  122. pass
  123. class MemcachedKeyNoneError(MemcachedKeyError):
  124. pass
  125. class MemcachedKeyTypeError(MemcachedKeyError):
  126. pass
  127. class MemcachedStringEncodingError(Exception):
  128. pass
  129. def __init__(self, servers, debug=0, pickleProtocol=0,
  130. pickler=pickle.Pickler, unpickler=pickle.Unpickler,
  131. pload=None, pid=None,
  132. server_max_key_length=SERVER_MAX_KEY_LENGTH,
  133. server_max_value_length=SERVER_MAX_VALUE_LENGTH,
  134. dead_retry=_DEAD_RETRY, socket_timeout=_SOCKET_TIMEOUT,
  135. cache_cas=False, flush_on_reconnect=0, check_keys=True):
  136. """
  137. Create a new Client object with the given list of servers.
  138. @param servers: C{servers} is passed to L{set_servers}.
  139. @param debug: whether to display error messages when a server can't be
  140. contacted.
  141. @param pickleProtocol: number to mandate protocol used by (c)Pickle.
  142. @param pickler: optional override of default Pickler to allow subclassing.
  143. @param unpickler: optional override of default Unpickler to allow subclassing.
  144. @param pload: optional persistent_load function to call on pickle loading.
  145. Useful for cPickle since subclassing isn't allowed.
  146. @param pid: optional persistent_id function to call on pickle storing.
  147. Useful for cPickle since subclassing isn't allowed.
  148. @param dead_retry: number of seconds before retrying a blacklisted
  149. server. Default to 30 s.
  150. @param socket_timeout: timeout in seconds for all calls to a server. Defaults
  151. to 3 seconds.
  152. @param cache_cas: (default False) If true, cas operations will be
  153. cached. WARNING: This cache is not expired internally, if you have
  154. a long-running process you will need to expire it manually via
  155. client.reset_cas(), or the cache can grow unlimited.
  156. @param server_max_key_length: (default SERVER_MAX_KEY_LENGTH)
  157. Data that is larger than this will not be sent to the server.
  158. @param server_max_value_length: (default SERVER_MAX_VALUE_LENGTH)
  159. Data that is larger than this will not be sent to the server.
  160. @param flush_on_reconnect: optional flag which prevents a scenario that
  161. can cause stale data to be read: If there's more than one memcached
  162. server and the connection to one is interrupted, keys that mapped to
  163. that server will get reassigned to another. If the first server comes
  164. back, those keys will map to it again. If it still has its data, get()s
  165. can read stale data that was overwritten on another server. This flag
  166. is off by default for backwards compatibility.
  167. @param check_keys: (default True) If True, the key is checked to
  168. ensure it is the correct length and composed of the right characters.
  169. """
  170. local.__init__(self)
  171. self.debug = debug
  172. self.dead_retry = dead_retry
  173. self.socket_timeout = socket_timeout
  174. self.flush_on_reconnect = flush_on_reconnect
  175. self.set_servers(servers)
  176. self.stats = {}
  177. self.cache_cas = cache_cas
  178. self.reset_cas()
  179. self.do_check_key = check_keys
  180. # Allow users to modify pickling/unpickling behavior
  181. self.pickleProtocol = pickleProtocol
  182. self.pickler = pickler
  183. self.unpickler = unpickler
  184. self.persistent_load = pload
  185. self.persistent_id = pid
  186. self.server_max_key_length = server_max_key_length
  187. self.server_max_value_length = server_max_value_length
  188. # figure out the pickler style
  189. file = StringIO()
  190. try:
  191. pickler = self.pickler(file, protocol=self.pickleProtocol)
  192. self.picklerIsKeyword = True
  193. except TypeError:
  194. self.picklerIsKeyword = False
  195. def reset_cas(self):
  196. """
  197. Reset the cas cache. This is only used if the Client() object
  198. was created with "cache_cas=True". If used, this cache does not
  199. expire internally, so it can grow unbounded if you do not clear it
  200. yourself.
  201. """
  202. self.cas_ids = {}
  203. def set_servers(self, servers):
  204. """
  205. Set the pool of servers used by this client.
  206. @param servers: an array of servers.
  207. Servers can be passed in two forms:
  208. 1. Strings of the form C{"host:port"}, which implies a default weight of 1.
  209. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is
  210. an integer weight value.
  211. """
  212. self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry,
  213. socket_timeout=self.socket_timeout,
  214. flush_on_reconnect=self.flush_on_reconnect)
  215. for s in servers]
  216. self._init_buckets()
  217. def get_stats(self, stat_args=None):
  218. '''Get statistics from each of the servers.
  219. @param stat_args: Additional arguments to pass to the memcache
  220. "stats" command.
  221. @return: A list of tuples ( server_identifier, stats_dictionary ).
  222. The dictionary contains a number of name/value pairs specifying
  223. the name of the status field and the string value associated with
  224. it. The values are not converted from strings.
  225. '''
  226. data = []
  227. for s in self.servers:
  228. if not s.connect(): continue
  229. if s.family == socket.AF_INET:
  230. name = '%s:%s (%s)' % (s.ip, s.port, s.weight)
  231. elif s.family == socket.AF_INET6:
  232. name = '[%s]:%s (%s)' % (s.ip, s.port, s.weight)
  233. else:
  234. name = 'unix:%s (%s)' % (s.address, s.weight)
  235. if not stat_args:
  236. s.send_cmd('stats')
  237. else:
  238. s.send_cmd('stats ' + stat_args)
  239. serverData = {}
  240. data.append((name, serverData))
  241. readline = s.readline
  242. while 1:
  243. line = readline()
  244. if not line or line.strip() == 'END': break
  245. stats = line.split(' ', 2)
  246. serverData[stats[1]] = stats[2]
  247. return (data)
  248. def get_slabs(self):
  249. data = []
  250. for s in self.servers:
  251. if not s.connect(): continue
  252. if s.family == socket.AF_INET:
  253. name = '%s:%s (%s)' % (s.ip, s.port, s.weight)
  254. elif s.family == socket.AF_INET6:
  255. name = '[%s]:%s (%s)' % (s.ip, s.port, s.weight)
  256. else:
  257. name = 'unix:%s (%s)' % (s.address, s.weight)
  258. serverData = {}
  259. data.append((name, serverData))
  260. s.send_cmd('stats items')
  261. readline = s.readline
  262. while 1:
  263. line = readline()
  264. if not line or line.strip() == 'END': break
  265. item = line.split(' ', 2)
  266. # 0 = STAT, 1 = ITEM, 2 = Value
  267. slab = item[1].split(':', 2)
  268. # 0 = items, 1 = Slab #, 2 = Name
  269. if slab[1] not in serverData:
  270. serverData[slab[1]] = {}
  271. serverData[slab[1]][slab[2]] = item[2]
  272. return data
  273. def flush_all(self):
  274. """Expire all data in memcache servers that are reachable."""
  275. for s in self.servers:
  276. if not s.connect(): continue
  277. s.flush()
  278. def debuglog(self, str):
  279. if self.debug:
  280. sys.stderr.write("MemCached: %s\n" % str)
  281. def _statlog(self, func):
  282. if func not in self.stats:
  283. self.stats[func] = 1
  284. else:
  285. self.stats[func] += 1
  286. def forget_dead_hosts(self):
  287. """
  288. Reset every host in the pool to an "alive" state.
  289. """
  290. for s in self.servers:
  291. s.deaduntil = 0
  292. def _init_buckets(self):
  293. self.buckets = []
  294. for server in self.servers:
  295. for i in range(server.weight):
  296. self.buckets.append(server)
  297. def _get_server(self, key):
  298. if isinstance(key, tuple):
  299. serverhash, key = key
  300. else:
  301. serverhash = serverHashFunction(key)
  302. for i in range(Client._SERVER_RETRIES):
  303. server = self.buckets[serverhash % len(self.buckets)]
  304. if server.connect():
  305. # print "(using server %s)" % server,
  306. return server, key
  307. serverhash = serverHashFunction(str(serverhash) + str(i))
  308. return None, None
  309. def disconnect_all(self):
  310. for s in self.servers:
  311. s.close_socket()
  312. def delete_multi(self, keys, time=0, key_prefix=''):
  313. '''
  314. Delete multiple keys in the memcache doing just one query.
  315. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
  316. >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
  317. 1
  318. >>> mc.delete_multi(['key1', 'key2'])
  319. 1
  320. >>> mc.get_multi(['key1', 'key2']) == {}
  321. 1
  322. This method is recommended over iterated regular L{delete}s as it reduces total latency, since
  323. your app doesn't have to wait for each round-trip of L{delete} before sending
  324. the next one.
  325. @param keys: An iterable of keys to clear
  326. @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay.
  327. @param key_prefix: Optional string to prepend to each key when sending to memcache.
  328. See docs for L{get_multi} and L{set_multi}.
  329. @return: 1 if no failure in communication with any memcacheds.
  330. @rtype: int
  331. '''
  332. self._statlog('delete_multi')
  333. server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
  334. # send out all requests on each server before reading anything
  335. dead_servers = []
  336. rc = 1
  337. for server in server_keys.iterkeys():
  338. bigcmd = []
  339. write = bigcmd.append
  340. if time != None:
  341. for key in server_keys[server]: # These are mangled keys
  342. write("delete %s %d\r\n" % (key, time))
  343. else:
  344. for key in server_keys[server]: # These are mangled keys
  345. write("delete %s\r\n" % key)
  346. try:
  347. server.send_cmds(''.join(bigcmd))
  348. except socket.error, msg:
  349. rc = 0
  350. if isinstance(msg, tuple): msg = msg[1]
  351. server.mark_dead(msg)
  352. dead_servers.append(server)
  353. # if any servers died on the way, don't expect them to respond.
  354. for server in dead_servers:
  355. del server_keys[server]
  356. for server, keys in server_keys.iteritems():
  357. try:
  358. for key in keys:
  359. server.expect("DELETED")
  360. except socket.error, msg:
  361. if isinstance(msg, tuple): msg = msg[1]
  362. server.mark_dead(msg)
  363. rc = 0
  364. return rc
  365. def delete(self, key, time=0):
  366. '''Deletes a key from the memcache.
  367. @return: 0 on server or socket error or no response. True on DELETED. False on NOT_FOUND.
  368. @param time: number of seconds any subsequent set / update commands
  369. should fail. Defaults to None for no delay.
  370. @rtype: int
  371. '''
  372. if self.do_check_key:
  373. self.check_key(key)
  374. server, key = self._get_server(key)
  375. if not server:
  376. return 0
  377. self._statlog('delete')
  378. if time != None and time != 0:
  379. cmd = "delete %s %d" % (key, time)
  380. else:
  381. cmd = "delete %s" % key
  382. try:
  383. server.send_cmd(cmd)
  384. line = server.readline()
  385. if line and line.strip()== 'DELETED': return True
  386. if line and line.strip() == 'NOT_FOUND': return False
  387. self.debuglog('Delete<key=%s> expected DELETED or NOT_FOUND, got: %s'
  388. % (key, repr(line)))
  389. except socket.error, msg:
  390. if isinstance(msg, tuple): msg = msg[1]
  391. server.mark_dead(msg)
  392. return 0
  393. def incr(self, key, delta=1):
  394. """
  395. Sends a command to the server to atomically increment the value
  396. for C{key} by C{delta}, or by 1 if C{delta} is unspecified.
  397. Returns None if C{key} doesn't exist on server, otherwise it
  398. returns the new value after incrementing.
  399. Note that the value for C{key} must already exist in the memcache,
  400. and it must be the string representation of an integer.
  401. >>> mc.set("counter", "20") # returns 1, indicating success
  402. 1
  403. >>> mc.incr("counter")
  404. 21
  405. >>> mc.incr("counter")
  406. 22
  407. Overflow on server is not checked. Be aware of values approaching
  408. 2**32. See L{decr}.
  409. @param delta: Integer amount to increment by (should be zero or greater).
  410. @return: New value after incrementing.
  411. @rtype: int
  412. """
  413. return self._incrdecr("incr", key, delta)
  414. def decr(self, key, delta=1):
  415. """
  416. Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and
  417. new values are capped at 0. If server value is 1, a decrement of 2
  418. returns 0, not -1.
  419. @param delta: Integer amount to decrement by (should be zero or greater).
  420. @return: New value after decrementing or None on error.
  421. @rtype: int
  422. """
  423. return self._incrdecr("decr", key, delta)
  424. def _incrdecr(self, cmd, key, delta):
  425. if self.do_check_key:
  426. self.check_key(key)
  427. server, key = self._get_server(key)
  428. if not server:
  429. return None
  430. self._statlog(cmd)
  431. cmd = "%s %s %d" % (cmd, key, delta)
  432. try:
  433. server.send_cmd(cmd)
  434. line = server.readline()
  435. if line == None or line.strip() == 'NOT_FOUND': return None
  436. return int(line)
  437. except socket.error, msg:
  438. if isinstance(msg, tuple): msg = msg[1]
  439. server.mark_dead(msg)
  440. return None
  441. def add(self, key, val, time=0, min_compress_len=0):
  442. '''
  443. Add new key with value.
  444. Like L{set}, but only stores in memcache if the key doesn't already exist.
  445. @return: Nonzero on success.
  446. @rtype: int
  447. '''
  448. return self._set("add", key, val, time, min_compress_len)
  449. def append(self, key, val, time=0, min_compress_len=0):
  450. """Append the value to the end of the existing key's value.
  451. Only stores in memcache if key already exists.
  452. Also see L{prepend}.
  453. @return: Nonzero on success.
  454. @rtype: int
  455. """
  456. return self._set("append", key, val, time, min_compress_len)
  457. def prepend(self, key, val, time=0, min_compress_len=0):
  458. """Prepend the value to the beginning of the existing key's value.
  459. Only stores in memcache if key already exists.
  460. Also see L{append}.
  461. @return: Nonzero on success.
  462. @rtype: int
  463. """
  464. return self._set("prepend", key, val, time, min_compress_len)
  465. def replace(self, key, val, time=0, min_compress_len=0):
  466. """Replace existing key with value.
  467. Like L{set}, but only stores in memcache if the key already exists.
  468. The opposite of L{add}.
  469. @return: Nonzero on success.
  470. @rtype: int
  471. """
  472. return self._set("replace", key, val, time, min_compress_len)
  473. def set(self, key, val, time=0, min_compress_len=0):
  474. """Unconditionally sets a key to a given value in the memcache.
  475. The C{key} can optionally be an tuple, with the first element
  476. being the server hash value and the second being the key.
  477. If you want to avoid making this module calculate a hash value.
  478. You may prefer, for example, to keep all of a given user's objects
  479. on the same memcache server, so you could use the user's unique
  480. id as the hash value.
  481. @return: Nonzero on success.
  482. @rtype: int
  483. @param time: Tells memcached the time which this value should expire, either
  484. as a delta number of seconds, or an absolute unix time-since-the-epoch
  485. value. See the memcached protocol docs section "Storage Commands"
  486. for more info on <exptime>. We default to 0 == cache forever.
  487. @param min_compress_len: The threshold length to kick in auto-compression
  488. of the value using the zlib.compress() routine. If the value being cached is
  489. a string, then the length of the string is measured, else if the value is an
  490. object, then the length of the pickle result is measured. If the resulting
  491. attempt at compression yeilds a larger string than the input, then it is
  492. discarded. For backwards compatability, this parameter defaults to 0,
  493. indicating don't ever try to compress.
  494. """
  495. return self._set("set", key, val, time, min_compress_len)
  496. def cas(self, key, val, time=0, min_compress_len=0):
  497. """Sets a key to a given value in the memcache if it hasn't been
  498. altered since last fetched. (See L{gets}).
  499. The C{key} can optionally be an tuple, with the first element
  500. being the server hash value and the second being the key.
  501. If you want to avoid making this module calculate a hash value.
  502. You may prefer, for example, to keep all of a given user's objects
  503. on the same memcache server, so you could use the user's unique
  504. id as the hash value.
  505. @return: Nonzero on success.
  506. @rtype: int
  507. @param time: Tells memcached the time which this value should expire,
  508. either as a delta number of seconds, or an absolute unix
  509. time-since-the-epoch value. See the memcached protocol docs section
  510. "Storage Commands" for more info on <exptime>. We default to
  511. 0 == cache forever.
  512. @param min_compress_len: The threshold length to kick in
  513. auto-compression of the value using the zlib.compress() routine. If
  514. the value being cached is a string, then the length of the string is
  515. measured, else if the value is an object, then the length of the
  516. pickle result is measured. If the resulting attempt at compression
  517. yeilds a larger string than the input, then it is discarded. For
  518. backwards compatability, this parameter defaults to 0, indicating
  519. don't ever try to compress.
  520. :type val: object
  521. :param key:
  522. """
  523. return self._set("cas", key, val, time, min_compress_len)
  524. def _map_and_prefix_keys(self, key_iterable, key_prefix):
  525. """Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of
  526. prefixed key -> original key.
  527. """
  528. # Check it just once ...
  529. key_extra_len = len(key_prefix)
  530. if key_prefix and self.do_check_key:
  531. self.check_key(key_prefix)
  532. # server (_Host) -> list of unprefixed server keys in mapping
  533. server_keys = {}
  534. prefixed_to_orig_key = {}
  535. # build up a list for each server of all the keys we want.
  536. for orig_key in key_iterable:
  537. if isinstance(orig_key, tuple):
  538. # Tuple of hashvalue, key ala _get_server(). Caller is essentially telling us what server to stuff this on.
  539. # Ensure call to _get_server gets a Tuple as well.
  540. str_orig_key = str(orig_key[1])
  541. server, key = self._get_server((orig_key[0],
  542. key_prefix + str_orig_key)) # Gotta pre-mangle key before hashing to a server. Returns the mangled key.
  543. else:
  544. str_orig_key = str(orig_key) # set_multi supports int / long keys.
  545. server, key = self._get_server(key_prefix + str_orig_key)
  546. # Now check to make sure key length is proper ...
  547. if self.do_check_key:
  548. self.check_key(str_orig_key, key_extra_len=key_extra_len)
  549. if not server:
  550. continue
  551. if server not in server_keys:
  552. server_keys[server] = []
  553. server_keys[server].append(key)
  554. prefixed_to_orig_key[key] = orig_key
  555. return server_keys, prefixed_to_orig_key
  556. def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0):
  557. """
  558. Sets multiple keys in the memcache doing just one query.
  559. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
  560. >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
  561. 1
  562. This method is recommended over regular L{set} as it lowers the
  563. number of total packets flying around your network, reducing
  564. total latency, since your app doesn't have to wait for each
  565. round-trip of L{set} before sending the next one.
  566. @param mapping: A dict of key/value pairs to set.
  567. @param time: Tells memcached the time which this value should
  568. expire, either as a delta number of seconds, or an absolute
  569. unix time-since-the-epoch value. See the memcached protocol
  570. docs section "Storage Commands" for more info on <exptime>. We
  571. default to 0 == cache forever.
  572. @param key_prefix: Optional string to prepend to each key when
  573. sending to memcache. Allows you to efficiently stuff these
  574. keys into a pseudo-namespace in memcache:
  575. >>> notset_keys = mc.set_multi(
  576. ... {'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
  577. >>> len(notset_keys) == 0
  578. True
  579. >>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
  580. True
  581. Causes key 'subspace_key1' and 'subspace_key2' to be
  582. set. Useful in conjunction with a higher-level layer which
  583. applies namespaces to data in memcache. In this case, the
  584. return result would be the list of notset original keys,
  585. prefix not applied.
  586. @param min_compress_len: The threshold length to kick in
  587. auto-compression of the value using the zlib.compress()
  588. routine. If the value being cached is a string, then
  589. the length of the string is measured, else if the value
  590. is an object, then the length of the pickle result is
  591. measured. If the resulting attempt at compression yeilds
  592. a larger string than the input, then it is discarded. For
  593. backwards compatability, this parameter defaults to 0,
  594. indicating don't ever try to compress.
  595. @return: List of keys which failed to be stored [ memcache out of
  596. memory, etc. ].
  597. @rtype: list
  598. """
  599. self._statlog('set_multi')
  600. server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(
  601. mapping.iterkeys(), key_prefix)
  602. # send out all requests on each server before reading anything
  603. dead_servers = []
  604. notstored = [] # original keys.
  605. for server in server_keys.iterkeys():
  606. bigcmd = []
  607. write = bigcmd.append
  608. try:
  609. for key in server_keys[server]: # These are mangled keys
  610. store_info = self._val_to_store_info(
  611. mapping[prefixed_to_orig_key[key]],
  612. min_compress_len)
  613. if store_info:
  614. write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0],
  615. time, store_info[1], store_info[2]))
  616. else:
  617. notstored.append(prefixed_to_orig_key[key])
  618. self.debuglog('cmd = {}\n'.format(''.join(bigcmd)))
  619. server.send_cmds(''.join(bigcmd))
  620. except socket.error, msg:
  621. if isinstance(msg, tuple): msg = msg[1]
  622. server.mark_dead(msg)
  623. dead_servers.append(server)
  624. # if any servers died on the way, don't expect them to respond.
  625. for server in dead_servers:
  626. del server_keys[server]
  627. # short-circuit if there are no servers, just return all keys
  628. if not server_keys: return (mapping.keys())
  629. for server, keys in server_keys.iteritems():
  630. try:
  631. for key in keys:
  632. if server.readline() == 'STORED':
  633. continue
  634. else:
  635. notstored.append(prefixed_to_orig_key[key]) # un-mangle.
  636. except (SocketRecvDataError, socket.error), msg:
  637. if isinstance(msg, tuple): msg = msg[1]
  638. server.mark_dead(msg)
  639. return notstored
  640. def _val_to_store_info(self, val, min_compress_len):
  641. """
  642. Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself.
  643. """
  644. flags = 0
  645. if isinstance(val, str):
  646. flags |= Client._FLAG_STRING
  647. elif isinstance(val, six.text_type):
  648. flags |= Client._FLAG_UNICODE
  649. val = val.encode('utf8')
  650. elif isinstance(val, int):
  651. flags |= Client._FLAG_INTEGER
  652. val = "%d" % val
  653. # force no attempt to compress this silly string.
  654. min_compress_len = 0
  655. elif isinstance(val, long):
  656. flags |= Client._FLAG_LONG
  657. val = "%d" % val
  658. # force no attempt to compress this silly string.
  659. min_compress_len = 0
  660. else:
  661. flags |= Client._FLAG_PICKLE
  662. file = StringIO()
  663. if self.picklerIsKeyword:
  664. pickler = self.pickler(file, protocol=self.pickleProtocol)
  665. else:
  666. pickler = self.pickler(file, self.pickleProtocol)
  667. if self.persistent_id:
  668. pickler.persistent_id = self.persistent_id
  669. pickler.dump(val)
  670. val = file.getvalue()
  671. lv = len(val)
  672. # We should try to compress if min_compress_len > 0 and we could
  673. # import zlib and this string is longer than our min threshold.
  674. if min_compress_len and _supports_compress and lv > min_compress_len:
  675. comp_val = compress(val)
  676. # Only retain the result if the compression result is smaller
  677. # than the original.
  678. if len(comp_val) < lv:
  679. flags |= Client._FLAG_COMPRESSED
  680. val = comp_val
  681. # silently do not store if value length exceeds maximum
  682. if self.server_max_value_length != 0 and \
  683. len(val) > self.server_max_value_length: return (0)
  684. return flags, len(val), val
  685. def _set(self, cmd, key, val, time, min_compress_len=0):
  686. if self.do_check_key:
  687. self.check_key(key)
  688. server, key = self._get_server(key)
  689. if not server:
  690. return 0
  691. def _unsafe_set():
  692. self._statlog(cmd)
  693. store_info = self._val_to_store_info(val, min_compress_len)
  694. if not store_info: return 0
  695. if cmd == 'cas':
  696. if key not in self.cas_ids:
  697. return self._set('set', key, val, time, min_compress_len)
  698. fullcmd = "%s %s %d %d %d %d\r\n%s" % (
  699. cmd, key, store_info[0], time, store_info[1],
  700. self.cas_ids[key], store_info[2])
  701. else:
  702. fullcmd = "%s %s %d %d %d\r\n%s" % (
  703. cmd, key, store_info[0], time, store_info[1], store_info[2])
  704. try:
  705. server.send_cmd(fullcmd)
  706. self.debuglog('cmd = {}\n'.format(fullcmd))
  707. return (server.expect("STORED", raise_exception=True)
  708. == "STORED")
  709. except socket.error, msg:
  710. if isinstance(msg, tuple): msg = msg[1]
  711. server.mark_dead(msg)
  712. return 0
  713. try:
  714. return _unsafe_set()
  715. except ConnectionDeadError:
  716. # retry once
  717. try:
  718. if server._get_socket():
  719. return _unsafe_set()
  720. except (ConnectionDeadError, socket.error), msg:
  721. server.mark_dead(msg)
  722. return 0
  723. def _get(self, cmd, key, ignore_exc = True):
  724. if self.do_check_key:
  725. self.check_key(key)
  726. server, key = self._get_server(key)
  727. if not server:
  728. if not ignore_exc:
  729. raise MemcachedNoServerError()
  730. else:
  731. return None
  732. def _unsafe_get(ignore_exc = True):
  733. self._statlog(cmd)
  734. try:
  735. server.send_cmd("%s %s" % (cmd, key))
  736. rkey = flags = rlen = cas_id = None
  737. if cmd == 'gets':
  738. rkey, flags, rlen, cas_id, = self._expect_cas_value(server,
  739. raise_exception = True)
  740. if rkey and self.cache_cas:
  741. self.cas_ids[rkey] = cas_id
  742. else:
  743. rkey, flags, rlen, = self._expectvalue(server,
  744. raise_exception = True)
  745. if not rkey:
  746. return None
  747. try:
  748. value = self._recv_value(server, flags, rlen)
  749. self.debuglog(
  750. 'server = {}; flags = {}; rlen = {}; key = {}; value = {}\n'.format(
  751. server, flags, rlen, rkey, value))
  752. finally:
  753. server.expect("END", raise_exception = True)
  754. except (SocketRecvDataError, socket.error), msg:
  755. if isinstance(msg, tuple): msg = msg[1]
  756. server.mark_dead(msg)
  757. if not ignore_exc:
  758. raise
  759. else:
  760. return None
  761. return value
  762. try:
  763. return _unsafe_get(ignore_exc = ignore_exc)
  764. except ConnectionDeadError:
  765. # retry once
  766. try:
  767. if server.connect() == 0:
  768. if not ignore_exc:
  769. raise MemcachedNoServerError()
  770. else:
  771. return None
  772. except (socket.error), msg:
  773. server.mark_dead(msg)
  774. if not ignore_exc:
  775. raise
  776. else:
  777. return None
  778. try:
  779. return _unsafe_get(ignore_exc = ignore_exc)
  780. except (ConnectionDeadError), msg:
  781. server.mark_dead(msg)
  782. if not ignore_exc:
  783. raise
  784. else:
  785. return None
  786. def get(self, key, ignore_exc = True):
  787. '''Retrieves a key from the memcache.
  788. @return: The value or None.
  789. '''
  790. return self._get('get', key, ignore_exc)
  791. def gets(self, key, ignore_exc = True):
  792. '''Retrieves a key from the memcache. Used in conjunction with 'cas'.
  793. @return: The value or None.
  794. '''
  795. return self._get('gets', key, ignore_exc)
  796. def get_multi(self, keys, key_prefix=''):
  797. '''
  798. Retrieves multiple keys from the memcache doing just one query.
  799. >>> success = mc.set("foo", "bar")
  800. >>> success = mc.set("baz", 42)
  801. >>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
  802. 1
  803. >>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
  804. 1
  805. This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'.
  806. >>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2}
  807. 1
  808. get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields.
  809. They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix.
  810. In this mode, the key_prefix could be a table name, and the key itself a db primary key number.
  811. >>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
  812. 1
  813. >>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
  814. 1
  815. This method is recommended over regular L{get} as it lowers the number of
  816. total packets flying around your network, reducing total latency, since
  817. your app doesn't have to wait for each round-trip of L{get} before sending
  818. the next one.
  819. See also L{set_multi}.
  820. @param keys: An array of keys.
  821. @param key_prefix: A string to prefix each key when we communicate with memcache.
  822. Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
  823. @return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present.
  824. '''
  825. self._statlog('get_multi')
  826. server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
  827. # send out all requests on each server before reading anything
  828. dead_servers = []
  829. for server in server_keys.iterkeys():
  830. try:
  831. server.send_cmd("get %s" % " ".join(server_keys[server]))
  832. except socket.error, msg:
  833. if isinstance(msg, tuple): msg = msg[1]
  834. server.mark_dead(msg)
  835. dead_servers.append(server)
  836. # if any servers died on the way, don't expect them to respond.
  837. for server in dead_servers:
  838. del server_keys[server]
  839. retvals = {}
  840. for server in server_keys.iterkeys():
  841. try:
  842. line = server.readline()
  843. while line and line != 'END':
  844. rkey, flags, rlen = self._expectvalue(server, line)
  845. # Bo Yang reports that this can sometimes be None
  846. if rkey is not None:
  847. val = self._recv_value(server, flags, rlen)
  848. self.debuglog(
  849. 'server = {}; flags = {}; rlen = {}; key = {}; value = {}\n'.format(
  850. server, flags, rlen, rkey, val))
  851. retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key.
  852. line = server.readline()
  853. except (SocketRecvDataError, socket.error), msg:
  854. if isinstance(msg, tuple): msg = msg[1]
  855. server.mark_dead(msg)
  856. return retvals
  857. def _expect_cas_value(self, server, line=None, raise_exception=False):
  858. if not line:
  859. line = server.readline(raise_exception)
  860. if line and line[:5] == 'VALUE':
  861. resp, rkey, flags, len, cas_id = line.split()
  862. return rkey, int(flags), int(len), int(cas_id)
  863. else:
  864. return None, None, None, None
  865. def _expectvalue(self, server, line = None, raise_exception = False):
  866. if not line:
  867. line = server.readline(raise_exception)
  868. if line and line[:5] == 'VALUE':
  869. resp, rkey, flags, len = line.split()
  870. flags = int(flags)
  871. rlen = int(len)
  872. return rkey, flags, rlen
  873. else:
  874. return None, None, None
  875. def _recv_value(self, server, flags, rlen):
  876. rlen += 2 # include \r\n
  877. buf = server.recv(rlen)
  878. if len(buf) != rlen:
  879. raise SocketRecvDataError("received %d bytes when expecting %d"
  880. % (len(buf), rlen))
  881. # self.debuglog('raw:server = {}; flags = {}; rlen = {}; buf = {}\n'.format(server, flags, rlen, buf))
  882. if len(buf) == rlen:
  883. buf = buf[:-2] # strip \r\n
  884. if flags & Client._FLAG_COMPRESSED:
  885. buf = decompress(buf)
  886. flags &= ~Client._FLAG_COMPRESSED
  887. if flags == 0 or flags == Client._FLAG_STRING:
  888. val = buf
  889. elif flags & Client._FLAG_UNICODE:
  890. val = buf.decode('utf8')
  891. elif flags & Client._FLAG_INTEGER:
  892. val = int(buf)
  893. elif flags & Client._FLAG_INTEGER_OLD:
  894. val = int(buf)
  895. elif flags & Client._FLAG_LONG:
  896. val = long(buf)
  897. elif flags & Client._FLAG_PICKLE:
  898. try:
  899. file = StringIO(buf)
  900. unpickler = self.unpickler(file)
  901. if self.persistent_load:
  902. unpickler.persistent_load = self.persistent_load
  903. val = unpickler.load()
  904. except Exception, e:
  905. self.debuglog('Pickle error: %s\n' % e)
  906. return None
  907. else:
  908. self.debuglog("unknown flags on get: %x\n" % flags)
  909. return buf
  910. return val
  911. def check_key(self, key, key_extra_len=0):
  912. """Checks sanity of key. Fails if:
  913. Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength).
  914. Contains control characters (Raises MemcachedKeyCharacterError).
  915. Is not a string (Raises MemcachedStringEncodingError)
  916. Is an unicode string (Raises MemcachedStringEncodingError)
  917. Is not a string (Raises MemcachedKeyError)
  918. Is None (Raises MemcachedKeyError)
  919. """
  920. if isinstance(key, tuple): key = key[1]
  921. if not key:
  922. raise Client.MemcachedKeyNoneError("Key is None")
  923. if isinstance(key, unicode):
  924. raise Client.MemcachedStringEncodingError(
  925. "Keys must be str()'s, not unicode. Convert your unicode "
  926. "strings using mystring.encode(charset)!")
  927. if not isinstance(key, str):
  928. raise Client.MemcachedKeyTypeError("Key must be str()'s")
  929. if isinstance(key, basestring):
  930. if self.server_max_key_length != 0 and \
  931. len(key) + key_extra_len > self.server_max_key_length:
  932. raise Client.MemcachedKeyLengthError("Key length is > %s"
  933. % self.server_max_key_length)
  934. if not valid_key_chars_re.match(key):
  935. raise Client.MemcachedKeyCharacterError(
  936. "Control characters not allowed")
  937. class _Host(object):
  938. def __init__(self, host, debug=0, dead_retry=_DEAD_RETRY,
  939. socket_timeout=_SOCKET_TIMEOUT, flush_on_reconnect=0):
  940. self.dead_retry = dead_retry
  941. self.socket_timeout = socket_timeout
  942. self.debug = debug
  943. self.flush_on_reconnect = flush_on_reconnect
  944. if isinstance(host, tuple):
  945. host, self.weight = host
  946. else:
  947. self.weight = 1
  948. # parse the connection string
  949. m = re.match(r'^(?P<proto>unix):(?P<path>.*)$', host)
  950. if not m:
  951. m = re.match(r'^(?P<proto>inet6):'
  952. r'\[(?P<host>[^\[\]]+)\](:(?P<port>[0-9]+))?$', host)
  953. if not m:
  954. m = re.match(r'^(?P<proto>inet):'
  955. r'(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host)
  956. if not m: m = re.match(r'^(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host)
  957. if not m:
  958. raise ValueError('Unable to parse connection string: "%s"' % host)
  959. hostData = m.groupdict()
  960. if hostData.get('proto') == 'unix':
  961. self.family = socket.AF_UNIX
  962. self.address = hostData['path']
  963. elif hostData.get('proto') == 'inet6':
  964. self.family = socket.AF_INET6
  965. self.ip = hostData['host']
  966. self.port = int(hostData.get('port') or 11211)
  967. self.address = (self.ip, self.port)
  968. else:
  969. self.family = socket.AF_INET
  970. self.ip = hostData['host']
  971. self.port = int(hostData.get('port') or 11211)
  972. self.address = (self.ip, self.port)
  973. self.deaduntil = 0
  974. self.socket = None
  975. self.flush_on_next_connect = 0
  976. self.buffer = ''
  977. def debuglog(self, str):
  978. if self.debug:
  979. sys.stderr.write("MemCached: %s\n" % str)
  980. def _check_dead(self):
  981. if self.deaduntil and self.deaduntil > time.time():
  982. return 1
  983. self.deaduntil = 0
  984. return 0
  985. def connect(self):
  986. if self._get_socket():
  987. return 1
  988. return 0
  989. def mark_dead(self, reason):
  990. self.debuglog("MemCache: %s: %s. Marking dead." % (self, reason))
  991. self.deaduntil = time.time() + self.dead_retry
  992. if self.flush_on_reconnect:
  993. self.flush_on_next_connect = 1
  994. self.close_socket()
  995. def _get_socket(self):
  996. if self._check_dead():
  997. self.debuglog("check dead is True. socket return None.")
  998. return None
  999. if self.socket:
  1000. return self.socket
  1001. s = socket.socket(self.family, socket.SOCK_STREAM)
  1002. try:
  1003. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  1004. except:
  1005. pass
  1006. if hasattr(s, 'settimeout'): s.settimeout(self.socket_timeout)
  1007. try:
  1008. s.connect(self.address)
  1009. except socket.timeout, msg:
  1010. self.mark_dead("connect(timeout): %s" % msg)
  1011. return None
  1012. except socket.error, msg:
  1013. if isinstance(msg, tuple): msg = msg[1]
  1014. self.mark_dead("connect(error): %s" % msg[1])
  1015. return None
  1016. self.socket = s
  1017. self.buffer = ''
  1018. if self.flush_on_next_connect:
  1019. self.flush()
  1020. self.flush_on_next_connect = 0
  1021. return s
  1022. def close_socket(self):
  1023. if self.socket:
  1024. self.socket.close()
  1025. self.socket = None
  1026. def send_cmd(self, cmd):
  1027. self.socket.sendall(cmd + '\r\n')
  1028. def send_cmds(self, cmds):
  1029. """ cmds already has trailing \r\n's applied """
  1030. self.socket.sendall(cmds)
  1031. def readline(self, raise_exception=False):
  1032. """Read a line and return it. If "raise_exception" is set,
  1033. raise _ConnectionDeadError if the read fails, otherwise return
  1034. an empty string.
  1035. """
  1036. buf = self.buffer
  1037. if self.socket:
  1038. recv = self.socket.recv
  1039. else:
  1040. recv = lambda bufsize: ''
  1041. while True:
  1042. index = buf.find('\r\n')
  1043. if index >= 0:
  1044. break
  1045. data = recv(4096)
  1046. if not data:
  1047. # connection close, let's kill it and raise
  1048. self.mark_dead('connection closed in readline()')
  1049. if raise_exception:
  1050. raise ConnectionDeadError()
  1051. else:
  1052. return ''
  1053. buf += data
  1054. self.buffer = buf[index + 2:]
  1055. return buf[:index]
  1056. def expect(self, text, raise_exception=False):
  1057. line = self.readline(raise_exception)
  1058. if line != text:
  1059. self.debuglog("while expecting '%s', got unexpected response '%s'"
  1060. % (text, line))
  1061. return line
  1062. def recv(self, rlen):
  1063. self_socket_recv = self.socket.recv
  1064. buf = self.buffer
  1065. while len(buf) < rlen:
  1066. foo = self_socket_recv(max(rlen - len(buf), 4096))
  1067. buf += foo
  1068. if not foo:
  1069. raise SocketRecvDataError('Read %d bytes, expecting %d, '
  1070. 'read returned 0 length bytes' % (len(buf), rlen))
  1071. self.buffer = buf[rlen:]
  1072. return buf[:rlen]
  1073. def flush(self):
  1074. self.send_cmd('flush_all')
  1075. self.expect('OK')
  1076. def __str__(self):
  1077. d = ''
  1078. if self.deaduntil:
  1079. d = " (dead until %d)" % self.deaduntil
  1080. if self.family == socket.AF_INET:
  1081. return "inet:%s:%d%s" % (self.address[0], self.address[1], d)
  1082. elif self.family == socket.AF_INET6:
  1083. return "inet6:[%s]:%d%s" % (self.address[0], self.address[1], d)
  1084. else:
  1085. return "unix:%s%s" % (self.address, d)
  1086. def _doctest():
  1087. # noinspection PyUnresolvedReferences
  1088. import doctest, memcache
  1089. servers = ["127.0.0.1:11211"]
  1090. mc = Client(servers, debug=1)
  1091. globs = {"mc": mc}
  1092. return doctest.testmod(memcache, globs=globs)
  1093. if __name__ == "__main__":
  1094. failures = 0
  1095. print "Testing docstrings..."
  1096. _doctest()
  1097. print "Running tests:"
  1098. print
  1099. serverList = [["127.0.0.1:11211"]]
  1100. if '--do-unix' in sys.argv:
  1101. serverList.append([os.path.join(os.getcwd(), 'memcached.socket')])
  1102. for servers in serverList:
  1103. mc = Client(servers, debug=1)
  1104. def to_s(val):
  1105. if not isinstance(val, basestring):
  1106. return "%s (%s)" % (val, type(val))
  1107. return "%s" % val
  1108. def test_setget(key, val):
  1109. global failures
  1110. print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)),
  1111. mc.set(key, val)
  1112. newval = mc.get(key)
  1113. if newval == val:
  1114. print "OK"
  1115. return 1
  1116. else:
  1117. print "FAIL"
  1118. failures = failures + 1
  1119. return 0
  1120. class FooStruct(object):
  1121. def __init__(self):
  1122. self.bar = "baz"
  1123. def __str__(self):
  1124. return "A FooStruct"
  1125. def __eq__(self, other):
  1126. if isinstance(other, FooStruct):
  1127. return self.bar == other.bar
  1128. return 0
  1129. test_setget("a_string", "some random string")
  1130. test_setget("an_integer", 42)
  1131. if test_setget("long", long(1 << 30)):
  1132. print "Testing delete ...",
  1133. if mc.delete("long"):
  1134. print "OK"
  1135. else:
  1136. print "FAIL"
  1137. failures = failures + 1
  1138. print "Checking results of delete ..."
  1139. if mc.get("long") == None:
  1140. print "OK"
  1141. else:
  1142. print "FAIL"
  1143. failures = failures + 1
  1144. print "Testing get_multi ...",
  1145. print mc.get_multi(["a_string", "an_integer"])
  1146. # removed from the protocol
  1147. # if test_setget("timed_delete", 'foo'):
  1148. # print "Testing timed delete ...",
  1149. # if mc.delete("timed_delete", 1):
  1150. # print "OK"
  1151. # else:
  1152. # print "FAIL" failures = failures + 1
  1153. # print "Checking results of timed delete ..."
  1154. # if mc.get("timed_delete") == None:
  1155. # print "OK"
  1156. # else:
  1157. # print "FAIL" failures = failures + 1
  1158. print "Testing get(unknown value) ...",
  1159. print to_s(mc.get("unknown_value"))
  1160. f = FooStruct()
  1161. test_setget("foostruct", f)
  1162. print "Testing incr ...",
  1163. x = mc.incr("an_integer", 1)
  1164. if x == 43:
  1165. print "OK"
  1166. else:
  1167. print "FAIL"
  1168. failures = failures + 1
  1169. print "Testing decr ...",
  1170. x = mc.decr("an_integer", 1)
  1171. if x == 42:
  1172. print "OK"
  1173. else:
  1174. print "FAIL"
  1175. failures = failures + 1
  1176. sys.stdout.flush()
  1177. # sanity tests
  1178. print "Testing sending spaces...",
  1179. sys.stdout.flush()
  1180. try:
  1181. x = mc.set("this has spaces", 1)
  1182. except Client.MemcachedKeyCharacterError, msg:
  1183. print "OK"
  1184. else:
  1185. print "FAIL"
  1186. failures = failures + 1
  1187. print "Testing sending control characters...",
  1188. try:
  1189. x = mc.set("this\x10has\x11control characters\x02", 1)
  1190. except Client.MemcachedKeyCharacterError, msg:
  1191. print "OK"
  1192. else:
  1193. print "FAIL"
  1194. failures = failures + 1
  1195. print "Testing using insanely long key...",
  1196. try:
  1197. x = mc.set('a' * SERVER_MAX_KEY_LENGTH, 1)
  1198. except Client.MemcachedKeyLengthError, msg:
  1199. print "FAIL"
  1200. failures = failures + 1
  1201. else:
  1202. print "OK"
  1203. try:
  1204. x = mc.set('a' * SERVER_MAX_KEY_LENGTH + 'a', 1)
  1205. except Client.MemcachedKeyLengthError, msg:
  1206. print "OK"
  1207. else:
  1208. print "FAIL"
  1209. failures = failures + 1
  1210. print "Testing sending a unicode-string key...",
  1211. try:
  1212. x = mc.set(unicode('keyhere'), 1)
  1213. except Client.MemcachedStringEncodingError, msg:
  1214. print "OK",
  1215. else:
  1216. print "FAIL",
  1217. failures = failures + 1
  1218. try:
  1219. x = mc.set((unicode('a') * SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
  1220. except:
  1221. print "FAIL",
  1222. failures = failures + 1
  1223. else:
  1224. print "OK",
  1225. import pickle
  1226. s = pickle.loads('V\\u4f1a\np0\n.')
  1227. try:
  1228. x = mc.set((s * SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
  1229. except Client.MemcachedKeyLengthError:
  1230. print "OK"
  1231. else:
  1232. print "FAIL"
  1233. failures = failures + 1
  1234. print "Testing using a value larger than the memcached value limit..."
  1235. print 'NOTE: "MemCached: while expecting[...]" is normal...'
  1236. x = mc.set('keyhere', 'a' * SERVER_MAX_VALUE_LENGTH)
  1237. if mc.get('keyhere') == None:
  1238. print "OK",
  1239. else:
  1240. print "FAIL",
  1241. failures = failures + 1
  1242. x = mc.set('keyhere', 'a' * SERVER_MAX_VALUE_LENGTH + 'aaa')
  1243. if mc.get('keyhere') == None:
  1244. print "OK"
  1245. else:
  1246. print "FAIL"
  1247. failures = failures + 1
  1248. print "Testing set_multi() with no memcacheds running",
  1249. mc.disconnect_all()
  1250. errors = mc.set_multi({'keyhere': 'a', 'keythere': 'b'})
  1251. if errors != []:
  1252. print "FAIL"
  1253. failures = failures + 1
  1254. else:
  1255. print "OK"
  1256. print "Testing delete_multi() with no memcacheds running",
  1257. mc.disconnect_all()
  1258. ret = mc.delete_multi({'keyhere': 'a', 'keythere': 'b'})
  1259. if ret != 1:
  1260. print "FAIL"
  1261. failures = failures + 1
  1262. else:
  1263. print "OK"
  1264. if failures > 0:
  1265. print '*** THERE WERE FAILED TESTS'
  1266. sys.exit(1)
  1267. sys.exit(0)
  1268. # vim: ts=4 sw=4 et :