o
    ;h                     @   sD   d dl Z d dlZd dlZd dlmZ d dlmZ G dd deZdS )    N)	BaseCache)BaseSerializerc                       s  e Zd ZdZe Z					d0dejdeje	 deje	 d	e
d
eje	 dejf fddZdejfddZdejfddZde	dejfddZde	defddZ		d1de	dejdeje
 deje dejf
ddZd2de	dejdeje
 dejfddZ	d2d eje	ejf deje
 dejej fd!d"Zd#e	dejej fd$d%Zd#e	deje	ejf fd&d'Zd2de	dejdeje
 dejfd(d)Zde	defd*d+Zd#e	dejej fd,d-Zdefd.d/Z  ZS )3MongoDbCachea  
    Implementation of cachelib.BaseCache that uses mongodb collection
    as the backend.

    Limitations: maximum MongoDB document size is 16mb

    :param client: mongodb client or connection string
    :param db: mongodb database name
    :param collection: mongodb collection name
    :param default_timeout: Set the timeout in seconds after which cache entries
                            expire
    :param key_prefix: A prefix that should be added to all keys.

    Ncache-dbcache-collection,  clientdb
collectiondefault_timeout
key_prefixkwargsc           
         s   t  | zdd l}W n ty   td Y nw |d u s$t|tr*|j|d}|| | | _	| j	
 }dd | D }	d|	vrK| j	jddd |pNd	| _|| _d S )
Nr   zno pymongo module found)hostc                 S   s"   h | ]}|d  D ]}|d qqS )keyr    ).0valuesubkeyr   r   C/var/www/html/venv/lib/python3.10/site-packages/cachelib/mongodb.py	<setcomp>.   s
    z(MongoDbCache.__init__.<locals>.<setcomp>idT)unique )super__init__pymongoImportErrorloggingwarning
isinstancestrZMongoClientr   Zindex_informationvaluesZcreate_indexr   r
   )
selfr   r	   r
   r   r   r   r   
index_infoall_keys	__class__r   r   r      s"   	


zMongoDbCache.__init__returnc                 C   s   t j  jt jjdS )z<Return a tz-aware UTC datetime representing the current time)tzinfo)datetimeutcnowreplacetimezoneutcr"   r   r   r   _utcnow6   s   zMongoDbCache._utcnowc                 C   s   | j dd|  ii}|S )N
expirationz$lte)r   delete_manyr/   )r"   resr   r   r   _expire_records:   s   zMongoDbCache._expire_recordsr   c                 C   s:   |    | jd| j| i}d}|r| j|d }|S )z
        Get a cache item

        :param key: The cache key of the item to fetch
        :return: cache value if not expired, else None
        r   Nval)r3   r   Zfind_oner   
serializerloads)r"   r   recordr   r   r   r   get>   s   zMongoDbCache.getc                 C   s(   | j d| j| i}t|jdk}|S )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
        r   r   )r   Z
delete_oner   booldeleted_count)r"   r   r2   Zdeletedr   r   r   deleteL   s   zMongoDbCache.deleteTr   timeout	overwritec                 C   s~   |  |}|  }|s| |rdS | j|}| j| |d}|dkr.|tj|d |d< | j	d| j| id|id dS )	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.
        Fr   r4   r   secondsr0   r   $setT)
_normalize_timeoutr/   hasr5   dumpsr   r)   	timedeltar   Z
update_one)r"   r   r   r<   r=   nowdumpr7   r   r   r   _setX   s   

zMongoDbCache._setc                 C      |    | j|||ddS )NTr<   r=   r3   rH   r"   r   r   r<   r   r   r   set|      zMongoDbCache.setmappingc                    s      ddlm} g }  } |}| D ]1\}} j|} j| |d}	|dkr9|t	j
|d |	d< ||d j| id|	idd	 q j|}
t| }|
jd
 t|kr jdd fdd|D ii}g }|D ]	}||d  qu|S )Nr   )	UpdateOner>   r?   r0   r   rA   T)ZupsertZ	nUpserted$inc                       g | ]} j | qS r   r   r   r   r.   r   r   
<listcomp>       z)MongoDbCache.set_many.<locals>.<listcomp>)r3   r   rP   r/   rB   itemsr5   rD   r   r)   rE   appendr   Z
bulk_writelistkeysZbulk_api_resultlenfind)r"   rO   r<   rP   
operationsrF   r   r4   rG   r7   resultrZ   queryitemr   r.   r   set_many   s.   
zMongoDbCache.set_manyrZ   c                 G   s.   | j | }g }|D ]}|||d  q	|S N)get_dictrX   r8   )r"   rZ   resultsr!   r   r   r   r   get_many   s
   
zMongoDbCache.get_manyc                    sn        jdd fdd|D ii}t|d }|D ]} j|d }|||d t jd  < q|S )Nr   rQ   c                    rR   r   rS   rT   r.   r   r   rU      rV   z)MongoDbCache.get_dict.<locals>.<listcomp>r4   )	r3   r   r\   dictfromkeysr5   r6   r[   r   )r"   rZ   r_   rd   r`   r   r   r.   r   rc      s   zMongoDbCache.get_dictc                 C   rI   )NFrJ   rK   rL   r   r   r   add   rN   zMongoDbCache.addc                 C   s   |    | |}|d uS rb   )r3   r8   )r"   r   r7   r   r   r   rC      s   
zMongoDbCache.hasc                    st      t|}ddfdd|D ii}j|}|jt|kr8fddj|D   fdd|D }|S )Nr   rQ   c                    rR   r   rS   rT   r.   r   r   rU      rV   z,MongoDbCache.delete_many.<locals>.<listcomp>c                    s"   g | ]}|d  t  jd qS )r   N)r[   r   r   r`   r.   r   r   rU      s    c                    s   g | ]}| vr|qS r   r   ri   )existing_keysr   r   rU      s    )r3   rY   r   r1   r:   r[   r\   )r"   rZ   r2   filterr^   r   )rj   r"   r   r1      s   

zMongoDbCache.delete_manyc                 C   s   | j   dS NT)r   Zdropr.   r   r   r   clear   s   
zMongoDbCache.clear)Nr   r   r   Nrl   rb   )__name__
__module____qualname____doc__r   r5   _tAnyOptionalr    intr   r/   r3   r8   r9   r;   rH   rM   DictListra   re   rc   rh   rC   r1   rm   __classcell__r   r   r%   r   r   	   sj    
&$

&r   )	r)   r   typingrr   Zcachelib.baser   Zcachelib.serializersr   r   r   r   r   r   <module>   s    