U
    3d]                     @   sl   d dl Z d dlmZ d dlZd dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ G dd	 d	eZdS )
    N)crc32)AWSAuthConnection)DynamoDBResponseError)Provider)
exceptions)jsonc                       s   e Zd ZdZdZdZdZdZdZdZ	dZ
eZd	Zd5 fdd	Zdd Zdd Zd6ddZdd Zdd Zd7ddZdd Zdd Zd d! Zd"d# Zd8d%d&Zd9d'd(Zd:d)d*Zd;d+d,Zd<d-d.Zd=d/d0Zd>d1d2Zd?d3d4Z   Z!S )@Layer1ae  
    This is the lowest-level interface to DynamoDB.  Methods at this
    layer map directly to API requests and parameters to the methods
    are either simple, scalar values or they are the Python equivalent
    of the JSON input as defined in the DynamoDB Developer's Guide.
    All responses are direct decoding of the JSON response bodies to
    Python data structures via the json or simplejson modules.

    :ivar throughput_exceeded_events: An integer variable that
        keeps a running total of the number of ThroughputExceeded
        responses this connection has received from Amazon DynamoDB.
    z	us-east-1DynamoDBZ20111205Z&ProvisionedThroughputExceededExceptionz.com.amazon.coral.service#ExpiredTokenExceptionZConditionalCheckFailedExceptionZValidationException
   NTr   c                    s   |	s8t jdd| j}t j D ]}|j|kr |}	 q8q |	| _tt	| j
| jj|||||||||
|d d| _t jdd|| _d S )Nr	   region)debugsecurity_tokenvalidate_certsprofile_namer   validate_checksums)botoconfiggetDefaultRegionNameZdynamodbZregionsnamer   superr   __init__endpointthroughput_exceeded_eventsZgetbool_validate_checksums)selfZaws_access_key_idZaws_secret_access_keyZ	is_secureportproxyZ
proxy_portr   r   r   r   r   r   Zregion_namereg	__class__ 8/tmp/pip-unpacked-wheel-d7dsrkjd/boto/dynamodb/layer1.pyr   J   s6    

      zLayer1.__init__c                 C   s   t | j| _| j| j d S )N)r   Z_provider_typeZproviderZ_auth_handlerZupdate_providerr   r!   r!   r"   _get_session_tokenb   s    zLayer1._get_session_tokenc                 C   s   dgS )Nzhmac-v4r!   r#   r!   r!   r"   _required_auth_capabilityf   s    z Layer1._required_auth_capability c              	   C   s   d| j | j|f | jjdtt|d}| dddi ||d}t }| j|d| j	| j
d}t | d }|d	}	tjd
|	  tjd|d |	t| | d}
tj|
 tj|
|dS )zW
        :raises: ``DynamoDBExpiredTokenError`` if the security token expires.
        z%s_%s.%szapplication/x-amz-json-1.0)X-Amz-TargetHostzContent-TypezContent-LengthPOST/N)ZsenderZoverride_num_retriesZretry_handleri  zx-amzn-RequestIdzRequestId: %sz%s: id=%s time=%smsr'   utf-8object_hook)ServiceNameVersionr   r   strlenZbuild_base_http_requesttimeZ_mexeNumberRetries_retry_handler	getheaderr   logr   Zperflogintreaddecoder   loads)r   actionbodyr-   headershttp_requeststartresponseelapsedZ
request_idresponse_bodyr!   r!   r"   make_requesti   s<     

   
  zLayer1.make_requestc           
      C   s  d }|j dkr(| d}tj| t|}| j|	dkr|  j
d7  _
d| j|f }| |}|d7 }|||f}|| jkrt|j |j|n| j|	dkrd}|   ||| j d df}n\| j|	dkrt|j |j|n8| j|	dkrt|j |j|n| |j |j||d}| jr|d k	rtjd	| d t| d
@ }	t|}|	|krd|	|f }||d | |f}|S )Ni  r+   Z__type   z%s, retry attempt %szRenewing Session Tokenr   zx-amz-crc32z&Validating crc32 checksum for body: %sl    zAThe calculated checksum %s did not match the expected checksum %s)statusr8   r9   r   r6   r   r   r:   ThruputErrorr   r   _exponential_timer3   dynamodb_exceptionsZDynamoDBThroughputExceededErrorreasonSessionExpiredErrorr$   Znum_retriesConditionalCheckFailedErrorZ#DynamoDBConditionalCheckFailedErrorValidationErrorZDynamoDBValidationErrorResponseErrorr5   r   r   r7   )
r   r@   i
next_sleeprE   rB   datamsgZexpected_crc32Zactual_crc32r!   r!   r"   r4      sb    



      

zLayer1._retry_handlerc                 C   s0   |dkrd}nt dd|  tjddd}|S )Nr   g?   ZBotoZmax_retry_delay<   )minr   r   r   )r   rN   rO   r!   r!   r"   rG      s    zLayer1._exponential_timec                 C   s2   i }|r||d< |r||d< t |}| d|S )at  
        Returns a dictionary of results.  The dictionary contains
        a **TableNames** key whose value is a list of the table names.
        The dictionary could also contain a **LastEvaluatedTableName**
        key whose value would be the last table name returned if
        the complete list of table names was not returned.  This
        value would then be passed as the ``start_table`` parameter on
        a subsequent call to this method.

        :type limit: int
        :param limit: The maximum number of tables to return.

        :type start_table: str
        :param start_table: The name of the table that starts the
            list.  If you ran a previous list_tables and not
            all results were returned, the response dict would
            include a LastEvaluatedTableName attribute.  Use
            that value here to continue the listing.
        LimitZExclusiveStartTableNameZ
ListTablesr   dumpsrC   )r   limitZstart_tablerP   
json_inputr!   r!   r"   list_tables   s    
zLayer1.list_tablesc                 C   s   d|i}t |}| d|S )z
        Returns information about the table including current
        state of the table, primary key schema and when the
        table was created.

        :type table_name: str
        :param table_name: The name of the table to describe.
        	TableNameZDescribeTablerV   r   
table_namerP   rY   r!   r!   r"   describe_table   s    	
zLayer1.describe_tablec                 C   s&   |||d}t |}| d|}|S )a  
        Add a new table to your account.  The table name must be unique
        among those associated with the account issuing the request.
        This request triggers an asynchronous workflow to begin creating
        the table.  When the workflow is complete, the state of the
        table will be ACTIVE.

        :type table_name: str
        :param table_name: The name of the table to create.

        :type schema: dict
        :param schema: A Python version of the KeySchema data structure
            as defined by DynamoDB

        :type provisioned_throughput: dict
        :param provisioned_throughput: A Python version of the
            ProvisionedThroughput data structure defined by
            DynamoDB.
        )r[   Z	KeySchemaProvisionedThroughputZCreateTablerV   )r   r]   Zschemaprovisioned_throughputrP   rY   Zresponse_dictr!   r!   r"   create_table   s    
zLayer1.create_tablec                 C   s    ||d}t |}| d|S )a_  
        Updates the provisioned throughput for a given table.

        :type table_name: str
        :param table_name: The name of the table to update.

        :type provisioned_throughput: dict
        :param provisioned_throughput: A Python version of the
            ProvisionedThroughput data structure defined by
            DynamoDB.
        )r[   r_   ZUpdateTablerV   )r   r]   r`   rP   rY   r!   r!   r"   update_table   s
    
zLayer1.update_tablec                 C   s   d|i}t |}| d|S )a  
        Deletes the table and all of it's data.  After this request
        the table will be in the DELETING state until DynamoDB
        completes the delete operation.

        :type table_name: str
        :param table_name: The name of the table to delete.
        r[   ZDeleteTablerV   r\   r!   r!   r"   delete_table	  s    	
zLayer1.delete_tableFc           	      C   sR   ||d}|r||d< |r"d|d< t |}| jd||d}d|krNtd|S )	a  
        Return a set of attributes for an item that matches
        the supplied key.

        :type table_name: str
        :param table_name: The name of the table containing the item.

        :type key: dict
        :param key: A Python version of the Key data structure
            defined by DynamoDB.

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type consistent_read: bool
        :param consistent_read: If True, a consistent read
            request is issued.  Otherwise, an eventually consistent
            request is issued.
        r[   KeyAttributesToGetTConsistentReadZGetItemr,   ItemzKey does not exist.)r   rW   rC   rH   ZDynamoDBKeyNotFoundError)	r   r]   keyattributes_to_getconsistent_readr-   rP   rY   r@   r!   r!   r"   get_item  s     
zLayer1.get_itemc                 C   s*   |si S d|i}t |}| jd||dS )a  
        Return a set of attributes for a multiple items in
        multiple tables using their primary keys.

        :type request_items: dict
        :param request_items: A Python version of the RequestItems
            data structure defined by DynamoDB.
        RequestItemsZBatchGetItemr,   rV   r   Zrequest_itemsr-   rP   rY   r!   r!   r"   batch_get_item<  s    

zLayer1.batch_get_itemc                 C   s"   d|i}t |}| jd||dS )a  
        This operation enables you to put or delete several items
        across multiple tables in a single API call.

        :type request_items: dict
        :param request_items: A Python version of the RequestItems
            data structure defined by DynamoDB.
        rm   ZBatchWriteItemr,   rV   rn   r!   r!   r"   batch_write_itemM  s
    	
zLayer1.batch_write_itemc                 C   s<   ||d}|r||d< |r"||d< t |}| jd||dS )a  
        Create a new item or replace an old item with a new
        item (including all attributes).  If an item already
        exists in the specified table with the same primary
        key, the new item will completely replace the old item.
        You can perform a conditional put by specifying an
        expected rule.

        :type table_name: str
        :param table_name: The name of the table in which to put the item.

        :type item: dict
        :param item: A Python version of the Item data structure
            defined by DynamoDB.

        :type expected: dict
        :param expected: A Python version of the Expected
            data structure defined by DynamoDB.

        :type return_values: str
        :param return_values: Controls the return of attribute
            name-value pairs before then were changed.  Possible
            values are: None or 'ALL_OLD'. If 'ALL_OLD' is
            specified and the item is overwritten, the content
            of the old item is returned.
        )r[   rh   ExpectedReturnValuesZPutItemr,   rV   )r   r]   itemexpectedreturn_valuesr-   rP   rY   r!   r!   r"   put_item[  s    
zLayer1.put_itemc           	      C   s>   |||d}|r||d< |r$||d< t |}| jd||dS )af  
        Edits an existing item's attributes. You can perform a conditional
        update (insert a new attribute name-value pair if it doesn't exist,
        or replace an existing name-value pair if it has certain expected
        attribute values).

        :type table_name: str
        :param table_name: The name of the table.

        :type key: dict
        :param key: A Python version of the Key data structure
            defined by DynamoDB which identifies the item to be updated.

        :type attribute_updates: dict
        :param attribute_updates: A Python version of the AttributeUpdates
            data structure defined by DynamoDB.

        :type expected: dict
        :param expected: A Python version of the Expected
            data structure defined by DynamoDB.

        :type return_values: str
        :param return_values: Controls the return of attribute
            name-value pairs before then were changed.  Possible
            values are: None or 'ALL_OLD'. If 'ALL_OLD' is
            specified and the item is overwritten, the content
            of the old item is returned.
        )r[   re   ZAttributeUpdatesrq   rr   Z
UpdateItemr,   rV   )	r   r]   ri   Zattribute_updatesrt   ru   r-   rP   rY   r!   r!   r"   update_item  s    
zLayer1.update_itemc                 C   s<   ||d}|r||d< |r"||d< t |}| jd||dS )aK  
        Delete an item and all of it's attributes by primary key.
        You can perform a conditional delete by specifying an
        expected rule.

        :type table_name: str
        :param table_name: The name of the table containing the item.

        :type key: dict
        :param key: A Python version of the Key data structure
            defined by DynamoDB.

        :type expected: dict
        :param expected: A Python version of the Expected
            data structure defined by DynamoDB.

        :type return_values: str
        :param return_values: Controls the return of attribute
            name-value pairs before then were changed.  Possible
            values are: None or 'ALL_OLD'. If 'ALL_OLD' is
            specified and the item is overwritten, the content
            of the old item is returned.
        rd   rq   rr   Z
DeleteItemr,   rV   )r   r]   ri   rt   ru   r-   rP   rY   r!   r!   r"   delete_item  s    
zLayer1.delete_itemc                 C   s   ||d}|r||d< |r"||d< |r.||d< |
r:d|d< |rFd|d< |rTd|d< nd	|d< |rh||d
< t |}| jd||	dS )a  
        Perform a query of DynamoDB.  This version is currently punting
        and expecting you to provide a full and correct JSON body
        which is passed as is to DynamoDB.

        :type table_name: str
        :param table_name: The name of the table to query.

        :type hash_key_value: dict
        :param key: A DynamoDB-style HashKeyValue.

        :type range_key_conditions: dict
        :param range_key_conditions: A Python version of the
            RangeKeyConditions data structure.

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type limit: int
        :param limit: The maximum number of items to return.

        :type count: bool
        :param count: If True, Amazon DynamoDB returns a total
            number of items for the Query operation, even if the
            operation has no matching items for the assigned filter.

        :type consistent_read: bool
        :param consistent_read: If True, a consistent read
            request is issued.  Otherwise, an eventually consistent
            request is issued.

        :type scan_index_forward: bool
        :param scan_index_forward: Specified forward or backward
            traversal of the index.  Default is forward (True).

        :type exclusive_start_key: list or tuple
        :param exclusive_start_key: Primary key of the item from
            which to continue an earlier query.  This would be
            provided as the LastEvaluatedKey in that query.
        )r[   ZHashKeyValueZRangeKeyConditionrf   rU   TCountrg   ZScanIndexForwardFExclusiveStartKeyZQueryr,   rV   )r   r]   Zhash_key_valueZrange_key_conditionsrj   rX   rk   Zscan_index_forwardexclusive_start_keyr-   countrP   rY   r!   r!   r"   query  s,    .

zLayer1.queryc           
      C   s^   d|i}|r||d< |r ||d< |r,||d< |r8d|d< |rD||d< t |}	| jd|	|d	S )
a  
        Perform a scan of DynamoDB.  This version is currently punting
        and expecting you to provide a full and correct JSON body
        which is passed as is to DynamoDB.

        :type table_name: str
        :param table_name: The name of the table to scan.

        :type scan_filter: dict
        :param scan_filter: A Python version of the
            ScanFilter data structure.

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type limit: int
        :param limit: The maximum number of items to evaluate.

        :type count: bool
        :param count: If True, Amazon DynamoDB returns a total
            number of items for the Scan operation, even if the
            operation has no matching items for the assigned filter.

        :type exclusive_start_key: list or tuple
        :param exclusive_start_key: Primary key of the item from
            which to continue an earlier query.  This would be
            provided as the LastEvaluatedKey in that query.
        r[   Z
ScanFilterrf   rU   Try   rz   ZScanr,   rV   )
r   r]   Zscan_filterrj   rX   r{   r-   r|   rP   rY   r!   r!   r"   scan  s    !
zLayer1.scan)NNTNNNr   NNTTN)r&   N)NN)NFN)N)N)NNN)NNN)NNN)NNNFTNNF)NNNNNF)"__name__
__module____qualname____doc__r   r.   r/   rF   rJ   rK   rL   r   rM   r3   r   r$   r%   rC   r4   rG   rZ   r^   ra   rb   rc   rl   ro   rp   rv   rw   rx   r}   r~   __classcell__r!   r!   r   r"   r   "   s                     
+
    
&

    
(    
+    
$            
D         r   )r2   binasciir   r   Zboto.connectionr   Zboto.exceptionr   Zboto.providerr   Zboto.dynamodbr   rH   Zboto.compatr   r   r!   r!   r!   r"   <module>   s   