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=None, 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://), leave empty to use the XNATPY_HOST or XNAT_HOST environment variables

  • user (str) – username to use, leave empty to use the XNATPY_USER or XNAT_USER environment variables, netrc entry or anonymous login (in that order).

  • password (str) – password to use with the username, leave empty when using netrc or the XNATPY_PASS or XNAT_PASS environment variables. 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 connection:
...    subjects = connection.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
>>> connection = xnat.connect('https://central.xnat.org')
>>> subjects = connection.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>>
>>> connection.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.plugins

  • 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: str, type_: str | None = None, fieldname: str | None = None, **kwargs) XNATBaseObject#

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 – url of the object

  • type – 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

delete(path: str, headers: Dict[str, str] | None = None, accepted_status: Container[int] | None = None, query: Dict[str, str] | None = None, timeout: float | Tuple[float, float] | None = None) Response#

Delete the content of a given REST directory.

Parameters:
  • path – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically

  • headers – the HTTP headers to include

  • query – the values to be added to the query string in the uri

  • accepted_status – a list of the valid values for the return code, default [200]

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

Returns:

the requests reponse

download(uri: str, target: str | Path, format: str | None = None, verbose: bool = True, timeout: float | Tuple[float, float] | None = None)#

Download uri to a target file

download_stream(uri: str, target_stream: BinaryIO, format: str | None = None, verbose: bool = False, chunk_size: int = 524288, update_func: Callable[[int, int | None, bool], None] | None = None, timeout: float | Tuple[float, float] | None = None)#

Download the given uri to the given target_stream.

Parameters:
  • uri – Path of the uri to retrieve.

  • target_stream – A writable file-like object to save the stream to.

  • format – Request format

  • verbose – If True, and an update_func is not specified, a progress bar is shown on stdout.

  • chunk_size – Download this many bytes at a time

  • update_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 – timeout in seconds, float or (connection timeout, read timeout)

download_zip(uri: str, target: str | Path, verbose: bool = True, timeout: float | Tuple[float, float] | None = None)#

Download uri to a target zip file

property experiments: XNATListing#

Listing of all experiments on the XNAT server

Returns an XNATListing with elements that are subclasses of ExperimentData

get(path: str, format: str | None = None, query: Dict[str, str] | None = None, accepted_status: Container[int] | None = None, timeout: float | Tuple[float, float] | None = None, headers: Dict[str, str] | None = None) Response#

Retrieve the content of a given REST directory.

Parameters:
  • path – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically

  • format – the format of the request, this will add the format= to the query string

  • query – the values to be added to the query string in the uri

  • accepted_status – a list of the valid values for the return code, default [200]

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

  • headers – the HTTP headers to include

Returns:

the requests reponse

get_json(uri: str, query: Dict[str, str] | None = None, accepted_status: Container[int] | None = None) None | int | str | bool | List[Any] | Dict[str, Any]#

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

Parameters:
  • uri – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically

  • query – the values to be added to the query string in the uri

  • accepted_status – a list of the valid values for the return code, default [200]

head(path: str, accepted_status: Container[int] | None = None, allow_redirects: bool = False, timeout: float | Tuple[float, float] | None = None, headers: Dict[str, str] | None = None) Response#

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

Parameters:
  • path – the path of the uri to retrieve (e.g. “/data/archive/projects”) the remained for the uri is constructed automatically

  • accepted_status – a list of the valid values for the return code, default [200]

  • allow_redirects – allow you request to be redirected

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

  • headers – the HTTP headers to include

Returns:

the requests reponse

property interface: Session#

The underlying requests interface used.

property plugins#

Collection of plugins, see xnat.plugins

post(path: str, data: Any | None = None, json: None | int | str | bool | List[Any] | Dict[str, Any] = None, format: str | None = None, query: Dict[str, str] | None = None, accepted_status: Container[int] | None = None, timeout: float | Tuple[float, float] | None = None, headers: Dict[str, str] | None = None) Response#

Post data to a given REST directory.

Parameters:
  • path – 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 – the format of the request, this will add the format= to the query string

  • query – the values to be added to the query string in the uri

  • accepted_status – a list of the valid values for the return code, default [200, 201]

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

  • headers – the HTTP headers to include

Returns:

the requests reponse

property prearchive: Prearchive#

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

property projects: XNATListing#

Listing of all projects on the XNAT server

Returns an XNATListing with elements of ProjectData

put(path: str, data: Any | None = None, files: Any | None = None, json: None | int | str | bool | List[Any] | Dict[str, Any] = None, format: str | None = None, query: Dict[str, str] | None = None, accepted_status: Container[int] | None = None, timeout: float | Tuple[float, float] | None = None, headers: Dict[str, str] | None = None) Response#

Put the content of a given REST directory.

Parameters:
  • path – 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 – the format of the request, this will add the format= to the query string

  • query – the values to be added to the query string in the uri

  • accepted_status – a list of the valid values for the return code, default [200, 201]

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

  • headers (dict) – the HTTP headers to include

Returns:

the requests reponse

property scan_types#

A list of scan types associated with this XNATSession instance

property scanners: List#

A list of scanners referenced in XNATSession

property services: Services#

Collection of services, see xnat.services

property session_expiration_time: Tuple[datetime, float] | None#

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: XNATListing#

Listing of all subjects on the XNAT server

Returns an XNATListing with elements of SubjectData

upload(uri: str, file_: str | bytes | Path | IO, **kwargs)#

Upload path to XNAT, this method attempt to automatically figure out what the type of the source path is.

Warning

DEPRECATED: This method can have unexpected behaviour (e.g. if you supply a str with a path but the file does not exist, it will upload the path as a string instead). This method will be removed in a future release of XNATpy

Parameters:
  • uri – uri to upload to

  • file – the data to upload

  • retries – amount of times xnatpy should retry in case of failure

  • query – extra query string content

  • content_type – the content type of the file, if not given it will default to application/octet-stream

  • method – either put (default) or post

  • overwrite – indicate if previous path should be overwritten

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

upload_file(uri: str, path: str | Path, **kwargs)#

Upload 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:

upload_stream(uri: str, stream: IO | BufferedIOBase | TextIOBase, retries: int = 1, query: Dict[str, str] | None = None, content_type: str | None = None, method: str = 'put', overwrite: bool = False, timeout: float | Tuple[float, float] | None = None)#

Upload path from a stream to XNAT

Parameters:
  • uri – uri to upload to

  • stream – the file handle, path to a file or a string of path (which should not be the path to an existing file!)

  • retries – amount of times xnatpy should retry in case of failure

  • query – extra query string content

  • content_type – the content type of the file, if not given it will default to application/octet-stream

  • method – either put (default) or post

  • overwrite – indicate if previous data should be overwritten

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

upload_string(uri: str, data: str | bytes, **kwargs)#

Upload path from a string to XNAT

Parameters:
  • uri – uri to upload to

  • data – the string to upload (has to be of type str), this string will become the content of the target.

  • retries – amount of times xnatpy should retry in case of failure

  • query – extra query string content

  • content_type – the content type of the file, if not given it will default to application/octet-stream

  • method – either put (default) or post

  • overwrite – indicate if previous path should be overwritten

  • timeout – timeout in seconds, float or (connection timeout, read timeout)

url_for(obj: XNATBaseObject, query: Dict[str, str] | None = None, scheme: str | None = None) str#

Return the (external) url for a given XNAT object :param 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: Users#

Representation of the users registered on the XNAT server

property xnat_build_info#

The build info of the XNAT server

property xnat_uptime#

The uptime of the XNAT server

property xnat_version: str#

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: BaseXNATSession

xnat.session.default_update_func(total) Callable[[str, str, bool], None]#

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: str, datatype: str, options: List[str] | None)#

Bases: object

class xnat.core.CustomVariableGroup(parent, definition)#

Bases: MutableMapping

property name: str#
class xnat.core.CustomVariableMap(parent)#

Bases: Mapping

property caching: bool#
clearcache()#
property definitions#
property fields#
property project#
property protocol#
class xnat.core.XNATBaseListing(parent: XNATBaseObject, field_name, secondary_lookup_field: str | None = None, xsi_type: str | None = None, **kwargs)#

Bases: Mapping, 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: str) str#
abstract property uri: str#
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

DEFAULT_SEARCH_FIELDS = None#
FROM_SEARCH_URI = None#
SECONDARY_LOOKUP_FIELD = None#
property cache_id#
property caching: bool#
clearcache()#
classmethod create_cache_id(uri, fieldname, data)#
abstract property data: None | int | str | bool | List[Any] | Dict[str, Any]#

The data of the current object (data fields only)

del_(name: str)#
delete(remove_files: bool = True)#

Remove the item from XNATSession

external_uri(query: Dict[str, str] | None = None, scheme: str | None = None) str#

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

fieldname = None#
abstract property fulldata: None | int | str | bool | List[Any] | Dict[str, Any]#

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

property fulluri: str#
get(name, type_=None)#
get_object(fieldname, type_=None)#
property id#
property logger#
mset(values: Dict[str, str] | None = None, timeout: float | Tuple[float, float] | None = None, **kwargs)#
parent = None#
set(name: str, value: Any, type_: str | Callable[[Any], str] | None = None, timeout: float | Tuple[float, float] | None = None)#

Set a field in the current object

Parameters:
  • name (str) – name of the field

  • value – value to set

  • type – type of the field

  • timeout – time for the set request

property uri: str#
property xnat_session: BaseXNATSession#
abstract property xpath: str#

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: 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)#
tabulate_pandas()#
property uri: str#
property used_filters#
class xnat.core.XNATNestedObject(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)#

Bases: XNATBaseObject

clearcache()#
property data: None | int | str | bool | List[Any] | Dict[str, Any]#

The data of the current object (data fields only)

property fulldata: None | int | str | bool | List[Any] | Dict[str, Any]#

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

property uri: str#
property xpath: str#

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: XNATBaseObject

property data: None | int | str | bool | List[Any] | Dict[str, Any]#

The data of the current object (data fields only)

property fulldata: None | int | str | bool | List[Any] | Dict[str, Any]#

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

property insert_date: <module 'datetime' from '/home/docs/.asdf/installs/python/3.10.13/lib/python3.10/datetime.py'>#
property is_history: bool#
property xpath: str#

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: XNATBaseListing, MutableMapping, 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 uri#
property xnat_session#
class xnat.core.XNATSubListing(parent: XNATBaseObject, field_name, secondary_lookup_field: str | None = None, xsi_type: str | None = None, **kwargs)#

Bases: XNATBaseListing, MutableMapping, 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: XNATBaseObject

clearcache()#
property data: None | int | str | bool | List[Any] | Dict[str, Any]#

The data of the current object (data fields only)

property fulldata: None | int | str | bool | List[Any] | Dict[str, Any]#

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

property uri: str#
property xpath: str#

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

xnat.core.caching(func) Callable#

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: str | XNATBaseObject, pattern: str = '*', prepend_type: bool = True) List[str]#
datatypes(pattern: str = '*', fields_pattern: str | None = None) List[str]#
property xnat_session#

prearchive Module#

class xnat.prearchive.Prearchive(xnat_session: BaseXNATSession)#

Bases: object

property caching: bool#
find(project: str | None = None, subject: str | None = None, session: str | None = None, status: str | None = None) List[PrearchiveSession]#

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

Parameters:
  • project

  • subject

  • session

  • status

Returns:

list of matching sessions

sessions(project: str | None = None) List[PrearchiveSession]#

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 – the project to filter on

Returns:

list of prearchive session found

property xnat_session: BaseXNATSession#
class xnat.prearchive.PrearchiveFile(uri: str, xnat_session: BaseXNATSession, id_: str = None, datafields=None, parent: PrearchiveScan = None, fieldname: str = None)#

Bases: 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: str, xnat_session: BaseXNATSession, id_: str = None, datafields: Any = None, parent: PrearchiveSession = None, fieldname: str = None)#

Bases: XNATBaseObject

property data#

The data of the current object (data fields only)

dicom_dump(fields: List[str] | None = None) None | int | str | bool | List[Any] | Dict[str, Any]#

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

Parameters:

fields – 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

download(path: Path | str) Path | str#

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[PrearchiveFile]#

List of files contained in the scan

property fulldata: Any#

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

read_dicom(file: PrearchiveFile | None = None, read_pixel_data: bool = False, force: bool = False) FileDataset#
property series_description: str#

The series description of the scan

property xpath: str#

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: XNATBaseObject

archive(overwrite: str | None = None, quarantine: bool | None = None, trigger_pipelines: bool | None = None, project: str | None = None, subject: str | None = None, experiment: str | None = None)#

Method to archive this prearchive session to the main archive

Parameters:
  • overwrite – how the handle existing data (none, append, delete)

  • quarantine – flag to indicate session should be quarantined

  • trigger_pipelines – indicate that archiving should trigger pipelines

  • project – the project in the archive to assign the session to

  • subject – the subject in the archive to assign the session to

  • experiment – the experiment in the archive to assign the session content to

Returns:

the newly created experiment

property autoarchive#
cli_str() str#
property data: None | int | str | bool | List[Any] | Dict[str, Any]#

The data of the current object (data fields only)

delete(asynchronous: bool | None = None) Response#

Delete the session from the prearchive

Parameters:

asynchronous – flag to delete asynchronously

Returns:

requests response

download(path: Path | str)#

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: str#
property fulldata: None | int | str | bool | List[Any] | Dict[str, Any]#

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

property id: str#

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

property label: str#
property lastmod: datetime#
move(new_project: str, asynchronous: bool | None = None) Response#

Move the session to a different project in the prearchive

Parameters:
  • new_project – the id of the project to move to

  • asynchronous – flag to move asynchronously

Returns:

requests response

property name: str#
property prevent_anon#
property prevent_auto_commit#
property project: str#
rebuild(asynchronous: bool | None = None) Response#

Rebuilt the session in the prearchive

Parameters:

asynchronous – flag to rebuild asynchronously

Returns:

requests response

property scan_date: date | None#
property scan_time: time | None#
property scans: List[PrearchiveScan]#

List of scans in the prearchive session

property status: str#
property subject: str#
property tag#
property timestamp#
property uploaded: datetime | None#

Datetime when the session was uploaded

property xpath: str#

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: str | Path)#
import_(path: str | Path | None = None, data: str | bytes | IO | None = None, overwrite: str | None = None, quarantine: bool = False, destination: str | None = None, trigger_pipelines: bool | None = None, project: str | None = None, subject: str | None = None, experiment: str | None = None, content_type: str | None = None, import_handler: str | None = 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

  • destination (str) – the destination to upload the scan to

  • trigger_pipelines (bool) – indicate that archiving should trigger pipelines

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

  • import_handler – The XNAT import handler to use, see https://wiki.xnat.org/display/XAPI/Image+Session+Import+Service+API

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: str | Path, overwrite: str | None = None, quarantine: bool = False, destination: str | None = None, trigger_pipelines: bool | None = None, project: str | None = None, subject: str | None = None, experiment: str | None = None, import_handler: str | None = None)#

Import a directory to an XNAT resource.

Parameters:
  • directory – local path of the directory to upload and import

  • overwrite – how the handle existing data (none, append, delete)

  • quarantine – flag to indicate session should be quarantined

  • destination – the destination to upload the scan to

  • trigger_pipelines – indicate that archiving should trigger pipelines

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

  • subject – the subject in the archive to assign the session to

  • experiment – the experiment in the archive to assign the session content to

  • import_handler – The XNAT import handler to use, see https://wiki.xnat.org/display/XAPI/Image+Session+Import+Service+API

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

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

property access_level#
property data#
property email#

The email of the user

property first_name#

The first name of the user

property group#
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, path='/data/users')#

Bases: 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: XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'label'#
property cache_id#
classmethod create_cache_id(uri, fieldname, data)#
property data#

The data of the current object (data fields only)

property data_dir#
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: int#
property file_size: int#
property files#
property fulldata#

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

property parent_obj#
refresh_catalog()#

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

upload(path: str | Path, remotepath: str, overwrite: bool = False, extract: bool = False, file_content: str | None = None, file_format: str | None = None, file_tags: str | None = None, **kwargs)#

Upload a file as an XNAT resource.

Parameters:
  • path – The path to the file to upload

  • remotepath – The remote path to which to upload to

  • overwrite – Flag to force overwriting of files

  • extract – Extract the files on the XNAT server

  • file_content – Set the Content of the file on XNAT

  • file_format – Set the format of the file on XNAT

  • file_tags – Set the tags of the file on XNAT

upload_data(data: str | bytes | IO, remotepath: str, overwrite: bool = False, extract: bool = False, file_content: str | None = None, file_format: str | None = None, file_tags: str | None = None, **kwargs)#

Upload a file as an XNAT resource.

Parameters:
  • data (str) – The data to upload, either a str, bytes or an IO object

  • 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: str | Path, overwrite: bool = False, method: str = '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 – The directory to upload

  • overwrite – Flag to force overwriting of files

  • method – 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: 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: XNATBaseObject

DEFAULT_SEARCH_FIELDS = ['id', 'project', 'subject_id']#
FROM_SEARCH_URI = '{session_uri}/projects/{project}/subjects/{subject_id}/experiments/{session_id}'#
SECONDARY_LOOKUP_FIELD = 'label'#
activate()#
property cache_id#
cli_str()#
classmethod create_cache_id(uri, fieldname, data)#
property data_dir#
property label#
quarantine()#
property status: str#
class xnat.mixin.ImageScanData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)#

Bases: XNATBaseObject

SECONDARY_LOOKUP_FIELD = 'type'#
create_resource(label, format=None, data_dir=None, method='tgz_file')#
property data_dir#
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: 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: XNATBaseObject

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

Bases: XNATBaseObject

FROM_SEARCH_URI = '{session_uri}/projects/{id}'#
SECONDARY_LOOKUP_FIELD = 'name'#
property cache_id#
cli_str()#
classmethod create_cache_id(uri, fieldname, data)#
create_resource(label, format=None, data_dir=None, method=None) AbstractResource#
property data_dir#
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#
parent = None#
property project#
property resources#
property subjects#
property users#
class xnat.mixin.SubjectAssessorData(uri=None, xnat_session=None, id_=None, datafields=None, parent=None, fieldname=None, overwrites=None, **kwargs)#

Bases: 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: XNATBaseObject

FROM_SEARCH_URI = '{session_uri}/projects/{project}/subjects/{subjectid}'#
SECONDARY_LOOKUP_FIELD = 'label'#
property cache_id#
cli_str()#
classmethod create_cache_id(uri, fieldname, data)#
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)#