
    Ջg@!                     J    d dl Z d dlZd dlmZ d dlmZ dZdZ G d de      Z	y)    N)	BaseCache)DynamoDbSerializer
created_atresponsec                       e Zd ZdZ e       Z	 	 	 	 	 ddej                  e   de	dej                  e   dej                  e   dej                  e   dej                  f fdZd	ej                  fd
Zddedej                  e   d	ej                  fdZded	ej                  fdZded	efdZ	 	 ddedej                  dej                  e	   dej                  e   d	ej                  f
dZddedej                  dej                  e	   d	ej                  fdZddedej                  dej                  e	   d	ej                  fdZded	efdZd	efdZ xZS )DynamoDbCachea(  
    Implementation of cachelib.BaseCache that uses an AWS DynamoDb table
    as the backend.

    Your server process will require dynamodb:GetItem and dynamodb:PutItem
    IAM permissions on the cache table.

    Limitations: DynamoDB table items are limited to 400 KB in size.  Since
    this class stores cached items in a table, the max size of a cache entry
    will be slightly less than 400 KB, since the cache key and expiration
    time fields are also part of the item.

    :param table_name: The name of the DynamoDB table to use
    :param default_timeout: Set the timeout in seconds after which cache entries
                            expire
    :param key_field: The name of the hash_key attribute in the DynamoDb
                      table. This must be a string attribute.
    :param expiration_time_field: The name of the table attribute to store the
                                  expiration time in.  This will be an int
                                  attribute. The timestamp will be stored as
                                  seconds past the epoch.  If you configure
                                  this as the TTL field, then DynamoDB will
                                  automatically delete expired entries.
    :param key_prefix: A prefix that should be added to all keys.

    
table_namedefault_timeout	key_fieldexpiration_time_field
key_prefixkwargsc                    t         |   |       	 dd l}|| _        || _        || _        |xs d| _         |j                  di || _
        |j                  j                  j                  | _        	 | j                  j                  |      | _        | j                   j#                          y # t        $ r}t	        d      |d }~ww xY w# t$        $ r | j                  j'                  |ddg||ddgd	      }	|	j)                           |j*                  di |}
|
j-                  |d
|d       | j                  j                  |      | _        | j                   j#                          Y y w xY w)Nr   zno boto3 module found S)AttributeNameAttributeTypeHASH)r   KeyTypePAY_PER_REQUEST)AttributeDefinitions	TableName	KeySchemaBillingModeT)Enabledr   )r   TimeToLiveSpecification)dynamodb)super__init__boto3ImportErrorRuntimeError_table_name
_key_field_expiration_time_fieldr   resource_dynamor   
conditionsAttr_attrTable_tableload	Exceptioncreate_tablewait_until_existsclientupdate_time_to_live)selfr	   r
   r   r   r   r   r    errtabledynamo	__class__s              D/var/www/html/venv/lib/python3.12/site-packages/cachelib/dynamodb.pyr   zDynamoDbCache.__init__)   sp    	)	A &#&;#$*%u~~;F;^^..33
	,,,,Z8DKKK  	A67S@	A  	LL--&/#F& %&/FC . . 	E ##%!U\\77F&&$#%:) '  ,,,,Z8DKKK+	s*   B. 3:C .	C7CCB"E0/E0returnc                     t         j                   j                         j                  t         j                  j                        S )z<Return a tz-aware UTC datetime representing the current time)tzinfo)datetimeutcnowreplacetimezoneutc)r3   s    r8   _utcnowzDynamoDbCache._utcnow[   s1      '')119J9J9N9N1OO    key
attributesc                    i }|rB| j                   |vrt        |      | j                   gz   }t        dj                  |            } | j                  j
                  dd| j                  |ii|}|j                  d      }|rKt        | j                         j                               }|j                  | j                   |dz         |kD  r|S y)a  
        Get an item from the cache table, optionally limiting the returned
        attributes.

        :param key: The cache key of the item to fetch

        :param attributes: An optional list of attributes to fetch.  If not
                           given, all attributes are fetched.  The
                           expiration_time field will always be added to the
                           list of fetched attributes.
        :return: The table item for key if it exists and is not expired, else
                 None
        ,)ProjectionExpressionKeyItemd   N )r%   listdictjoinr,   get_itemr$   getintrA   	timestamp)r3   rC   rD   r   r   
cache_itemnows          r8   	_get_itemzDynamoDbCache._get_item_   s     ***<!*-1L1L0MM
sxx
/CDF'4;;''MT__c,BMfM\\&)
dlln..01C~~d9939EK!!rB   c                     | j                  | j                  |z         }|r&|t           }| j                  j	                  |      }|S y)z
        Get a cache item

        :param key: The cache key of the item to fetch
        :return: cache value if not expired, else None
        N)rU   r   RESPONSE_FIELD
serializerloads)r3   rC   rS   r   values        r8   rP   zDynamoDbCache.get}   sD     ^^DOOc$9:
!.1HOO))(3ELrB   c                 :   	 | j                   j                  | j                  | j                  |z   i| j	                  | j                        j                                y# | j                  j                  j                  j                  j                  $ r Y yw xY w)z
        Deletes an item from the cache.  This is a no-op if the item doesn't
        exist

        :param key: Key of the item to delete.
        :return: True if the key existed and was deleted
        )rH   ConditionExpressionTF)r,   delete_itemr$   r   r*   existsr'   metar1   
exceptionsConditionalCheckFailedExceptionr3   rC   s     r8   deletezDynamoDbCache.delete   s    	KK##__doo&;<$(JJt$?$F$F$H $  ||  ''22RR 		s   AA   7BBrZ   timeout	overwritec                    | j                  |      }| j                         }i }|sw| j                  | j                        j	                         | j                  | j
                        j                  t        |j                                     z  }t        |      }	 | j                  j                  |      }| j                  |t        |j                         t        |i}	|dkD  r?|t        j                   |      z   }
t        |
j                               |	| j
                  <    | j"                  j$                  dd|	i| y# t&        $ r Y yw xY w)a*  
        Store a cache item, with the option to not overwrite existing items

        :param key: Cache key to use
        :param value: a serializable object
        :param timeout: The timeout in seconds for the cached item, to override
                        the default
        :param overwrite: If true, overwrite any existing cache item with key.
                          If false, the new value will only be stored if no
                          non-expired cache item exists with key.
        :return: True if the new item was stored.
        )r\   r   )secondsrI   TFrK   )_normalize_timeoutrA   r*   r$   
not_existsr%   lterQ   rR   rM   rX   dumpsCREATED_AT_FIELD	isoformatrW   r<   	timedeltar,   put_itemr.   )r3   rC   rZ   rd   re   rT   r   conddumpitemexpiration_times              r8   _setzDynamoDbCache._set   s$   & ))'2lln ::doo.99;djj++?c#cmmo&'(D d3F	??((/D #--/D
 {"%(:(:7(K"K478Q8Q8S4TT001 DKK  5d5f5 		s   B%E 	EEc                 F    | j                  | j                  |z   ||d      S )NTrd   re   rt   r   r3   rC   rZ   rd   s       r8   setzDynamoDbCache.set   s#    yy3.wRVyWWrB   c                 F    | j                  | j                  |z   ||d      S )NFrv   rw   rx   s       r8   addzDynamoDbCache.add   s#    yy3.wRWyXXrB   c                 Z    | j                  | j                  |z   | j                  g      d uS N)rU   r   r%   rb   s     r8   haszDynamoDbCache.has   s/    NN4??S043N3N2OP	
rB   c                 V   | j                   j                  j                  j                  d      }|j	                  | j
                  | j                        }| j                  j                         5 }|D ]  }|d   D ]  }|j                  |          	 d d d        y# 1 sw Y   yxY w)Nscan)r   rG   Items)rH   T)
r'   r_   r1   get_paginatorpaginater#   r$   r,   batch_writerr]   )r3   	paginatorpagesbatchpagerr   s         r8   clearzDynamoDbCache.clear   s    LL%%,,::6B	""&&T__ # 
 [[%%' 	05 0 M 0D%%$%/00	0
 	0
 s   1$BB()zpython-cachei,  	cache_keyrs   Nr}   )NT)__name__
__module____qualname____doc__r   rX   _tOptionalstrrQ   Anyr   rA   rL   rU   rP   boolrc   rt   ry   r{   r~   r   __classcell__)r7   s   @r8   r   r      s   6 $%J (6"&12C'+0KK$0 0 ;;s#	0
  "{{3/0 KK$0 &&0dP PS bkk$.? 266 <s rvv # $ * %)'+-- vv- S!	-
 ;;t$- 
-^Xs X266 XBKK4D XPRPVPV XYs Y266 YBKK4D YPRPVPV Y
s 
t 
t rB   r   )
r<   typingr   cachelib.baser   cachelib.serializersr   rl   rW   r   rK   rB   r8   <module>r      s*      # 3 WI WrB   