You are on page 1of 14

class Rt(builtins.

object):
:term:`API` for Request Tracker according to
http://requesttracker.wikia.com/wiki/REST. Interface is based on
:term:`REST` architecture, which is based on HTTP/1.1 protocol. This module
is therefore mainly sending and parsing special HTTP messages.

.. note:: Use only ASCII LF as newline (``\n``). Time is returned in UTC.


All strings returned are encoded in UTF-8 and the same is
expected as input for string values.

Methods defined here:

__init__(self, url, default_login=None, default_password=None, proxy=None,


default_queue='General', basic_auth=None, digest_auth=None, skip_login=False, verify_cert=True)
API initialization.

:keyword url: Base URL for Request Tracker API.


E.g.: http://tracker.example.com/REST/1.0/
:keyword default_login: Default RT login used by self.login if no
other credentials are provided
:keyword default_password: Default RT password
:keyword proxy: Proxy server (string with http://user:password@host/ syntax)
:keyword default_queue: Default RT queue
:keyword basic_auth: HTTP Basic authentication credentials, tuple (UN, PW)
:keyword digest_auth: HTTP Digest authentication credentials, tuple (UN, PW)
:keyword skip_login: Set this option True when HTTP Basic authentication
credentials for RT are in .netrc file. You do not
need to call login, because it is managed by
requests library instantly.

comment(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[])


Adds comment to the given ticket.

Form of message according to documentation::

id: <ticket-id>
Action: comment
Text: the text comment
second line starts with the same indentation as first
Attachment: an attachment filename/path

Example::

>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')


>>> attachment_name = sys.argv[1]
>>> message_text = ' '.join(sys.argv[2:])
>>> ret = tracker.comment(ticket_id, text=message_text,
... files=[(attachment_name, open(attachment_name, 'rb'))])
>>> if not ret:
... print('Error: could not send attachment', file=sys.stderr)
... exit(1)

:param ticket_id: ID of ticket to which comment belongs


:keyword text: Content of comment
:keyword content_type: Content type of comment, default to text/plain
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist

create_queue(self, Name, **kwargs)


Create queue (undocumented API feature).

:param Name: Queue name (required)


:param kwargs: Optional fields to set (see edit_queue)
:returns: ID of new queue or False when create fails
:raises BadRequest: When queue already exists
:raises InvalidUse: When invalid fields are set

create_ticket(self, Queue=None, files=[], **kwargs)


Create new ticket and set given parameters.

Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::

content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: somebody@example.com
Subject: Ticket created through REST API
Text: Lorem Ipsum

In case of success returned message has this form::

RT/3.8.7 200 Ok

# Ticket 123456 created.


# Ticket 123456 updated.

Otherwise::

RT/3.8.7 200 Ok

# Required: id, Queue

+ list of some key, value pairs, probably default values.


:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:

Requestors, Subject, Cc, AdminCc, Owner, Status,


Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)

Custom fields CF.{<CustomFieldName>} could be set


with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed

create_user(self, Name, EmailAddress, **kwargs)


Create user (undocumented API feature).

:param Name: User name (login for privileged, required)


:param EmailAddress: Email address (required)
:param kwargs: Optional fields to set (see edit_user)
:returns: ID of new user or False when create fails
:raises BadRequest: When user already exists
:raises InvalidUse: When invalid fields are set

edit_link(self, ticket_id, link_name, link_value, delete=False)


Creates or deletes a link between the specified tickets (undocumented API feature).

:param ticket_id: ID of ticket to edit


:param link_name: Name of link to edit (DependsOn, DependedOnBy,
RefersTo, ReferredToBy, HasMember or MemberOf)
:param link_value: Either ticker ID or external link.
:param delete: if True the link is deleted instead of created
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or link to delete is
not found
:raises InvalidUse: When none or more then one links are specified. Also
when wrong link name is used.

edit_queue(self, queue_id, **kwargs)


Edit queue (undocumented API feature).

:param queue_id: Identification of queue by name (str) or ID (int)


:param kwargs: Other fields to edit from the following list:

* Name
* Description
* CorrespondAddress
* CommentAddress
* InitialPriority
* FinalPriority
* DefaultDueIn

:returns: ID or name of edited queue or False when edit fails


:raises BadRequest: When queue does not exist
:raises InvalidUse: When invalid fields are set

edit_ticket(self, ticket_id, **kwargs)


Edit ticket values.

:param ticket_id: ID of ticket to edit


:keyword kwargs: Other arguments possible to set:

Requestors, Subject, Cc, AdminCc, Owner, Status,


Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)

Custom fields CF.{<CustomFieldName>} could be set


with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)

edit_ticket_links(self, ticket_id, **kwargs)


Edit ticket links.

.. warning:: This method is deprecated in favour of edit_link method, because


there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.

:param ticket_id: ID of ticket to edit


:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
edit_user(self, user_id, **kwargs)
Edit user profile (undocumented API feature).

:param user_id: Identification of user by username (str) or user ID


(int)
:param kwargs: Other fields to edit from the following list:

* Name
* Password
* EmailAddress
* RealName
* NickName
* Gecos
* Organization
* Address1
* Address2
* City
* State
* Zip
* Country
* HomePhone
* WorkPhone
* MobilePhone
* PagerPhone
* ContactInfo
* Comments
* Signature
* Lang
* EmailEncoding
* WebEncoding
* ExternalContactInfoId
* ContactInfoSystem
* ExternalAuthId
* AuthSystem
* Privileged
* Disabled

:returns: ID of edited user or False when edit fails


:raises BadRequest: When user does not exist
:raises InvalidUse: When invalid fields are set

get_attachment(self, ticket_id, attachment_id)


Get attachment.

:param ticket_id: ID of ticket


:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:

* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject

All these fields are strings, just 'Headers' holds another


dictionary with attachment headers as strings e.g.:

* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject

.. warning:: Content-Length parameter is set after opening


ticket in web interface!

Set of headers available depends on mailservers sending


emails not on Request Tracker!

Returns None if ticket or attachment does not exist.


:raises UnexpectedMessageFormat: Unexpected format of returned message.

get_attachment_content(self, ticket_id, attachment_id)


Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.

Format of message::

RT/3.8.7 200 Ok

Start of the content...End of the content

:param ticket_id: ID of ticket


:param attachment_id: ID of attachment

Returns: Bytes with content of attachment or None if ticket or


attachment does not exist.

get_attachments(self, ticket_id)
Get attachment list for a given ticket

:param ticket_id: ID of ticket


:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist.

get_attachments_ids(self, ticket_id)
Get IDs of attachments for given ticket.

:param ticket_id: ID of ticket


:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist.

get_history(self, ticket_id, transaction_id=None)


Get set of history items.

:param ticket_id: ID of ticket


:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned

:returns: List of history items ordered increasingly by time of event.


Each history item is dictionary with following keys:

Description, Creator, Data, Created, TimeTaken, NewValue,


Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).

Returns None if ticket or transaction does not exist.


:raises UnexpectedMessageFormat: Unexpected format of returned message.

get_links(self, ticket_id)
Gets the ticket links for a single ticket.

:param ticket_id: ticket ID


:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):

* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy

None is returned if ticket does not exist.


:raises UnexpectedMessageFormat: In case that returned status code is not 200

get_queue(self, queue_id)
Get queue details.

:param queue_id: Identification of queue by name (str) or queue ID


(int)
:returns: Queue details as strings in dictionary with these keys
if queue exists (otherwise None):

* id
* Name
* Description
* CorrespondAddress
* CommentAddress
* InitialPriority
* FinalPriority
* DefaultDueIn

:raises UnexpectedMessageFormat: In case that returned status code is not 200

get_short_history(self, ticket_id)
Get set of short history items

:param ticket_id: ID of ticket


:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist.

get_ticket(self, ticket_id)
Fetch ticket by its ID.

:param ticket_id: ID of demanded ticket

:returns: Dictionary with key, value pairs for ticket with


*ticket_id* or None if ticket does not exist. List of keys:

* id
* Queue
* Owner
* Creator
* Subject
* Status
* Priority
* InitialPriority
* FinalPriority
* Requestors
* Cc
* AdminCc
* Created
* Starts
* Started
* Due
* Resolved
* Told
* TimeEstimated
* TimeWorked
* TimeLeft
:raises UnexpectedMessageFormat: Unexpected format of returned message.

get_user(self, user_id)
Get user details.

:param user_id: Identification of user by username (str) or user ID


(int)
:returns: User details as strings in dictionary with these keys for RT
users:

* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name

Or these keys for external users (e.g. Requestors replying


to email from RT:

* RealName
* Disabled
* EmailAddress
* Password
* id
* Name

None is returned if user does not exist.


:raises UnexpectedMessageFormat: In case that returned status code is not 200

last_updated(self, since, queue=None)


Obtains tickets changed after given date.

:param since: Date as string in form '2011-02-24'


:keyword queue: Queue where to search

:returns: List of tickets with LastUpdated parameter later than


*since* ordered in decreasing order by LastUpdated.
Each tickets is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.

login(self, login=None, password=None)


Login with default or supplied credetials.

.. note::

Calling this method is not necessary when HTTP basic or HTTP


digest_auth authentication is used and RT accepts it as external
authentication method, because the login in this case is done
transparently by requests module. Anyway this method can be useful
to check whether given credentials are valid or not.

:keyword login: Username used for RT, if not supplied together with
*password* :py:attr:`~Rt.default_login` and
:py:attr:`~Rt.default_password` are used instead
:keyword password: Similarly as *login*

:returns: ``True``
Successful login
``False``
Otherwise
:raises AuthorizationError: In case that credentials are not supplied neither
during inicialization or call of this method.
logout(self)
Logout of user.

:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login)

merge_ticket(self, ticket_id, into_id)


Merge ticket into another (undocumented API feature).

:param ticket_id: ID of ticket to be merged


:param into: ID of destination ticket
:returns: ``True``
Operation was successful
``False``
Either origin or destination ticket does not
exist or user does not have ModifyTicket permission.

new_correspondence(self, queue=None)
Obtains tickets changed by other users than the system one.

:keyword queue: Queue where to search

:returns: List of tickets which were last updated by other user than
the system one ordered in decreasing order by LastUpdated.
Each ticket is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.

reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[])


Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.

Form of message according to documentation::

id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path

:param ticket_id: ID of ticket to which message belongs


:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist

search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs)


Search arbitrary needles in given fields and queue.

Example::

>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')


>>> tracker.login()
>>> tickets = tracker.search(CF_Domain='example.com', Subject__like='warning')
>>> tickets = tracker.search(Queue='General', order='Status',
raw_query="id='1'+OR+id='2'+OR+id='3'")

:keyword Queue: Queue where to search. If you wish to search across


all of your queues, pass the ALL_QUEUES object as the
argument.
:keyword order: Name of field sorting result list, for descending
order put - before the field name. E.g. -Created
will put the newest tickets at the beginning
:keyword raw_query: A raw query to provide to RT if you know what
you are doing. You may still pass Queue and order
kwargs, so use these instead of including them in
the raw query. You can refer to the RT query builder.
If passing raw_query, all other **kwargs will be ignored.
:keyword Format: Format of the query:
- i: only `id' fields are populated
- s: only `id' and `subject' fields are populated
- l: multi-line format, all fields are populated
:keyword kwargs: Other arguments possible to set if not passing raw_query:

Requestors, Subject, Cc, AdminCc, Owner, Status,


Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)

Custom fields CF.{<CustomFieldName>} could be set


with keywords CF_CustomFieldName.

To alter lookup operators you can append one of the


following endings to each keyword:

__exact for operator = (default)


__notexact for operator !=
__gt for operator >
__lt for operator <
__like for operator LIKE
__notlike for operator NOT LIKE

Setting values to keywords constrain search


result to the tickets satisfying all of them.

:returns: List of matching tickets. Each ticket is the same dictionary


as in :py:meth:`~Rt.get_ticket`.
:raises: UnexpectedMessageFormat: Unexpected format of returned message.
InvalidQueryError: If raw query is malformed

steal(self, ticket_id)
Steal ticket

:param ticket_id: ID of ticket to be merged


:returns: ``True``
Operation was successful
``False``
Either the ticket does not exist or user does not
have StealTicket permission.

take(self, ticket_id)
Take ticket

:param ticket_id: ID of ticket to be merged


:returns: ``True``
Operation was successful
``False``
Either the ticket does not exist or user does not
have TakeTicket permission.

untake(self, ticket_id)
Untake ticket

:param ticket_id: ID of ticket to be merged


:returns: ``True``
Operation was successful
``False``
Either the ticket does not exist or user does not
own the ticket.

----------------------------------------------------------------------
Data descriptors defined here:

__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

----------------------------------------------------------------------
Data and other attributes defined here:

RE_PATTERNS = {'attachments_list_pattern': re.compile('[^0-9]*(\\d+): ...

You might also like