Format: application/x-python-code
⬇ Download File (7.4 KB)
   1  o
   2  
   3  2'h@!�@sDddlZddlZddlmZddlmZdZdZGdd�de�Z	dS)�N)�	BaseCache)�DynamoDbSerializerZ
   4  created_at�responsec
   5  s\eZdZdZe�Z					d(dejede	d	ejed
   6  ejedejedej
   7  f�fd
   8  d�
   9  Zdej
  10  fdd�Zd)dedeje
  11  dej
  12  fdd�Zdedej
  13  fdd�Zdedefdd�Z		d*dedej
  14  deje	dejedej
  15  f
  16  dd�Zd)dedej
  17  deje	dej
  18  fd d!�Zd)dedej
  19  deje	dej
  20  fd"d#�Zdedefd$d%�Zdefd&d'�Z�ZS)+�
  21  DynamoDbCachea(
  22      Implementation of cachelib.BaseCache that uses an AWS DynamoDb table
  23      as the backend.
  24  
  25      Your server process will require dynamodb:GetItem and dynamodb:PutItem
  26      IAM permissions on the cache table.
  27  
  28      Limitations: DynamoDB table items are limited to 400 KB in size.  Since
  29      this class stores cached items in a table, the max size of a cache entry
  30      will be slightly less than 400 KB, since the cache key and expiration
  31      time fields are also part of the item.
  32  
  33      :param table_name: The name of the DynamoDB table to use
  34      :param default_timeout: Set the timeout in seconds after which cache entries
  35                              expire
  36      :param key_field: The name of the hash_key attribute in the DynamoDb
  37                        table. This must be a string attribute.
  38      :param expiration_time_field: The name of the table attribute to store the
  39                                    expiration time in.  This will be an int
  40                                    attribute. The timestamp will be stored as
  41                                    seconds past the epoch.  If you configure
  42                                    this as the TTL field, then DynamoDB will
  43                                    automatically delete expired entries.
  44      :param key_prefix: A prefix that should be added to all keys.
  45  
  46      �python-cache�,�	cache_key�expiration_timeN�
  47  table_name�default_timeout�	key_field�expiration_time_field�
  48  key_prefix�kwargsc
  49  st��|�zddl}Wnty}ztd�|�d}~ww||_||_||_|p*d|_|j	di|��|_
  50  |jjj
  51  |_z|j
  52  �|�|_|j��WdSty�|j
  53  j|dd�g||dd�gd	d
  54  �}	|	��|jdi|��}
  55  |
  56  j|d|d�d
  57  �|j
  58  �|�|_|j��YdSw)Nrzno boto3 module found��dynamodb�S)�
  59  AttributeNameZ
  60  AttributeType�HASH)rZKeyTypeZPAY_PER_REQUEST)ZAttributeDefinitions�	TableNameZ	KeySchemaZBillingModeT)ZEnabledr)rZTimeToLiveSpecification)r)�super�__init__�boto3�ImportError�RuntimeError�_table_name�
  61  _key_field�_expiration_time_fieldr�resource�_dynamorZ
  62  conditionsZAttr�_attr�Table�_table�load�	ExceptionZcreate_tableZwait_until_exists�clientZupdate_time_to_live)�selfr
  63  rrr
  64  rrr�err�tableZdynamo��	__class__��GC:\Users\shubh\Videos\agent\nova\Lib\site-packages\cachelib/dynamodb.pyr)sH	
  65  ��
  66  ���
  67  ���zDynamoDbCache.__init__�returncCstj��jtjjd�S)z<Return a tz-aware UTC datetime representing the current time)�tzinfo)�datetime�utcnow�replace�timezone�utc)r&r+r+r,�_utcnow[szDynamoDbCache._utcnow�key�
  68  attributescCs�i}|r|j|vrt|�|jg}td�|�d�}|jjdd|j|ii|��}|�d�}|rCt|�	��
  69  ��}|�|j|d�|krC|SdS)a
  70          Get an item from the cache table, optionally limiting the returned
  71          attributes.
  72  
  73          :param key: The cache key of the item to fetch
  74  
  75          :param attributes: An optional list of attributes to fetch.  If not
  76                             given, all attributes are fetched.  The
  77                             expiration_time field will always be added to the
  78                             list of fetched attributes.
  79          :return: The table item for key if it exists and is not expired, else
  80                   None
  81          �,)�ProjectionExpression�Key�Item�dNr+)r�list�dict�joinr"Zget_itemr�get�intr4�	timestamp)r&r5r6rr�
  82  cache_item�nowr+r+r,�	_get_item_s
  83  
  84  zDynamoDbCache._get_itemcCs0|�|j|�}|r|t}|j�|�}|SdS)z�
  85          Get a cache item
  86  
  87          :param key: The cache key of the item to fetch
  88          :return: cache value if not expired, else None
  89          N)rDr�RESPONSE_FIELD�
  90  serializer�loads)r&r5rBr�valuer+r+r,r?}szDynamoDbCache.getcCsNz|jj|j|j|i|�|j���d�WdS|jjjj	j
  91  y&YdSw)z�
  92          Deletes an item from the cache.  This is a no-op if the item doesn't
  93          exist
  94  
  95          :param key: Key of the item to delete.
  96          :return: True if the key existed and was deleted
  97          )r9�ConditionExpressionTF)r"�delete_itemrrr �existsr�metar%�
  98  exceptionsZConditionalCheckFailedException�r&r5r+r+r,�delete�s��zDynamoDbCache.deleteTrH�timeout�	overwritecCs�|�|�}|��}i}|s'|�|j���|�|j��t|����B}t	|d�}z4|j
  99  �|�}|j|t|�
 100  �t|i}	|dkrN|tj|d�}
 101  t|
 102  ���|	|j<|jjdd|	i|��WdStyeYdSw)	a*
 103          Store a cache item, with the option to not overwrite existing items
 104  
 105          :param key: Cache key to use
 106          :param value: a serializable object
 107          :param timeout: The timeout in seconds for the cached item, to override
 108                          the default
 109          :param overwrite: If true, overwrite any existing cache item with key.
 110                            If false, the new value will only be stored if no
 111                            non-expired cache item exists with key.
 112          :return: True if the new item was stored.
 113          )rIr)�secondsr:TFNr+)Z_normalize_timeoutr4r rZ
 114  not_existsrZlter@rAr=rF�dumps�CREATED_AT_FIELD�	isoformatrEr/�	timedeltar"Zput_itemr$)r&r5rHrPrQrCrZcond�dump�itemr	r+r+r,�_set�s0
 115  ��
 116  ��zDynamoDbCache._setcC�|j|j|||dd�S)NT�rPrQ�rYr�r&r5rHrPr+r+r,�set��zDynamoDbCache.setcCrZ)NFr[r\r]r+r+r,�add�r_zDynamoDbCache.addcCs|�|j||jg�duS�N)rDrrrNr+r+r,�has�s��zDynamoDbCache.hascCsv|jjj�d�}|j|j|jd�}|j���}|D]}|dD]}|j	|d�qqWd�dS1s4wYdS)N�scan)rr8ZItems)r9T)
 117  rrLr%Z
 118  get_paginatorZpaginaterrr"Zbatch_writerrJ)r&Z	paginatorZpages�batch�pagerXr+r+r,�clear�s���
 119  ��zDynamoDbCache.clear)rrrr	Nra)NT)�__name__�
 120  __module__�__qualname__�__doc__rrF�_t�Optional�strr@�Anyrr4r<rDr?�boolrOrYr^r`rbrf�
 121  __classcell__r+r+r)r,rsT�������2 �����
 122  �&/&r)
 123  r/�typingrkZ
 124  cachelib.baserZcachelib.serializersrrTrErr+r+r+r,�<module>s