U
    W+de                     @   s   d dl Zd dlZd dlZd dlmZ d dlmZ d dlmZm	Z	 d dl
mZ d dlmZ d dlmZ G dd	 d	ejZG d
d deZdS )    N)handler)AWSQueryConnection)DomainDomainMetaData)Item)SDBRegionInfo)SDBResponseErrorc                       s(   e Zd ZdZ fddZdd Z  ZS )
ItemThreadaj  
    A threaded :class:`Item <boto.sdb.item.Item>` retriever utility class.
    Retrieved :class:`Item <boto.sdb.item.Item>` objects are stored in the
    ``items`` instance variable after :py:meth:`run() <run>` is called.

    .. tip:: The item retrieval will not start until
        the :func:`run() <boto.sdb.connection.ItemThread.run>` method is called.
    c                    s0   t t| j|d || _t | _|| _g | _dS )a  
        :param str name: A thread name. Used for identification.
        :param str domain_name: The name of a SimpleDB
            :class:`Domain <boto.sdb.domain.Domain>`
        :type item_names: string or list of strings
        :param item_names: The name(s) of the items to retrieve from the specified
            :class:`Domain <boto.sdb.domain.Domain>`.
        :ivar list items: A list of items retrieved. Starts as empty list.
        )nameN)superr	   __init__domain_nameSDBConnectionconn
item_namesitems)selfr
   r   r   	__class__ 7/tmp/pip-unpacked-wheel-dlxw5sjy/boto/sdb/connection.pyr   (   s
    
zItemThread.__init__c                 C   s,   | j D ] }| j| j|}| j| qdS )z
        Start the threaded retrieval of items. Populates the
        ``items`` list with :class:`Item <boto.sdb.item.Item>` objects.
        N)r   r   get_attributesr   r   append)r   	item_nameitemr   r   r   run9   s    
zItemThread.run)__name__
__module____qualname____doc__r   r   __classcell__r   r   r   r   r	      s   r	   c                       s   e Zd ZdZdZdZdZeZd8 fd	d
	Z	dd Z
dd Zd9ddZdd Zd:ddZdd Zdd Zdd Zd;ddZd<dd Zd=d!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd>d+d,Zd?d-d.Zd@d/d0ZdAd1d2Zd3d4 ZdBd6d7Z  ZS )Cr   a  
    This class serves as a gateway to your SimpleDB region (defaults to
    us-east-1). Methods within allow access to SimpleDB
    :class:`Domain <boto.sdb.domain.Domain>` objects and their associated
    :class:`Item <boto.sdb.item.Item>` objects.

    .. tip::
        While you may instantiate this class directly, it may be easier to
        go through :py:func:`boto.connect_sdb`.
    z	us-east-1zsdb.us-east-1.amazonaws.comz
2009-04-15NTr   /c                    s   |s8t jdd| j}t j D ]}|j|kr |} q8q || _tt	| j
||||||||| jj|	|
||||d d| _|| _t| _dS )aZ  
        For any keywords that aren't documented, refer to the parent class,
        :py:class:`boto.connection.AWSAuthConnection`. You can avoid having
        to worry about these keyword arguments by instantiating these objects
        via :py:func:`boto.connect_sdb`.

        :type region: :class:`boto.sdb.regioninfo.SDBRegionInfo`
        :keyword region: Explicitly specify a region. Defaults to ``us-east-1``
            if not specified. You may also specify the region in your ``boto.cfg``:

            .. code-block:: cfg

                [SDB]
                region = eu-west-1

        ZSDBregion)security_tokenvalidate_certsprofile_nameg        N)botoconfiggetDefaultRegionNamesdbZregionsr
   r"   r   r   r   Zendpoint	box_usage	converterr   item_cls)r   Zaws_access_key_idZaws_secret_access_keyZ	is_secureportproxyZ
proxy_portZ
proxy_userZ
proxy_passdebugZhttps_connection_factoryr"   pathr,   r#   r$   r%   Zregion_nameregr   r   r   r   T   s4    
      	zSDBConnection.__init__c                 C   s   dgS )Nr*   r   r   r   r   r   _required_auth_capability   s    z'SDBConnection._required_auth_capabilityc                 C   s
   || _ dS )a  
        While the default item class is :py:class:`boto.sdb.item.Item`, this
        default may be overridden. Use this method to change a connection's
        item class.

        :param object cls: The new class to set as this connection's item
            class. See the default item class for inspiration as to what your
            replacement should/could look like.
        N)r-   )r   clsr   r   r   set_item_cls   s    
zSDBConnection.set_item_clsF	Attributec           
      C   s   t | }d}|D ]}|| }t|tr|D ]R}	||d||f < | jrT| j|	}	|	|d||f < |rxd|d||f < |d7 }q.nF||d||f < | jr| j|}||d||f < |rd|d||f < |d7 }qd S )N   z
%s.%d.Namez%s.%d.Valuetruez%s.%d.Replace)sortedkeys
isinstancelistr,   encode)
r   params
attributesreplacelabelr;   ikeyvaluevr   r   r   _build_name_value_list   s(    
z$SDBConnection._build_name_value_listc                 C   sH   |d |d< |d dkr"d|d< n"|d dkr8d|d< n|d |d	< d S )
Nr   zExpected.1.Namer8   Tr9   zExpected.1.ExistsFfalsezExpected.1.Valuer   )r   r?   expected_valuer   r   r   _build_expected_value   s    

z#SDBConnection._build_expected_valuec                 C   s  |  }d}|D ]}||d| < d}|| }|d k	r|  }	|	D ]}
||
 }t|tr|D ]R}| jrr| j|}|
|d||f < ||d||f < |rd|d||f < |d7 }q\qB|
|d||f < | jr| j|}||d||f < |rd|d||f < |d7 }qB|d7 }qd S )Nr   zItem.%d.ItemNamezItem.%d.Attribute.%d.NamezItem.%d.Attribute.%d.Valuer9   zItem.%d.Attribute.%d.Replacer8   )r;   r<   r=   r,   r>   )r   r?   r   rA   r   rC   r   jr   
attr_names	attr_namerE   rF   r   r   r   _build_batch_list   s6    


zSDBConnection._build_batch_listc                 C   s.   d}|   |D ]}||d| < |d7 }qd S )Nr8   zAttribute.%d.Name)sort)r   r?   attribute_namesrC   r
   r   r   r   _build_name_list   s
    zSDBConnection._build_name_listc                 C   s   | j S )a  
        Returns the BoxUsage (in USD) accumulated on this specific SDBConnection
        instance.

        .. tip:: This can be out of date, and should only be treated as a
            rough estimate. Also note that this estimate only applies to the
            requests made on this specific connection instance. It is by
            no means an account-wide estimate.

        :rtype: float
        :return: The accumulated BoxUsage of all requests made on the connection.
        )r+   r3   r   r   r   	get_usage   s    zSDBConnection.get_usagec                 C   s(   t d| j  | jd }t d|  dS )a  
        Print the BoxUsage and approximate costs of all requests made on
        this specific SDBConnection instance.

        .. tip:: This can be out of date, and should only be treated as a
            rough estimate. Also note that this estimate only applies to the
            requests made on this specific connection instance. It is by
            no means an account-wide estimate.
        zTotal Usage: %f compute secondsgQ?zApproximate Cost: $%fN)printr+   )r   Zcostr   r   r   print_usage   s    

zSDBConnection.print_usagec                 C   s"   t | |}|r| |d|  |S )a  
        Retrieves a :py:class:`boto.sdb.domain.Domain` object whose name
        matches ``domain_name``.

        :param str domain_name: The name of the domain to retrieve
        :keyword bool validate: When ``True``, check to see if the domain
            actually exists. If ``False``, blindly return a
            :py:class:`Domain <boto.sdb.domain.Domain>` object with the
            specified name set.

        :raises:
            :py:class:`boto.exception.SDBResponseError` if ``validate`` is
            ``True`` and no match could be found.

        :rtype: :py:class:`boto.sdb.domain.Domain`
        :return: The requested domain
        zselect * from `%s` limit 1)r   selectr   r   validatedomainr   r   r   
get_domain   s    
zSDBConnection.get_domainc                 C   s&   z|  ||}W n   d}Y nX |S )a  
        Lookup an existing SimpleDB domain. This differs from
        :py:meth:`get_domain` in that ``None`` is returned if ``validate`` is
        ``True`` and no match was found (instead of raising an exception).

        :param str domain_name: The name of the domain to retrieve

        :param bool validate: If ``True``, a ``None`` value will be returned
            if the specified domain can't be found. If ``False``, a
            :py:class:`Domain <boto.sdb.domain.Domain>` object will be dumbly
            returned, regardless of whether it actually exists.

        :rtype: :class:`boto.sdb.domain.Domain` object or ``None``
        :return: The Domain object or ``None`` if the domain does not exist.
        N)rY   rV   r   r   r   lookup  s
    
zSDBConnection.lookupc                 C   s0   i }|r||d< |r||d< |  d|dtfgS )aI  
        Returns a :py:class:`boto.resultset.ResultSet` containing
        all :py:class:`boto.sdb.domain.Domain` objects associated with
        this connection's Access Key ID.

        :keyword int max_domains: Limit the returned
            :py:class:`ResultSet <boto.resultset.ResultSet>` to the specified
            number of members.
        :keyword str next_token: A token string that was returned in an
            earlier call to this method as the ``next_token`` attribute
            on the returned :py:class:`ResultSet <boto.resultset.ResultSet>`
            object. This attribute is set if there are more than Domains than
            the value specified in the ``max_domains`` keyword. Pass the
            ``next_token`` value from you earlier query in this keyword to
            get the next 'page' of domains.
        ZMaxNumberOfDomains	NextTokenZListDomains
DomainName)get_listr   )r   Zmax_domains
next_tokenr?   r   r   r   get_all_domains  s    zSDBConnection.get_all_domainsc                 C   s    d|i}|  d|t}||_|S )z
        Create a SimpleDB domain.

        :type domain_name: string
        :param domain_name: The name of the new domain

        :rtype: :class:`boto.sdb.domain.Domain` object
        :return: The newly created domain
        r\   ZCreateDomain)
get_objectr   r
   )r   r   r?   dr   r   r   create_domain6  s    
zSDBConnection.create_domainc                 C   s&   t |tr||jfS | ||fS dS )a  
        Given a ``str`` or :class:`boto.sdb.domain.Domain`, return a
        ``tuple`` with the following members (in order):

            * In instance of :class:`boto.sdb.domain.Domain` for the requested
              domain
            * The domain's name as a ``str``

        :type domain_or_name: ``str`` or :class:`boto.sdb.domain.Domain`
        :param domain_or_name: The domain or domain name to get the domain
            and name for.

        :raises: :class:`boto.exception.SDBResponseError` when an invalid
            domain name is specified.

        :rtype: tuple
        :return: A ``tuple`` with contents outlined as per above.
        N)r<   r   r
   rY   )r   domain_or_namer   r   r   get_domain_and_nameE  s    

z!SDBConnection.get_domain_and_namec                 C   s"   |  |\}}d|i}| d|S )aX  
        Delete a SimpleDB domain.

        .. caution:: This will delete the domain and all items within the domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :rtype: bool
        :return: True if successful

        r\   ZDeleteDomain)rd   
get_status)r   rc   rX   r   r?   r   r   r   delete_domain]  s    zSDBConnection.delete_domainc                 C   s.   |  |\}}d|i}| d|t}||_|S )aR  
        Get the Metadata for a SimpleDB domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :rtype: :class:`boto.sdb.domain.DomainMetaData` object
        :return: The newly created domain metadata object
        r\   ZDomainMetadata)rd   r`   r   rX   )r   rc   rX   r   r?   ra   r   r   r   domain_metadatan  s
    
zSDBConnection.domain_metadatac           	      C   sB   |  |\}}||d}| ||| |r6| || | d|S )a  
        Store attributes for a given item in a domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :type item_name: string
        :param item_name: The name of the item whose attributes are being
                          stored.

        :type attribute_names: dict or dict-like object
        :param attribute_names: The name/value pairs to store as attributes

        :type expected_value: list
        :param expected_value: If supplied, this is a list or tuple consisting
            of a single attribute name and expected value. The list can be
            of the form:

                * ['name', 'value']

            In which case the call will first verify that the attribute "name"
            of this item has a value of "value".  If it does, the delete
            will proceed, otherwise a ConditionalCheckFailed error will be
            returned. The list can also be of the form:

                * ['name', True|False]

            which will simply check for the existence (True) or
            non-existence (False) of the attribute.

        :type replace: bool
        :param replace: Whether the attribute values passed in will replace
                        existing values or will be added as addition values.
                        Defaults to True.

        :rtype: bool
        :return: True if successful
        r\   ZItemNameZPutAttributes)rd   rG   rJ   re   )	r   rc   r   r@   rA   rI   rX   r   r?   r   r   r   put_attributes~  s    (zSDBConnection.put_attributesc                 C   s4   |  |\}}d|i}| ||| | jd|ddS )a|  
        Store attributes for multiple items in a domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :type items: dict or dict-like object
        :param items: A dictionary-like object.  The keys of the dictionary are
                      the item names and the values are themselves dictionaries
                      of attribute names/values, exactly the same as the
                      attribute_names parameter of the scalar put_attributes
                      call.

        :type replace: bool
        :param replace: Whether the attribute values passed in will replace
                        existing values or will be added as addition values.
                        Defaults to True.

        :rtype: bool
        :return: True if successful
        r\   ZBatchPutAttributesPOSTZverbrd   rN   re   )r   rc   r   rA   rX   r   r?   r   r   r   batch_put_attributes  s    z"SDBConnection.batch_put_attributesc                 C   s   |  |\}}||d}|r$d|d< |rFt|ts8|g}| ||d | d|}	|	 }
|	jdkr|dkrx| ||}t	|| }t
j|
| |S t|	j|	j|
dS )a  
        Retrieve attributes for a given item in a domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :type item_name: string
        :param item_name: The name of the item whose attributes are
            being retrieved.

        :type attribute_names: string or list of strings
        :param attribute_names: An attribute name or list of attribute names.
            This parameter is optional.  If not supplied, all attributes will
            be retrieved for the item.

        :type consistent_read: bool
        :param consistent_read: When set to true, ensures that the most recent
            data is returned.

        :type item: :class:`boto.sdb.item.Item`
        :keyword item: Instead of instantiating a new Item object, you may
            specify one to update.

        :rtype: :class:`boto.sdb.item.Item`
        :return: An Item with the requested attribute name/values set on it
        rh   r9   ConsistentReadZAttributeNameZGetAttributes   N)rd   r<   r=   Zbuild_list_paramsZmake_requestreadstatusr-   r   Z
XmlHandlerxmlsaxparseStringr   reason)r   rc   r   rP   consistent_readr   rX   r   r?   responsebodyhr   r   r   r     s&    

zSDBConnection.get_attributesc                 C   sr   |  |\}}||d}|rVt|tr4| || n"t|tsJt|| jrV| || |rf| || | d|S )a  
        Delete attributes from a given item in a domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :type item_name: string
        :param item_name: The name of the item whose attributes are being
                          deleted.

        :type attributes: dict, list or :class:`boto.sdb.item.Item`
        :param attributes: Either a list containing attribute names which
                           will cause all values associated with that attribute
                           name to be deleted or a dict or Item containing the
                           attribute names and keys and list of values to
                           delete as the value.  If no value is supplied,
                           all attribute name/values for the item will be
                           deleted.

        :type expected_value: list
        :param expected_value: If supplied, this is a list or tuple consisting
            of a single attribute name and expected value. The list can be
            of the form:

                * ['name', 'value']

            In which case the call will first verify that the attribute "name"
            of this item has a value of "value".  If it does, the delete
            will proceed, otherwise a ConditionalCheckFailed error will be
            returned. The list can also be of the form:

                * ['name', True|False]

            which will simply check for the existence (True) or
            non-existence (False) of the attribute.

        :rtype: bool
        :return: True if successful
        rh   ZDeleteAttributes)	rd   r<   r=   rQ   dictr-   rG   rJ   re   )r   rc   r   rL   rI   rX   r   r?   r   r   r   delete_attributes  s    )
zSDBConnection.delete_attributesc                 C   s4   |  |\}}d|i}| ||d | jd|ddS )a]  
        Delete multiple items in a domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
        :param domain_or_name: Either the name of a domain or a Domain object

        :type items: dict or dict-like object
        :param items: A dictionary-like object.  The keys of the dictionary are
            the item names and the values are either:

                * dictionaries of attribute names/values, exactly the
                  same as the attribute_names parameter of the scalar
                  put_attributes call.  The attribute name/value pairs
                  will only be deleted if they match the name/value
                  pairs passed in.
                * None which means that all attributes associated
                  with the item should be deleted.

        :return: True if successful
        r\   FZBatchDeleteAttributesrj   rk   rl   )r   rc   r   rX   r   r?   r   r   r   batch_delete_attributes.  s    z%SDBConnection.batch_delete_attributes c           	   
   C   s   |  |\}}d|i}|r"d|d< |r.||d< z| jd|d| jfg|dW S  tk
r } zd||jf |_|W 5 d	}~X Y nX d	S )
a  
        Returns a set of Attributes for item names within domain_name that
        match the query.  The query must be expressed in using the SELECT
        style syntax rather than the original SimpleDB query language.
        Even though the select request does not require a domain object,
        a domain object must be passed into this method so the Item objects
        returned can point to the appropriate domain.

        :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object
        :param domain_or_name: Either the name of a domain or a Domain object

        :type query: string
        :param query: The SimpleDB query to be performed.

        :type consistent_read: bool
        :param consistent_read: When set to true, ensures that the most recent
                                data is returned.

        :rtype: ResultSet
        :return: An iterator containing the results.
        ZSelectExpressionr9   rn   r[   ZSelectr   )parentzQuery: %s
%sN)rd   r]   r-   r   rx   )	r   rc   queryr^   rv   rX   r   r?   er   r   r   rU   H  s    zSDBConnection.select)NNTNNNNNr   NNr!   NNTN)Fr7   )F)T)T)NN)TN)T)NFN)NN)r}   NF) r   r   r   r   r)   ZDefaultRegionEndpointZ
APIVersionr   ResponseErrorr   r4   r6   rG   rJ   rN   rQ   rR   rT   rY   rZ   r_   rb   rd   rf   rg   ri   rm   r   r{   r|   rU   r    r   r   r   r   r   D   sj   
                        +  
	



   
0
    
0  
5  r   )Zxml.saxrr   	threadingr&   r   Zboto.connectionr   Zboto.sdb.domainr   r   Zboto.sdb.itemr   Zboto.sdb.regioninfor   Zboto.exceptionr   Threadr	   r   r   r   r   r   <module>   s   %