U
    3dtN                     @   s0   d Z ddlmZ ddlmZ G dd deZdS )z
Represents an SQS Queue
    )urllib)Messagec                   @   s`  e Zd ZddefddZdd Zdd ZeeZdd	 Z	ee	Z
d
d ZeeZdd Zdd Zdd ZdKddZdd Zdd Zdd Zdd Zdd ZdLdd ZdMd!d"Zd#d$ ZdNd&d'ZdOd)d*Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 ZdPd6d7Z dQd8d9Z!dRd:d;Z"dSd=d>Z#dTd?d@Z$dUdAdBZ%e%Z&dCdD Z'dVdEdFZ(dWdGdHZ)dXdIdJZ*e*Z+dS )YQueueNc                 C   s   || _ || _|| _d | _d S N)
connectionurlmessage_classvisibility_timeout)selfr   r   r    r   2/tmp/pip-unpacked-wheel-d7dsrkjd/boto/sqs/queue.py__init__   s    zQueue.__init__c                 C   s
   d| j  S )Nz	Queue(%s))r   r
   r   r   r   __repr__%   s    zQueue.__repr__c                 C   s$   | j rtj| j d }n| j }|S )N   )r   r   parseurlparser
   valr   r   r   _id(   s    z	Queue._idc                 C   s.   | j r$tj| j d dd }n| j }|S )Nr   /)r   r   r   r   splitr   r   r   r   _name0   s    zQueue._namec                 C   sB   | j d}| jjjdkr d}nd}d|| jjj|d |d f S )Nr   z
cn-north-1zaws-cnZawszarn:%s:sqs:%s:%s:%s   r   )idr   r   Zregionname)r
   parts	partitionr   r   r   _arn8   s       z
Queue._arnc                 C   s   d S r   r   )r
   r   attrsr   r   r   r   startElementB   s    zQueue.startElementc                 C   s4   |dkr|| _ n |dkr$t|| _nt| || d S )NZQueueUrlVisibilityTimeout)r   intr	   setattr)r
   r   valuer   r   r   r   
endElementE   s
    zQueue.endElementc                 C   s
   || _ dS )aq  
        Set the message class that should be used when instantiating
        messages read from the queue.  By default, the class
        :class:`boto.sqs.message.Message` is used but this can be overriden
        with any class that behaves like a message.

        :type message_class: Message-like class
        :param message_class:  The new Message class
        N)r   )r
   r   r   r   r   set_message_classM   s    
zQueue.set_message_classAllc                 C   s   | j | |S )a  
        Retrieves attributes about this queue object and returns
        them in an Attribute instance (subclass of a Dictionary).

        :type attributes: string
        :param attributes: String containing one of:
                           ApproximateNumberOfMessages,
                           ApproximateNumberOfMessagesNotVisible,
                           VisibilityTimeout,
                           CreatedTimestamp,
                           LastModifiedTimestamp,
                           Policy
                           ReceiveMessageWaitTimeSeconds
        :rtype: Attribute object
        :return: An Attribute object which is a mapping type holding the
                 requested name/value pairs
        )r   Zget_queue_attributes)r
   
attributesr   r   r   get_attributesY   s    zQueue.get_attributesc                 C   s   | j | ||S )a
  
        Set a new value for an attribute of the Queue.

        :type attribute: String
        :param attribute: The name of the attribute you want to set.

        :param value: The new value for the attribute must be:


            * For `DelaySeconds` the value must be an integer number of
            seconds from 0 to 900 (15 minutes).
                >>> queue.set_attribute('DelaySeconds', 900)

            * For `MaximumMessageSize` the value must be an integer number of
            bytes from 1024 (1 KiB) to 262144 (256 KiB).
                >>> queue.set_attribute('MaximumMessageSize', 262144)

            * For `MessageRetentionPeriod` the value must be an integer number of
            seconds from 60 (1 minute) to 1209600 (14 days).
                >>> queue.set_attribute('MessageRetentionPeriod', 1209600)

            * For `Policy` the value must be an string that contains JSON formatted
            parameters and values.
                >>> queue.set_attribute('Policy', json.dumps({
                ...     'Version': '2008-10-17',
                ...     'Id': '/123456789012/testQueue/SQSDefaultPolicy',
                ...     'Statement': [
                ...        {
                ...            'Sid': 'Queue1ReceiveMessage',
                ...            'Effect': 'Allow',
                ...            'Principal': {
                ...                'AWS': '*'
                ...            },
                ...            'Action': 'SQS:ReceiveMessage',
                ...            'Resource': 'arn:aws:aws:sqs:us-east-1:123456789012:testQueue'
                ...        }
                ...    ]
                ... }))

            * For `ReceiveMessageWaitTimeSeconds` the value must be an integer number of
            seconds from 0 to 20.
                >>> queue.set_attribute('ReceiveMessageWaitTimeSeconds', 20)

            * For `VisibilityTimeout` the value must be an integer number of
            seconds from 0 to 43200 (12 hours).
                >>> queue.set_attribute('VisibilityTimeout', 43200)

            * For `RedrivePolicy` the value must be an string that contains JSON formatted
            parameters and values. You can set maxReceiveCount to a value between 1 and 1000.
            The deadLetterTargetArn value is the Amazon Resource Name (ARN) of the queue that
            will receive the dead letter messages.
                >>> queue.set_attribute('RedrivePolicy', json.dumps({
                ...    'maxReceiveCount': 5,
                ...    'deadLetterTargetArn': "arn:aws:aws:sqs:us-east-1:123456789012:testDeadLetterQueue"
                ... }))

        :rtype: bool
        :return: True if successful, otherwise False.
        )r   Zset_queue_attribute)r
   	attributer$   r   r   r   set_attributem   s    <zQueue.set_attributec                 C   s   |  d}t|d S )z
        Get the visibility timeout for the queue.

        :rtype: int
        :return: The number of seconds as an integer.
        r!   r)   r"   )r
   ar   r   r   get_timeout   s    
zQueue.get_timeoutc                 C   s   |  d|}|r|| _|S )z
        Set the visibility timeout for the queue.

        :type visibility_timeout: int
        :param visibility_timeout: The desired timeout in seconds
        r!   )r+   r	   )r
   r	   retvalr   r   r   set_timeout   s    zQueue.set_timeoutc                 C   s   | j | |||S )as  
        Add a permission to a queue.

        :type label: str or unicode
        :param label: A unique identification of the permission you are setting.
            Maximum of 80 characters ``[0-9a-zA-Z_-]``
            Example, AliceSendMessage

        :type aws_account_id: str or unicode
        :param principal_id: The AWS account number of the principal who
            will be given permission.  The principal must have an AWS account,
            but does not need to be signed up for Amazon SQS. For information
            about locating the AWS account identification.

        :type action_name: str or unicode
        :param action_name: The action.  Valid choices are:
            SendMessage|ReceiveMessage|DeleteMessage|
            ChangeMessageVisibility|GetQueueAttributes|*

        :rtype: bool
        :return: True if successful, False otherwise.

        )r   add_permission)r
   labelZaws_account_idaction_namer   r   r   r1      s    zQueue.add_permissionc                 C   s   | j | |S )a  
        Remove a permission from a queue.

        :type label: str or unicode
        :param label: The unique label associated with the permission
            being removed.

        :rtype: bool
        :return: True if successful, False otherwise.
        )r   remove_permission)r
   r2   r   r   r   r4      s    zQueue.remove_permissionc                 C   s.   | j d|||d}t|dkr&|d S dS dS )aD  
        Read a single message from the queue.

        :type visibility_timeout: int
        :param visibility_timeout: The timeout for this message in seconds

        :type wait_time_seconds: int
        :param wait_time_seconds: The duration (in seconds) for which the call
            will wait for a message to arrive in the queue before returning.
            If a message is available, the call will return sooner than
            wait_time_seconds.

        :type message_attributes: list
        :param message_attributes: The name(s) of additional message
            attributes to return. The default is to return no additional
            message attributes. Use ``['All']`` or ``['.*']`` to return all.

        :rtype: :class:`boto.sqs.message.Message`
        :return: A single message or None if queue is empty
        r   )wait_time_secondsmessage_attributesr   N)get_messageslen)r
   r	   r5   r6   rsr   r   r   read   s    z
Queue.readc                 C   s.   | j j| | ||jd}|j|_|j|_|S )a  
        Add a single message to the queue.

        :type message: Message
        :param message: The message to be written to the queue

        :rtype: :class:`boto.sqs.message.Message`
        :return: The :class:`boto.sqs.message.Message` object that was written.
        )delay_secondsr6   )r   send_messageZget_body_encodedr6   r   md5)r
   messager;   Znew_msgr   r   r   write  s    
 zQueue.writec                 C   s   | j | |S )a  
        Delivers up to 10 messages in a single request.

        :type messages: List of lists.
        :param messages: A list of lists or tuples.  Each inner
            tuple represents a single message to be written
            and consists of and ID (string) that must be unique
            within the list of messages, the message body itself
            which can be a maximum of 64K in length, an
            integer which represents the delay time (in seconds)
            for the message (0-900) before the message will
            be delivered to the queue, and an optional dict of
            message attributes like those passed to ``send_message``
            in the connection class.
        )r   Zsend_message_batchr
   messagesr   r   r   write_batch  s    zQueue.write_batch c                 K   s   | j | |f|}| |_|S )z
        Create new message of appropriate class.

        :type body: message body
        :param body: The body of the newly created message (optional).

        :rtype: :class:`boto.sqs.message.Message`
        :return: A new Message object
        )r   queue)r
   bodykwargsmr   r   r   new_message*  s    
zQueue.new_messager   c                 C   s   | j j| |||||dS )a  
        Get a variable number of messages.

        :type num_messages: int
        :param num_messages: The maximum number of messages to read from
            the queue.

        :type visibility_timeout: int
        :param visibility_timeout: The VisibilityTimeout for the messages read.

        :type attributes: str
        :param attributes: The name of additional attribute to return
            with response or All if you want all attributes.  The
            default is to return no additional attributes.  Valid
            values: All SenderId SentTimestamp ApproximateReceiveCount
            ApproximateFirstReceiveTimestamp

        :type wait_time_seconds: int
        :param wait_time_seconds: The duration (in seconds) for which the call
            will wait for a message to arrive in the queue before returning.
            If a message is available, the call will return sooner than
            wait_time_seconds.

        :type message_attributes: list
        :param message_attributes: The name(s) of additional message
            attributes to return. The default is to return no additional
            message attributes. Use ``['All']`` or ``['.*']`` to return all.

        :rtype: list
        :return: A list of :class:`boto.sqs.message.Message` objects.
        )Znumber_messagesr	   r(   r5   r6   )r   Zreceive_message)r
   Znum_messagesr	   r(   r5   r6   r   r   r   r7   9  s    "  zQueue.get_messagesc                 C   s   | j | |S )a  
        Delete a message from the queue.

        :type message: :class:`boto.sqs.message.Message`
        :param message: The :class:`boto.sqs.message.Message` object to delete.

        :rtype: bool
        :return: True if successful, False otherwise
        )r   delete_message)r
   r>   r   r   r   rI   a  s    
zQueue.delete_messagec                 C   s   | j | |S )z
        Deletes a list of messages in a single request.

        :type messages: List of :class:`boto.sqs.message.Message` objects.
        :param messages: A list of message objects.
        )r   delete_message_batchr@   r   r   r   rJ   m  s    zQueue.delete_message_batchc                 C   s   | j | |S )ar  
        A batch version of change_message_visibility that can act
        on up to 10 messages at a time.

        :type messages: List of tuples.
        :param messages: A list of tuples where each tuple consists
            of a :class:`boto.sqs.message.Message` object and an integer
            that represents the new visibility timeout for that message.
        )r   change_message_visibility_batchr@   r   r   r   rK   v  s    
z%Queue.change_message_visibility_batchc                 C   s   | j | S )z#
        Delete the queue.
        )r   Zdelete_queuer   r   r   r   delete  s    zQueue.deletec                 C   s   | j | S )z2
        Purge all messages in the queue.
        )r   Zpurge_queuer   r   r   r   purge  s    zQueue.purge
   c                 C   s   |   S )z?Deprecated utility function to remove all messages from a queue)rM   )r
   	page_sizevtimeoutr   r   r   clear  s    zQueue.clearc                 C   s   |  d}t|d S )z
        Utility function to count the number of messages in a queue.
        Note: This function now calls GetQueueAttributes to obtain
        an 'approximate' count of the number of messages in a queue.
        ZApproximateNumberOfMessagesr,   )r
   rO   rP   r-   r   r   r   count  s    
zQueue.countc                 C   s8   d}|  ||}|r4|D ]}|d7 }q|  ||}q|S )a  
        Deprecated.  This is the old 'count' method that actually counts
        the messages by reading them all.  This gives an accurate count but
        is very slow for queues with non-trivial number of messasges.
        Instead, use get_attributes('ApproximateNumberOfMessages') to take
        advantage of the new SQS capability.  This is retained only for
        the unit tests.
        r   r   )r7   )r
   rO   rP   nlrG   r   r   r   
count_slow  s    	
zQueue.count_slow
c           	      C   sf   t |d}d}| ||}|rZ|D ](}||  |rB|| |d7 }q"| ||}q|  |S )zoUtility function to dump the messages in a queue to a file
        NOTE: Page size must be < 10 else SQS errorswbr   r   )openr7   r?   get_bodyclose)	r
   	file_namerO   rP   sepfprS   rT   rG   r   r   r   dump  s    


z
Queue.dumpc                 C   sL   d}|   }|rH|d7 }||  |r4|| | | |   }q|S )a:  
        Read all messages from the queue and persist them to file-like object.
        Messages are written to the file and the 'sep' string is written
        in between messages.  Messages are deleted from the queue after
        being written to the file.
        Returns the number of messages saved.
        r   r   )r:   r?   rY   rI   )r
   r]   r\   rS   rG   r   r   r   save_to_file  s    


zQueue.save_to_filec                 C   s"   t |d}| ||}|  |S )a4  
        Read all messages from the queue and persist them to local file.
        Messages are written to the file and the 'sep' string is written
        in between messages.  Messages are deleted from the queue after
        being written to the file.
        Returns the number of messages saved.
        rW   )rX   r_   rZ   r
   r[   r\   r]   rS   r   r   r   save_to_filename  s    
zQueue.save_to_filenamec                 C   sT   d}|   }|rP|d7 }|d| j|jf }||  | | |   }q|S )a+  
        Read all messages from the queue and persist them to S3.
        Messages are stored in the S3 bucket using a naming scheme of::

            <queue_id>/<message_id>

        Messages are deleted from the queue after being saved to S3.
        Returns the number of messages saved.
        r   r   z%s/%s)r:   Znew_keyr   Zset_contents_from_stringrY   rI   )r
   bucketrS   rG   keyr   r   r   
save_to_s3  s    


zQueue.save_to_s3c                 C   s^   d}|rd| }nd| j dd  }|j|d}|D ]$}|d7 }| | }| | q4|S )z7
        Load messages previously saved to S3.
        r   z%s/r   N)prefix)r   listrH   Zget_contents_as_stringr?   )r
   rb   re   rS   r9   rc   rG   r   r   r   load_from_s3  s    
zQueue.load_from_s3c                 C   s`   d}d}|  }|r\||krJt| |}| | |d7 }td|  d}n|| }|  }q|S )zDUtility function to load messages from a file-like object to a queuer   rC   r   zwriting message %d)readliner   r?   print)r
   r]   r\   rS   rE   rT   rG   r   r   r   load_from_file  s    


zQueue.load_from_filec                 C   s"   t |d}| ||}|  |S )zBUtility function to load messages from a local filename to a queuerb)rX   rj   rZ   r`   r   r   r   load_from_filename  s    
zQueue.load_from_filename)r'   )NNN)N)rC   )r   NNNN)rN   rN   )rN   rN   )rN   rN   )rN   rN   rV   )rV   )rV   )N)rV   )rV   ),__name__
__module____qualname__r   r   r   r   propertyr   r   r   r   Zarnr    r%   r&   r)   r+   r.   r0   r1   r4   r:   r?   rB   rH   r7   rI   rJ   rK   rL   rM   rQ   rR   rU   r^   r_   ra   saverd   rg   rj   rl   loadr   r   r   r   r      sZ   
>
  


     
(	

	






r   N)__doc__Zboto.compatr   Zboto.sqs.messager   objectr   r   r   r   r   <module>   s   