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, default_timeout=300, auth_provider=None, jsession=None, cli=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)

  • debug (bool) – 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.

  • extension_types (bool) – Flag to indicate whether or not to build an object model for extension types added by plugins.

  • 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)

  • default_timeout (int) – The default timeout of requests sent by xnatpy, is a 5 minutes per default.

  • auth_provider (str) – Set the auth provider to use to log in to XNAT.

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.BaseXNATSession(server, logger, interface=None, user=None, password=None, keepalive=None, debug=False, original_uri=None, logged_in_user=None, default_timeout=300, jsession=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.core.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

create_object(uri, type_=None, fieldname=None, **kwargs)

Create an xnatpy object for a given uri. This does not create anything server sided, but rather wraps and uri (and optionally data) in an object. It allows you to create an xnatpy object from an arbitrary uri to something on the xnat server and continue as normal from there on.

Parameters
  • uri (str) – url of the object

  • type (str) – the xsi_type to select the object type (this is option, by default it will be auto retrieved)

  • fieldname – indicate the name of the field that was used to retrieved this object

  • kwargs – arguments to pass to object creation

Returns

newly created xnatpy object

Return type

XNATObject

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 bytes 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

property experiments

Listing of all experiments on the XNAT server

Returns an XNATListing with elements that are subclasses of ExperimentData

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

property 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

property prearchive

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

property projects

Listing of all projects on the XNAT server

Returns an XNATListing with elements of ProjectData

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

property scan_types

A list of scan types associated with this XNATSession instance

property scanners

A list of scanners referenced in XNATSession

property services

Collection of services, see xnat.services

property 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

property subjects

Listing of all subjects on the XNAT server

Returns an XNATListing with elements of SubjectData

upload(uri, file_, retries=1, query=None, content_type=None, method='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

upload_file(uri, path, **kwargs)

Upload data or a file to XNAT

Parameters
  • uri (str) – uri to upload to

  • path (str) – path to the file to be uploaded (str)

  • 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

property users

Representation of the users registered on the XNAT server

property xnat_version

The version of the XNAT server

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

Bases: xnat.session.BaseXNATSession

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.

core Module

class xnat.core.CustomVariableDef(name, datatype, options)

Bases: object

class xnat.core.CustomVariableGroup(parent, definition)

Bases: collections.abc.MutableMapping

property name
class xnat.core.CustomVariableMap(parent)

Bases: collections.abc.Mapping

property caching
clearcache()
property definitions
property fields
property project
property protocol
class xnat.core.XNATBaseListing(parent, field_name, secondary_lookup_field=None, xsi_type=None, **kwargs)

Bases: collections.abc.Mapping, collections.abc.Sequence

property caching
clearcache()
property data

The data mapping using the primary key

abstract property data_maps

The generator function (should be cached) of all the data access properties. They are all generated from the same data, so their caching is shared.

delete_item_from_cache(obj)
classmethod delete_item_from_listings(obj)
property key_map

The data mapping using the secondary key

property listing

The listing view of the data

property logger
property non_unique_keys

Set of non_unique keys

sanitize_name(name)
property uri
property xnat_session
class xnat.core.XNATBaseObject(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: object

SECONDARY_LOOKUP_FIELD = None
property caching
clearcache()
abstract property data

The data of the current object (data fields only)

del_(name)
delete(remove_files=True)

Remove the item from XNATSession

external_uri(query=None, scheme=None)

Return the external url for this object, not just a REST path

Parameters
  • query – extra query string parameters

  • scheme – scheme to use (when not using original url scheme)

Returns

external url for this object

property fieldname
abstract property fulldata

The full data of the current object (incl children, meta etc)

property fulluri
get(name, type_=None)
get_object(fieldname, type_=None)
property id
property logger
mset(values=None, timeout=None, **kwargs)
property parent
set(name, value, type_=None, timeout=None)

Set a field in the current object

Parameters
  • name (str) – name of the field

  • value – value to set

  • type – type of the field

property uri
property xnat_session
abstract property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

class xnat.core.XNATListing(uri, filter=None, **kwargs)

Bases: xnat.core.XNATBaseListing

property data_maps

The generator function (should be cached) of all the data access properties. They are all generated from the same data, so their caching is shared.

filter(filters=None, **kwargs)

Create a new filtered listing based on this listing. There are two way of defining the new filters. Either by passing a dict as the first argument, or by adding filters as keyword arguments.

For example::
>>> listing.filter({'ID': 'A*'})
>>> listing.filter(ID='A*')

are equivalent.

Parameters
  • filters (dict) – a dictionary containing the filters

  • kwargs (str) – keyword arguments containing the filters

Returns

new filtered XNATListing

Return type

XNATListing

static merge_filters(old_filters, extra_filters)
tabulate(columns=None, filter=None)
tabulate_csv(columns=None, filter=None, header=True)
property used_filters
class xnat.core.XNATNestedObject(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

clearcache()
property data

The data of the current object (data fields only)

property fulldata

The full data of the current object (incl children, meta etc)

property uri
property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

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

Bases: xnat.core.XNATBaseObject

property data

The data of the current object (data fields only)

property fulldata

The full data of the current object (incl children, meta etc)

property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

class xnat.core.XNATSimpleListing(parent, field_name, secondary_lookup_field=None, xsi_type=None, data_field_name=None, **kwargs)

Bases: xnat.core.XNATBaseListing, collections.abc.MutableMapping, collections.abc.MutableSequence

clearcache()
property data_maps

The generator function (should be cached) of all the data access properties. They are all generated from the same data, so their caching is shared.

property fulldata
insert(index, value)

S.insert(index, value) – insert value before index

property xnat_session
class xnat.core.XNATSubListing(parent, field_name, secondary_lookup_field=None, xsi_type=None, **kwargs)

Bases: xnat.core.XNATBaseListing, collections.abc.MutableMapping, collections.abc.MutableSequence

clearcache()
property data_maps

The generator function (should be cached) of all the data access properties. They are all generated from the same data, so their caching is shared.

property fulldata
property fulluri
insert(index, value)

S.insert(index, value) – insert value before index

property uri
property xnat_session
property xpath
class xnat.core.XNATSubObject(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

clearcache()
property data

The data of the current object (data fields only)

property fulldata

The full data of the current object (incl children, meta etc)

property uri
property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

xnat.core.caching(func)

This decorator caches the value in self._cache to avoid data to be retrieved multiple times. This works for properties or functions without arguments.

inspect Module

class xnat.inspect.Inspect(xnat_session)

Bases: object

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

prearchive Module

class xnat.prearchive.Prearchive(xnat_session)

Bases: object

property caching
find(project=None, subject=None, session=None, status=None)

Find specific session(s) given the project/subject/session/status

Parameters
  • project (str) –

  • subject (str) –

  • session (str) –

  • status (str) –

Returns

list of matching sessions

Return type

list[PrearchiveSession]

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

property xnat_session
class xnat.prearchive.PrearchiveFile(uri, xnat_session, id_=None, datafields=None, parent=None, fieldname=None)

Bases: xnat.core.XNATBaseObject

property data

The data of the current object (data fields only)

download(path)

Download the file

Parameters

path (str) – the path to download to

Returns

the path of the downloaded file

Return type

str

property fulldata

The full data of the current object (incl children, meta etc)

property name

The name of the file

open()
property size

The size of the file

property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

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

Bases: xnat.core.XNATBaseObject

property data

The data of the current object (data fields only)

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

property files

List of files contained in the scan

property fulldata

The full data of the current object (incl children, meta etc)

read_dicom(file=None, read_pixel_data=False, force=False)
property series_description

The series description of the scan

property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

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

xnat.classes.ExperimentData

property autoarchive
cli_str()
property data

The data of the current object (data fields only)

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

property folder_name
property fulldata

The full data of the current object (incl children, meta etc)

property id

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

property label
property 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

property name
property prevent_anon
property prevent_auto_commit
property project
rebuild(asynchronous=None)

Rebuilt the session in the prearchive

Parameters

asynchronous (bool) – flag to rebuild asynchronously

Returns

requests response

property scan_date
property scan_time
property scans

List of scans in the prearchive session

property status
property subject
property tag
property timestamp
property uploaded

Datetime when the session was uploaded

property xpath

The xpath of the object as seen from the root of the data. Used for setting fields in the object.

services Module

class xnat.services.DicomBoxImportRequest(uri, xnat_session)

Bases: object

property cleanup_after_import
property created
property enabled
property id
property project_id
property session_path
property status
property subject_id
property timestamp
property username
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

guess_content_type(path)
import_(path=None, data=None, overwrite=None, quarantine=False, destination=None, trigger_pipelines=None, project=None, subject=None, experiment=None, content_type=None, import_handler=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

  • data – either a string containing the data to be uploaded or a open file handle to read the data from

  • 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 (only accepts project ID, not a label)

  • 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 default the mimetype will be guessed using the mimetypes package). This will often be application/zip.

Returns

Note

The project has to be given using the project ID and NOT the label.

Warning

On some systems the guessed mimetype of a zip file might not be application/zip but be something like application/x-zip-compressed. In that case you might have to set the content_type parameter to application/zip manually.

import_dicom_inbox(path, cleanup=False, project=None, subject=None, experiment=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

  • cleanup (str) – remove the files after importing them (default false)

  • project (str) – the project in the archive to assign the session to (only accepts project ID, not a label)

  • 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

Note

The project and subject has to be given using the ID and NOT the label/name.

import_dir(directory, overwrite=None, quarantine=False, destination=None, trigger_pipelines=None, project=None, subject=None, experiment=None, method='zip_file', import_handler=None)

Import a directory to an XNAT resource.

Parameters
  • directory (str) – local path of the directory 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 (only accepts project ID, not a label)

  • 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

The method has 2 options, default is zip_file:

  1. zip_file: Create a temporary zip file and upload that

  2. zip_memory: Create a temporary zip file in memory and upload it

The considerations are that sometimes you can fit things in memory so you can save disk IO by putting it in memory.

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)

refresh_catalog(resource, checksum=False, delete=False, append=False, populate_stats=False)

Call for a refresh of the catalog, see https://wiki.xnat.org/display/XAPI/Catalog+Refresh+API for details.

Introduced with XNAT 1.6.2, the refresh catalog service is used to update catalog xmls that are out of sync with the file system. This service can be used to store checksums for entries that are missing the, remove entries that no longer have valid files, or add new entries for files that have been manually added to the archive directory.

When using this feature to add files that have been manually added to the archive directory, you must have placed the files in the appropriate archive directory (in the same directory as the generated catalog xml or a sub-directory). The catalog xml should already exist before triggering this service. If you haven’t generated the catalog yet, you can do so by doing a PUT to the resource URL (i.e. /data/archive/experiments/ID/resources/TEST).

Extra parameters indicate operations to perform on the specified resource(s) during the refresh. If non are given, then the catalog will be reviewed and updated for validity, but nothing else.

Parameters
  • resource – XNATObject or uri indicating the resource to use

  • checksum (bool) – generate checksums for any entries that are missing them

  • delete (bool) – remove entries that do not reference valid files

  • append (bool) – add entries for files in the catalog directory (or sub-directory)

  • populate_stats (bool) – updates the statistics for the resource in the XNAT abstract resource table.

Returns

property xnat_session
class xnat.services.TokenResult(alias, secret)

Bases: tuple

property alias

Alias for field number 0

property secret

Alias for field number 1

users Module

class xnat.users.User(data)

Bases: object

Representation of a user on the connected XNAT systen

property data
property email

The email of the user

property first_name

The first name of the user

property id

The id of the user

property last_name

The last name of the user

property login

The login name of the user

class xnat.users.Users(xnat_session)

Bases: collections.abc.Mapping

Listing of the users on the connected XNAT installation

property data
property xnat_session

mixin Module

class xnat.mixin.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 = 'label'
property data

The data of the current object (data fields only)

download(path, verbose=True)
download_dir(target_dir, verbose=True, flatten_dirs=False)

Download the entire resource and unpack it in a given directory

Parameters
  • target_dir (str) – directory to unpack to

  • verbose (bool) – show progress

property file_count
property file_size
property files
property fulldata

The full data of the current object (incl children, meta etc)

refresh_catalog()

Call refresh catalog on this object, see xnat.services.Services.refresh_catalog() for details.

upload(data, remotepath, overwrite=False, extract=False, file_content=None, file_format=None, file_tags=None, **kwargs)

Upload a file as an XNAT resource.

Parameters
  • data (str) – The path to the file to upload

  • remotepath (str) – The remote path to which to uploadt

  • overwrite (bool) – Flag to force overwriting of files

  • extract (bool) – Extract the files on the XNAT server

  • file_content (str) – Set the Content of the file on XNAT

  • file_format (str) – Set the format of the file on XNAT

  • file_tags (str) – Set the tags of the file on XNAT

upload_dir(directory, overwrite=False, method='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

  5. 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.mixin.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)
property files
property fulluri
property resources
class xnat.mixin.ExperimentData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'label'
cli_str()
property label
class xnat.mixin.ImageScanData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'type'
create_resource(label, format=None, data_dir=None, method='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)
property fields
property files
read_dicom(file=None, read_pixel_data=False, force=False)
property resources
class xnat.mixin.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)

Download the entire experiment and unpack it in a given directory. Note that this method will create a directory structure following $target_dir/{experiment.label} and unzip the experiment zips as given by XNAT into that. If the $target_dir/{experiment.label} does not exist, it will be created.

Parameters
  • target_dir (str) – directory to create experiment directory in

  • verbose (bool) – show progress

property files
share(project, label=None)
class xnat.mixin.InvestigatorData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

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

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'name'
cli_str()
create_resource(label, format=None, data_dir=None, method=None)
download_dir(target_dir, verbose=True, progress_callback=None)

Download the entire project and unpack it in a given directory. Note that this method will create a directory structure following $target_dir/{project.name}/{subject.label}/{experiment.label} and unzip the experiment zips as given by XNAT into that. If the $target_dir/{project.name} does not exist, it will be created.

Parameters
  • target_dir (str) – directory to create project directory in

  • verbose (bool) – show progress

  • progress_callback – function to call with progress string should be a function with one argument

property experiments
property files
property fulluri
property project
property resources
property subjects
class xnat.mixin.SubjectAssessorData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)

Bases: xnat.core.XNATBaseObject

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

Bases: xnat.core.XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'label'
cli_str()
create_resource(label, format=None, data_dir=None, method=None)
download_dir(target_dir, verbose=True, progress_callback=None)

Download the entire subject and unpack it in a given directory. Note that this method will create a directory structure following $target_dir/{subject.label}/{experiment.label} and unzip the experiment zips as given by XNAT into that. If the $target_dir/{subject.label} does not exist, it will be created.

Parameters
  • target_dir (str) – directory to create subject directory in

  • verbose (bool) – show progress

  • progress_callback – function to call with progress string should be a function with one argument

property files
property fulluri
property label
share(project, label=None)