Code reference

xnat Package

This package contains the entire client. The connect function is the only function actually in the package. All following classes are created based on the https://central.xnat.org/schema/xnat/xnat.xsd schema and the xnatcore and xnatbase modules, using the convert_xsd.

xnat.connect(server, user=None, password=None, verify=True, netrc_file=None, debug=False, extension_types=True, loglevel=None, logger=None, detect_redirect=True, no_parse_model=False)

Connect to a server and generate the correct classed based on the servers xnat.xsd This function returns an object that can be used as a context operator. It will call disconnect automatically when the context is left. If it is used as a function, then the user should call .disconnect() to destroy the session and temporary code file.

Parameters:
  • server (str) – uri of the server to connect to (including http:// or https://)
  • user (str) – username to use, leave empty to use netrc entry or anonymous login.
  • password (str) – password to use with the username, leave empty when using netrc. If a username is given and no password, there will be a prompt on the console requesting the password.
  • verify (bool) – verify the https certificates, if this is false the connection will be encrypted with ssl, but the certificates are not checked. This is potentially dangerous, but required for self-signed certificates.
  • netrc_file (str) – alternative location to use for the netrc file (path pointing to a file following the netrc syntax)
  • bool (debug) – Set debug information printing on and print extra debug information. This is meant for xnatpy developers and not for normal users. If you want to debug your code using xnatpy, just set the loglevel to DEBUG which will show you all requests being made, but spare you the xnatpy internals.
  • loglevel (str) – Set the level of the logger to desired level
  • logger (logging.Logger) – A logger to reuse instead of creating an own logger
  • detect_redirect (bool) – Try to detect a redirect (via a 302 response) and short-cut for subsequent requests
  • no_parse_model (bool) – Create an XNAT connection without parsing the server data model, this create a connection for which the simple get/head/put/post/delete functions where, but anything requiring the data model will file (e.g. any wrapped classes)
Returns:

XNAT session object

Return type:

XNATSession

Preferred use:

>>> import xnat
>>> with xnat.connect('https://central.xnat.org') as session:
...    subjects = session.projects['Sample_DICOM'].subjects
...    print('Subjects in the SampleDICOM project: {}'.format(subjects))
Subjects in the SampleDICOM project: <XNATListing (CENTRAL_S01894, dcmtest1): <SubjectData CENTRAL_S01894>, (CENTRAL_S00461, PACE_HF_SUPINE): <SubjectData CENTRAL_S00461>>

Alternative use:

>>> import xnat
>>> session = xnat.connect('https://central.xnat.org')
>>> subjects = session.projects['Sample_DICOM'].subjects
>>> print('Subjects in the SampleDICOM project: {}'.format(subjects))
Subjects in the SampleDICOM project: <XNATListing (CENTRAL_S01894, dcmtest1): <SubjectData CENTRAL_S01894>, (CENTRAL_S00461, PACE_HF_SUPINE): <SubjectData CENTRAL_S00461>>
>>> session.disconnect()

session Module

class xnat.session.XNATSession(server, logger, interface=None, user=None, password=None, keepalive=None, debug=False, original_uri=None, logged_in_user=None)

Bases: object

The main XNATSession session class. It keeps a connection to XNATSession alive and manages the main communication to XNATSession. To keep the connection alive there is a background thread that sends a heart-beat to avoid a time-out.

The main starting points for working with the XNATSession server are:

  • XNATSession.projects
  • XNATSession.subjects
  • XNATSession.experiments
  • XNATSession.prearchive
  • XNATSession.services
  • XNATSession.users

Note

Some methods create listing that are using the xnat.XNATListing class. They allow for indexing with both XNATSession ID and a secondary key (often the label). Also they support basic filtering and tabulation.

There are also methods for more low level communication. The main methods are XNATSession.get, XNATSession.post, XNATSession.put, and XNATSession.delete. The methods do not query URIs but instead query XNATSession REST paths as described in the XNATSession 1.6 REST API Directory.

For an even lower level interfaces, the XNATSession.interface gives access to the underlying requests interface. This interface has the user credentials and benefits from the keep alive of this class.

Note

XNATSession Objects have a client-side cache. This is for efficiency, but might cause problems if the server is being changed by a different client. It is possible to clear the current cache using XNATSession.clearcache. Turning off caching complete can be done by setting XNATSession.caching.

Warning

You should NOT try use this class directly, it should only be created by xnat.connect.

clearcache()

Clear the cache of the listings in the Session object

delete(path, headers=None, accepted_status=None, query=None, timeout=None)

Delete the content of a given REST directory.

Parameters:
  • path (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • headers (dict) – the HTTP headers to include
  • query (dict) – the values to be added to the query string in the uri
  • accepted_status (list) – a list of the valid values for the return code, default [200]
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
Returns:

the requests reponse

Return type:

requests.Response

download(uri, target, format=None, verbose=True, timeout=None)

Download uri to a target file

download_stream(uri, target_stream, format=None, verbose=False, chunk_size=524288, update_func=None, timeout=None)

Download the given uri to the given target_stream.

Parameters:
  • uri (str) – Path of the uri to retrieve.
  • target_stream (file) – A writable file-like object to save the stream to.
  • format (str) – Request format
  • verbose (bool) – If True, and an update_func is not specified, a progress bar is shown on stdout.
  • chunk_size (int) – Download this many bytes at a time
  • update_func (func) –

    If provided, will be called every chunk_size bytes. Must accept three parameters:

    • the number of bytes downloaded so far
    • the total number of bytse to be downloaded (might be None),
    • A boolean flag which is False during the download, and True when the download has completed (or failed)
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
download_zip(uri, target, verbose=True, timeout=None)

Download uri to a target zip file

experiments

Listing of all experiments on the XNAT server

Cached using the caching decorator

get(path, format=None, query=None, accepted_status=None, timeout=None, headers=None)

Retrieve the content of a given REST directory.

Parameters:
  • path (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • format (str) – the format of the request, this will add the format= to the query string
  • query (dict) – the values to be added to the query string in the uri
  • accepted_status (list) – a list of the valid values for the return code, default [200]
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
  • headers (dict) – the HTTP headers to include
Returns:

the requests reponse

Return type:

requests.Response

get_json(uri, query=None, accepted_status=None)

Helper function that perform a GET, but sets the format to JSON and parses the result as JSON

Parameters:
  • uri (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • query (dict) – the values to be added to the query string in the uri
head(path, accepted_status=None, allow_redirects=False, timeout=None, headers=None)

Retrieve the header for a http request of a given REST directory.

Parameters:
  • path (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • accepted_status (list) – a list of the valid values for the return code, default [200]
  • allow_redirects (bool) – allow you request to be redirected
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
  • headers (dict) – the HTTP headers to include
Returns:

the requests reponse

Return type:

requests.Response

interface

The underlying requests interface used.

post(path, data=None, json=None, format=None, query=None, accepted_status=None, timeout=None, headers=None)

Post data to a given REST directory.

Parameters:
  • path (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • data – Dictionary, bytes, or file-like object to send in the body of the Request.
  • json – json data to send in the body of the Request.
  • format (str) – the format of the request, this will add the format= to the query string
  • query (dict) – the values to be added to the query string in the uri
  • accepted_status (list) – a list of the valid values for the return code, default [200, 201]
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
  • headers (dict) – the HTTP headers to include
Returns:

the requests reponse

Return type:

requests.Response

prearchive

Representation of the prearchive on the XNAT server, see xnat.prearchive

projects

Listing of all projects on the XNAT server

Cached using the caching decorator

put(path, data=None, files=None, json=None, format=None, query=None, accepted_status=None, timeout=None, headers=None)

Put the content of a given REST directory.

Parameters:
  • path (str) – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically
  • data – Dictionary, bytes, or file-like object to send in the body of the Request.
  • json – json data to send in the body of the Request.
  • files – Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
  • format (str) – the format of the request, this will add the format= to the query string
  • query (dict) – the values to be added to the query string in the uri
  • accepted_status (list) – a list of the valid values for the return code, default [200, 201]
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
  • headers (dict) – the HTTP headers to include
Returns:

the requests reponse

Return type:

requests.Response

scan_types

A list of scan types associated with this XNATSession instance

scanners

A list of scanners referenced in XNATSession

services

Collection of services, see xnat.services

session_expiration_time

Get the session expiration time information from the cookies. This returns the timestamp (datetime format) when the session was created and an integer with the session timeout interval.

This can return None if the cookie is not found or cannot be parsed.

Returns:datetime with last session refresh and integer with timeout in seconds
Return type:tuple
subjects

Listing of all subjects on the XNAT server

Cached using the caching decorator

upload(uri, file_, retries=1, query=None, content_type=None, method=u'put', overwrite=False, timeout=None)

Upload data or a file to XNAT

Parameters:
  • uri (str) – uri to upload to
  • file – the file handle, path to a file or a string of data (which should not be the path to an existing file!)
  • retries (int) – amount of times xnatpy should retry in case of failure
  • query (dict) – extra query string content
  • content_type – the content type of the file, if not given it will default to application/octet-stream
  • method (str) – either put (default) or post
  • overwrite (bool) – indicate if previous data should be overwritten
  • timeout (float or tuple) – timeout in seconds, float or (connection timeout, read timeout)
Returns:

url_for(obj, query=None, scheme=None)

Return the (external) url for a given XNAT object :param XNATBaseObject obj: object to get url for :param query: extra query string parameters :param scheme: scheme to use (when not using original url scheme) :return: external url for the object

users

Representation of the users registered on the XNAT server

xnat_version

The version of the XNAT server

Cached using the caching decorator

xnat.session.default_update_func(total)

Set up a default update function to be used by the Session.download_stream method. This function configures a progressbar.ProgressBar object which displays progress as a file is downloaded.

Parameters:total (int) – Total number of bytes to be downloaded (might be None)
Returns:A function to be used as the update_func by the Session.download_stream method.

inspect Module

class xnat.inspect.Inspect(xnat_session)

Bases: object

datafields(datatype, pattern=u'*', prepend_type=True)
datatypes(pattern=u'*', fields_pattern=None)
xnat_session

prearchive Module

class xnat.prearchive.Prearchive(xnat_session)

Bases: object

sessions(project=None)

Get the session in the prearchive, optionally filtered by project. This function is not cached and returns the results of a query at each call.

Parameters:project (str) – the project to filter on
Returns:list of prearchive session found
Return type:list
xnat_session
class xnat.prearchive.PrearchiveFile(uri, xnat_session, id_=None, datafields=None, parent=None, fieldname=None)

Bases: xnat.core.XNATBaseObject

data
download(path)

Download the file

Parameters:path (str) – the path to download to
Returns:the path of the downloaded file
Return type:str
fulldata
name

The name of the file

size

The size of the file

xpath
class xnat.prearchive.PrearchiveScan(uri, xnat_session, id_=None, datafields=None, parent=None, fieldname=None)

Bases: xnat.core.XNATBaseObject

data
dicom_dump(fields=None)

Retrieve a dicom dump as a JSON data structure See the XAPI documentation for more detailed information: DICOM Dump Service

Parameters:fields (list) – Fields to filter for DICOM tags. It can either a tag name or tag number in the format GGGGEEEE (G = Group number, E = Element number)
Returns:JSON object (dict) representation of DICOM header
Return type:dict
download(path)

Download the scan as a zip

Parameters:path (str) – the path to download to
Returns:the path of the downloaded file
Return type:str
files

List of files contained in the scan

fulldata
series_description

The series description of the scan

xpath
class xnat.prearchive.PrearchiveSession(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

archive(overwrite=None, quarantine=None, trigger_pipelines=None, project=None, subject=None, experiment=None)

Method to archive this prearchive session to the main archive

Parameters:
  • overwrite (str) – how the handle existing data (none, append, delete)
  • quarantine (bool) – flag to indicate session should be quarantined
  • trigger_pipelines (bool) – indicate that archiving should trigger pipelines
  • project (str) – the project in the archive to assign the session to
  • subject (str) – the subject in the archive to assign the session to
  • experiment (str) – the experiment in the archive to assign the session content to
Returns:

the newly created experiment

Return type:

ExperimentData

autoarchive
data
delete(asynchronous=None)

Delete the session from the prearchive

Parameters:asynchronous (bool) – flag to delete asynchronously
Returns:requests response
download(path)

Method to download the zip of the prearchive session

Parameters:path (str) – path to download to
Returns:path of the downloaded zip file
Return type:str
folder_name
fulldata
id

A unique ID for the session in the prearchive :return:

label
lastmod
move(new_project, asynchronous=None)

Move the session to a different project in the prearchive

Parameters:
  • new_project (str) – the id of the project to move to
  • asynchronous (bool) – flag to move asynchronously
Returns:

requests response

name
prevent_anon
prevent_auto_commit
project
rebuild(asynchronous=None)

Rebuilt the session in the prearchive

Parameters:asynchronous (bool) – flag to rebuild asynchronously
Returns:requests response
scan_date
scan_time
scans

List of scans in the prearchive session

status
subject
tag
timestamp
uploaded

Datetime when the session was uploaded

xpath

services Module

class xnat.services.Services(xnat_session)

Bases: object

The class representing all service functions in XNAT found in the /data/services REST directory

dicom_dump(src, fields=None)

Retrieve a dicom dump as a JSON data structure See the XAPI documentation for more detailed information: DICOM Dump Service

Parameters:
  • src (str) – The url of the scan to generate the DICOM dump for
  • fields (list) – Fields to filter for DICOM tags. It can either a tag name or tag number in the format GGGGEEEE (G = Group number, E = Element number)
Returns:

JSON object (dict) representation of DICOM header

Return type:

dict

import_(path, overwrite=None, quarantine=False, destination=None, trigger_pipelines=None, project=None, subject=None, experiment=None, content_type=None)

Import a file into XNAT using the import service. See the XNAT wiki for a detailed explanation.

Parameters:
  • path (str) – local path of the file to upload and import
  • overwrite (str) – how the handle existing data (none, append, delete)
  • quarantine (bool) – flag to indicate session should be quarantined
  • trigger_pipelines (bool) – indicate that archiving should trigger pipelines
  • destination (str) – the destination to upload the scan to
  • project (str) – the project in the archive to assign the session to
  • subject (str) – the subject in the archive to assign the session to
  • experiment (str) – the experiment in the archive to assign the session content to
  • content_type (str) – overwite the content_type (by the mimetype will be guessed)
Returns:

issue_token(user=None)

Issue a login token, by default for the current logged in user. If username is given, for that user. To issue tokens for other users you must be an admin.

Parameters:user (str) – User to issue token for, default is current user
Returns:Token in a named tuple (alias, secret)
xnat_session
class xnat.services.TokenResult(alias, secret)

Bases: tuple

alias

Alias for field number 0

secret

Alias for field number 1

users Module

class xnat.users.User(data)

Bases: object

Representation of a user on the connected XNAT systen

data
email

The email of the user

first_name

The first name of the user

id

The id of the user

last_name

The last name of the user

login

The login name of the user

class xnat.users.Users(xnat_session)

Bases: _abcoll.Mapping

Listing of the users on the connected XNAT installation

data

Cached using the caching decorator

xnat_session

xnatbases Module

class xnat.xnatbases.AbstractResource(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, data_dir=None, upload_method=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = u'label'
data
download(path, verbose=True)
download_dir(target_dir, verbose=True)
file_count
file_size
files

Cached using the caching decorator

fulldata

Cached using the caching decorator

upload(data, remotepath, overwrite=False, extract=False, **kwargs)
upload_dir(directory, overwrite=False, method=u'tgz_file', **kwargs)

Upload a directory to an XNAT resource. This means that if you do resource.upload_dir(directory) that if there is a file directory/a.txt it will be uploaded to resource/files/a.txt

The method has 5 options, default is tgz_file:

  1. per_file: Scans the directory and uploads file by file
  2. tar_memory: Create a tar archive in memory and upload it in one go
  3. tgz_memory: Create a gzipped tar file in memory and upload that

4. tar_file: Create a temporary tar file and upload that 4. tgz_file: Create a temporary gzipped tar file and upload that

The considerations are that sometimes you can fit things in memory so you can save disk IO by putting it in memory. The per file does not create additional archives, but has one request per file so might be slow when uploading many files.

Parameters:
  • directory (str) – The directory to upload
  • overwrite (bool) – Flag to force overwriting of files
  • method (str) – The method to use
class xnat.xnatbases.DerivedData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

create_resource(label, format=None, data_dir=None, method=None)
download(path, verbose=True)
files

Cached using the caching decorator

fulluri
resources

Cached using the caching decorator

class xnat.xnatbases.ExperimentData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = u'label'
label = <SearchField xnat:baseObject/label>
class xnat.xnatbases.ImageScanData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = u'type'
create_resource(label, format=None, data_dir=None, method=u'tgz_file')
dicom_dump(fields=None)

Retrieve a dicom dump as a JSON data structure See the XAPI documentation for more detailed information: DICOM Dump Service

Parameters:fields (list) – Fields to filter for DICOM tags. It can either a tag name or tag number in the format GGGGEEEE (G = Group number, E = Element number)
Returns:JSON object (dict) representation of DICOM header
Return type:dict
download(path, verbose=True)
download_dir(target_dir, verbose=True)
files

Cached using the caching decorator

read_dicom(file=None, read_pixel_data=False)
resources

Cached using the caching decorator

class xnat.xnatbases.ImageSessionData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

create_assessor(label, type_)
download(path, verbose=True)
download_dir(target_dir, verbose=True)
files

Cached using the caching decorator

share(project, label=None)
class xnat.xnatbases.ProjectData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = u'name'
download_dir(target_dir, verbose=True)
experiments

Cached using the caching decorator

files

Cached using the caching decorator

fulluri
resources

Cached using the caching decorator

subjects

Cached using the caching decorator

class xnat.xnatbases.SubjectAssessorData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

fulluri
subject
class xnat.xnatbases.SubjectData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = u'label'
download_dir(target_dir, verbose=True)
files

Cached using the caching decorator

fulluri
label = <SearchField xnat:baseObject/label>
share(project, label=None)