Jira rest api python

6. API Documentation#

Initialise the Session object’s cookies, so we can use the session cookie.

HTTPError – if the post returns an erroring http response

Refresh cookies if the session cookie has expired. Then retry the request.

response (requests.Response) – the response with the possible 401 to handle

process_original_request ( original_request : PreparedRequest ) [source] # update_cookies ( original_request : PreparedRequest ) [source] # send_request ( request : PreparedRequest ) [source] # class jira.client. TokenAuth ( token : str ) [source] #

Bearer Token Authentication.

__init__ ( token : str ) [source] # class jira.client. JIRA ( server : str = None , options : dict [ str , str | bool | Any ] = None , basic_auth : tuple [ str , str ] | None = None , token_auth : str | None = None , oauth : dict [ str , Any ] = None , jwt : dict [ str , Any ] = None , kerberos = False , kerberos_options : dict [ str , Any ] = None , validate = False , get_server_info : bool = True , async_ : bool = False , async_workers : int = 5 , logging : bool = True , max_retries : int = 3 , proxies : Any = None , timeout : None | float | tuple [ float , float ] | tuple [ float , None ] | None = None , auth : tuple [ str , str ] = None , default_batch_sizes : dict [ type [ Resource ] , int | None ] | None = None ) [source] #

Clients interact with Jira by constructing an instance of this object and calling its methods. For addressable resources in Jira – those with “self” links – an appropriate subclass of jira.resources.Resource will be returned with customized update() and delete() methods, along with attribute access to fields. This means that calls of the form issue.fields.summary will be resolved into the proper lookups to return the JSON value at that mapping. Methods that do not return resources will return a dict constructed from the JSON response or a scalar value; see each method’s documentation for details on what that method returns.

Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the ‘atlas-run’, atlas-debug or atlas-run-standalone commands. By default, this instance runs at http://localhost:2990/jira . The options argument can be used to set the Jira instance to use.

Authentication is handled with the basic_auth argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests.

For quick command line access to a server, see the jirashell script included with this distribution.

The easiest way to instantiate is using j = JIRA(«https://jira.atlassian.com»)

Читайте также:  Режимы открытия файлов python

Construct a Jira client instance.

Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the ‘atlas-run’, atlas-debug or atlas-run-standalone commands. By default, this instance runs at http://localhost:2990/jira . The options argument can be used to set the Jira instance to use.

Authentication is handled with the basic_auth or token_auth argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests.

For quick command line access to a server, see the jirashell script included with this distribution.

The easiest way to instantiate is using j = JIRA(«https://jira.atlasian.com»)

  • server (Optional[str]) – The server address and context path to use. Defaults to http://localhost:2990/jira .
  • options (Optional[Dict[str,bool,Any]]) – Specify the server and properties this client will use. Use a dict with any of the following properties:
  • server – the server address and context path to use. Defaults to http://localhost:2990/jira .
  • rest_path – the root REST path to use. Defaults to api , where the Jira REST resources live.
  • rest_api_version – the version of the REST resources under rest_path to use. Defaults to 2 .
  • agile_rest_path — the REST path to use for Jira Agile requests. Defaults to agile .
  • verify (Union[bool, str]) – Verify SSL certs. (Default: True ). Or path to a CA_BUNDLE file or directory with certificates of trusted CAs, for the requests library to use.
  • client_cert (Union[str, Tuple[str,str]]) – Path to file with both cert and key or a tuple of (cert,key), for the requests library to use for client side SSL.
  • check_update – Check whether using the newest python-jira library version.
  • headers – a dict to update the default headers the session uses for all API requests.
  • access_token – OAuth access token for the user
  • access_token_secret – OAuth access token secret to sign with the key
  • consumer_key – key of the OAuth application link defined in Jira
  • key_cert – private key file to sign requests with (should be the pair of the public key supplied to Jira in the OAuth application link)
  • signature_method (Optional) – The signature method to use with OAuth. Defaults to oauthlib.oauth1.SIGNATURE_HMAC_SHA1
  • secret – shared secret as delivered during ‘installed’ lifecycle event (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details)
  • payload – dict of fields to be inserted in the JWT payload, e.g. ‘iss’

Источник

jira 3.5.2

Python library for interacting with JIRA via REST APIs.

Ссылки проекта

Статистика

Метаданные

Лицензия: BSD License (BSD-2-Clause)

Сопровождающий: Sorin Sbarnea

Метки api, atlassian, jira, rest, web

Требует: Python >=3.8

Сопровождающие

Классификаторы

Описание проекта

This library eases the use of the Jira REST API from Python and it has been used in production for years.

As this is an open-source project that is community maintained, do not be surprised if some bugs or features are not implemented quickly enough. You are always welcomed to use BountySource to motivate others to help.

Quickstart

Feeling impatient? I like your style.

Installation

Download and install using pip install jira or easy_install jira

You can also try pip install —user —upgrade jira which will install or upgrade jira to your user directory. Or maybe you ARE using a virtualenv right?

By default only the basic library dependencies are installed, so if you want to use the cli tool or other optional dependencies do perform a full installation using pip install jira[opt,cli,test]

Usage

See the documentation for full details.

Development

Development takes place on GitHub using the default repository branch. Each version is tagged.

Setup

Automatic (VS Code)

Follow the instructions in the contributing guide, which will describe how to use the dev container that will automatically setup a suitable environment.

Manual

  • Install pyenv to install a suitable python version.
  • Launch docker jira server
    • docker run -dit -p 2990:2990 —name jira addono/jira-software-standalone

    tox envs

    When updating interactions with the Jira REST API please refer to the documentation below. We aim to support both Jira Cloud and Jira Server / Data Center.

    1. Jira Cloud / Jira Server (main REST API reference)
    2. Jira Software Cloud / Jira Software Server (former names include: Jira Agile, Greenhopper)
    3. Jira Service Desk Cloud / Jira Service Desk Server

    Credits

    In addition to all the contributors we would like to thank to these companies:

    • Atlassian for developing such a powerful issue tracker and for providing a free on-demand Jira instance that we can use for continuous integration testing.
    • JetBrains for providing us with free licenses of PyCharm
    • GitHub for hosting our continuous integration and our git repo
    • Navicat for providing us free licenses of their powerful database client GUI tools.

    Источник

    Работа с Jira API при помощи Python

    Всем привет. Появилась мысль автоматизировать выгрузку отчетов из Jira. Так как любимым инструментом был Python, выбор пал на модуль от JIra позволяющий работать с их API. Кому интересно прошу по кат.

    image

    У atlassian есть официальная документация по использованию их модуля. Сам модуль так и называется «jira». По традиции выполним установку модуля командой:

    Затем импортируем модуль непосредственно в коде:

    Для того чтобы подключиться к самому серверу, необходимо создать клиент передав в него требуемые параметры:

    jira_options = jira = JIRA(options=jira_options, basic_auth=(login, api_key))

    Для того чтобы пройти авторизацию по паролю, вместо api key можно передать пароль. После того как авторизация пройдена, мы имеем активный api client к которому можно обращаться.

    Возможности конечно не безграничны, но достаточно широкие. Мне было необходимо вытаскивать задачи за определенную неделю и составлять отчет по потраченным часам в Excell. Вытаскивать задачи можно непосредственно по самому проекту, по номеру задачи, так и по JQL запросу. Инструменты поиска достаточно гибкие и простые. Вся информация возвращаемая апи клиентом приходит в string, поэтому для работы с ней требуются дополнительные действия.
    Составляем jql запрос и забираем по нему задачи:

    jql = 'project = ' + project_key + ' AND worklogDate >= ' + work_date issues_list = jira.search_issues(jql) 

    К сожалению я так и не понял почему в тех задачах которые получаются через такой запрос нет свойства worklog. После некоторых попыток понять что же не так, я вежливо попросил у jira задачу по номеру:

    issue = jira.issue(issue_key)

    В задаче возвращенной по такому методу поле worklog со списком worklog-ов было. В результате чего я стал брать задачи по jql запросу, вытаскивал номера задачи и уже после вытаскивал необходимую мне информацию:

    worklogs = issue.fields.worklog.worklogs

    Подобная строка позволяет вытащить все записи о времени от определенной задачи. У каждой из записи есть информация о времени как в секундах так и в текстовом представлении (1h, 3d etc).
    Дальше все просто, берем отбрасываем записи, которые не подходят по периоду, в моем случае не совпадает номер недели:

    worklog_date_str = re.search(r'(\d-\d-\d)', worklog.started) worklog_date = datetime.strptime(worklog_date_str.group(0), '%Y-%m-%d') if worklog_date.isocalendar()[1] == weak_number:

    Так как дата возвращается в строке, я воспользовался простым регулярным выражением, чтобы забирать его, а в следующей строке привожу уже необходимый тип. Выражение worklog_date.isocalendar()[1] позволяет узнать номер недели, который будет сравниваться с тем что необходимо забирать. Если он совпадает, топаем дальше и записываем остальные данные.

    В целом вышеприведенный модуль позволяет решать достаточно широкий круг задач, нужно лишь время и желание.

    Можно не запрашивать задачи повторно, а просто экспандить нужное поле
    github.com/pycontribs/jira/blob/master/jira/client.py#L2371
    спасибо HSerg

    Источник

Оцените статью