Skip to content

readstore-cli package

readstore module

Provides readstore command line interface

Functions:

Name Description
- configure_list

List configuration settings

- configure

Configure ReadStore CLI

- upload

Upload FASTQ Files

- import_fastq

Import FASTQ Files from Template

- upload_pro_data

Upload Processed Data

- list_fq_datasets

List Datasets

- list_projects

List Projects

- list_pro_data

List Processed Data

- get_fastq_dataset

Get Dataset

- get_project

Get Project

- get_pro_data

Get Processed Data

- create_fastq_dataset

Create Dataset

- create_project

Create Project

- update_fq_dataset

Update Dataset

- update_project

Update Project

- delete_pro_data

Delete Processed Data

- download_fq_dataset_attachment

Download Dataset Attachment

- download_project_attachment

Download Project Attachment

- main

Main function for ReadStore CLI

_get_readstore_client()

Get ReadStore RSClient

Load readstore configuration and generate client Requires READSTORE_CONFIG_FILE global Requires DEFAULT_ENDPOINT_URL Requires DEFAULT_FASTQ_EXTENSIONS Requires DEFAULT_OUTPUT

Raises:

Type Description
ReadStoreError

If no config is found in config file or ENV variables

Returns:

Type Description
RSClient

rsclient.RSClient

Source code in readstore_cli/readstore.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
def _get_readstore_client() -> rsclient.RSClient:
    """Get ReadStore RSClient

    Load readstore configuration and generate client
    Requires READSTORE_CONFIG_FILE global
    Requires DEFAULT_ENDPOINT_URL
    Requires DEFAULT_FASTQ_EXTENSIONS
    Requires DEFAULT_OUTPUT

    Raises:
        rsexceptions.ReadStoreError:
            If no config is found in config file or ENV variables

    Returns:
        rsclient.RSClient
    """

    if os.path.isfile(READSTORE_CONFIG_FILE):
        config_params = rsconfig.load_rs_config(filename=READSTORE_CONFIG_FILE)
    else:
        try:
            # Try to load default configuration and environment variables
            config_params = rsconfig.load_rs_config(
                default_endpoint_url=DEFAULT_ENDPOINT_URL,
                default_fastq_extensions=DEFAULT_FASTQ_EXTENSIONS,
                default_output=DEFAULT_OUTPUT,
            )

        except rsexceptions.ReadStoreError as e:
            raise rsexceptions.ReadStoreError(
                e.message + "\n No Configuration File and No ENV Variables Found"
            )

    username, token, endpoint_url, fastq_extensions, output = config_params

    client = rsclient.RSClient(username, token, endpoint_url, output)

    return client

_validate_read_path(fq_file_path)

Check fq_file path

Check if fastq file exists and can be read

Parameters:

Name Type Description Default
fq_file_path str

File to check

required

Returns:

Name Type Description
bool bool

True if path is valid else False

Source code in readstore_cli/readstore.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def _validate_read_path(fq_file_path: str) -> bool:
    """Check fq_file path

    Check if fastq file exists and can be read

    Args:
        fq_file_path: File to check

    Returns:
        bool: True if path is valid else False
    """

    # Check if file exists
    if not os.path.isfile(fq_file_path):
        sys.stderr.write(
            f"""ReadStore Warning:
            Upload Path of this FASTQ File could not be found: {fq_file_path}\n"""
        )
        return False
    # Check for read permission
    elif not os.access(fq_file_path, os.R_OK):
        sys.stderr.write(f"ReadStore Warning: No Read Permission: {fq_file_path}\n")
        return False
    else:
        return True

configure()

Configure CLI

Write config file for ReadStore CLI

Requires: READSTORE_CONFIG_FILE

Write config file to READSTORE_CONFIG_FILE

Source code in readstore_cli/readstore.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
def configure():
    """Configure CLI

    Write config file for ReadStore CLI

    Requires: READSTORE_CONFIG_FILE

    Write config file to READSTORE_CONFIG_FILE

    """

    print("Configuring ReadStore CLI")

    readstore_config_dir = os.path.dirname(READSTORE_CONFIG_FILE)

    os.makedirs(readstore_config_dir, exist_ok=True)

    username = input("ReadStore Username: ")
    token = input("ReadStore Token: ")
    output = input("Default Output Format (json, text, csv): ")

    if output not in OUTPUT_FORMATS:
        sys.stderr.write("ReadStore Error: Invalid Output Format.\n")
        return

    endpoint_url = DEFAULT_ENDPOINT_URL
    fastq_extensions = DEFAULT_FASTQ_EXTENSIONS
    write_config = True

    # Check if config exists, if so, ask to overwrite
    if os.path.isfile(READSTORE_CONFIG_FILE):

        try:
            config = rsconfig.load_rs_config(READSTORE_CONFIG_FILE)
            (
                username_old,
                token_old,
                endpoint_url_old,
                fastq_extensions_old,
                output_format_old,
            ) = config
            write_config = False
            print(f"Config file found at {READSTORE_CONFIG_FILE}")
            overwrite = input("Overwrite? (y/n): ")

            # If not overwrite, don't write config
            if overwrite.lower().strip() == "y":

                endpoint_url = endpoint_url_old
                fastq_extensions = fastq_extensions_old
                rsconfig.write_rs_config(
                    READSTORE_CONFIG_FILE,
                    username,
                    token,
                    endpoint_url,
                    fastq_extensions,
                    output,
                )
                print("Configuration File Updated")
            else:
                print("Abort Configuration")

        except rsexceptions.ReadStoreError:
            # If config file is invalid, overwrite anyway
            sys.stderr.write("Error Setting Configuration\n")

    if write_config:

        rsconfig.write_rs_config(
            READSTORE_CONFIG_FILE,
            username,
            token,
            endpoint_url,
            fastq_extensions,
            output,
        )
        print(f"Created New Configuration File at {READSTORE_CONFIG_FILE}")

configure_list()

List config settings

List user and general client configuration Print in console

Raises: rsexceptions.ReadStoreError

Source code in readstore_cli/readstore.py
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def configure_list():
    """List config settings

    List user and general client configuration
    Print in console



    Raises: rsexceptions.ReadStoreError
    """

    print("Listing ReadStore Configuration and Credentials")

    if os.path.isfile(READSTORE_CONFIG_FILE):
        try:
            config_params = rsconfig.load_rs_config(READSTORE_CONFIG_FILE)
            username, token, endpoint_url, fastq_extensions, output = config_params

            # For token make last 4 characters visible
            token_hidden = "*" * (len(token) - 4) + token[-4:]

            print(f"Configuration File Found at {READSTORE_CONFIG_FILE}")

            print("[USER]")
            print(f"Username: {username}")
            print(f"Token: {token_hidden}")

            print("[GENERAL]")
            print(f"Endpoint URL: {endpoint_url}")
            print(f"""FASTQ Extensions: {fastq_extensions}""")
            print(f"""Default Output: {output}""")

        except rsexceptions.ReadStoreError as e:
            # If config file is invalid, overwrite anyway
            sys.stderr.write(e.message + "\n")
            sys.stderr.write(
                """Configuration Found, But Corrupted.\n
                             Reset Configuration with "readstore configure"\n"""
            )
    else:
        sys.stderr.write(
            """No Configuration Found.\n
                        Set Configuration with "readstore configure"\n"""
        )

download_fq_dataset_attachment(attachment_name, outpath, dataset_id=None, dataset_name=None)

Download Fastq Dataset Attachment

Parameters:

Name Type Description Default
attachment_name str

Choose attachment to download

required
outpath str

Set outpath to write file to.

required
dataset_id int | None

Set dataset id

None
dataset_name str | None

Set dataset name

None
Source code in readstore_cli/readstore.py
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
def download_fq_dataset_attachment(
    attachment_name: str,
    outpath: str,
    dataset_id: int | None = None,
    dataset_name: str | None = None,
):
    """Download Fastq Dataset Attachment

    Args:
        attachment_name: Choose attachment to download
        outpath: Set outpath to write file to.
        dataset_id: Set dataset id
        dataset_name: Set dataset name
    """

    if not dataset_id and not dataset_name:
        sys.stderr.write(
            "ReadStore Error: Must Provide Dataset ID (--id) or Name (--name)\n"
        )
        sys.stderr.write("ReadStore Error: Run readstore download -h for help\n")
        return

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    outpath = os.path.abspath(outpath)
    out_dirname = os.path.dirname(outpath)

    # case directory path (e.g. '.' or /home/user/)
    if os.path.isdir(outpath):
        download_path = os.path.join(outpath, attachment_name)
    # case full path is provided, e.g. test.png or /home/user/test.png
    elif os.path.isdir(out_dirname):
        download_path = outpath
    else:
        sys.stderr.write(
            f"ReadStore Error: Output Directory Path Not Found: {outpath}\n"
        )
        return

    try:
        client.download_fq_dataset_attachment(
            attachment_name=attachment_name,
            outpath=download_path,
            dataset_id=dataset_id,
            dataset_name=dataset_name,
        )

        print(f"ReadStore Download: {attachment_name}\nDownloaded to {outpath}")

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

download_project_attachment(attachment_name, outpath, project_id=None, project_name=None)

Download Project Attachment

Download attachment file from project defined by project id or project name and download attachment_name

Either project_id and project_name are required

Parameters:

Name Type Description Default
attachment_name str

Choose attachment to download

required
outpath str

Set outpath to write file to.

required
project_id int | None

Set project id

None
project_name str | None

Set project name

None
Source code in readstore_cli/readstore.py
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
def download_project_attachment(
    attachment_name: str,
    outpath: str,
    project_id: int | None = None,
    project_name: str | None = None,
):
    """Download Project Attachment

    Download attachment file from project defined by project id
    or project name and download attachment_name

    Either project_id and project_name are required

    Args:
        attachment_name: Choose attachment to download
        outpath: Set outpath to write file to.
        project_id: Set project id
        project_name: Set project name
    """

    if not project_id and not project_name:
        sys.stderr.write(
            "ReadStore Error: Must Provide Project ID (--id) or Name (--name)\n"
        )
        sys.stderr.write(
            "ReadStore Error: Run readstore project download -h for help\n"
        )
        return

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    outpath = os.path.abspath(outpath)
    out_dirname = os.path.dirname(outpath)

    # case directory path (e.g. '.' or /home/user/)
    if os.path.isdir(outpath):
        download_path = os.path.join(outpath, attachment_name)
    # case full path is provided, e.g. test.png or /home/user/test.png
    elif os.path.isdir(out_dirname):
        download_path = outpath
    else:
        sys.stderr.write(
            f"ReadStore Error: Output Directory Path Not Found: {outpath}\n"
        )
        return

    try:
        client.download_project_attachment(
            attachment_name=attachment_name,
            outpath=download_path,
            project_id=project_id,
            project_name=project_name,
        )

        print(f"ReadStore Download: {attachment_name}\nDownloaded to {outpath}")

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

get_fastq_dataset(dataset_id=None, dataset_name=None, meta=False, attachment=False, pro_data=False, read1=False, read2=False, index1=False, index2=False, read1_path=False, read2_path=False, index1_path=False, index2_path=False, output=None)

Get individual FASTQ dataset

Use arguments to filter and return specific data such as individual reads, metadata or read paths

Parameters:

Name Type Description Default
dataset_id int | None

Filter by Dataset Id. Defaults to None.

None
dataset_name str | None

Filter by Dataset Name. Defaults to None.

None
meta bool

Show only metadata.

False
attachment bool

Show only attachments

False
read1 bool

Show Read 1 data.

False
read2 bool

Show Read 2 data.

False
index1 bool

Show Index 1 data

False
index2 bool

Show Index 2 data

False
read1_path bool

Show Read 1 Path

False
read2_path bool

Show Read 2 Path

False
index1_path bool

Show Index 1 Path

False
index2_path bool

Show Index 2 Path

False
output str | None

Set output format. If none use default from config file

None
Source code in readstore_cli/readstore.py
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def get_fastq_dataset(
    dataset_id: int | None = None,
    dataset_name: str | None = None,
    meta: bool = False,
    attachment: bool = False,
    pro_data: bool = False,
    read1: bool = False,
    read2: bool = False,
    index1: bool = False,
    index2: bool = False,
    read1_path: bool = False,
    read2_path: bool = False,
    index1_path: bool = False,
    index2_path: bool = False,
    output: str | None = None,
):
    """Get individual FASTQ dataset

    Use arguments to filter and return specific data
    such as individual reads, metadata or read paths

    Args:
        dataset_id: Filter by Dataset Id. Defaults to None.
        dataset_name: Filter by Dataset Name. Defaults to None.
        meta: Show only metadata.
        attachment: Show only attachments
        read1: Show Read 1 data.
        read2: Show Read 2 data.
        index1: Show Index 1 data
        index2: Show Index 2 data
        read1_path: Show Read 1 Path
        read2_path: Show Read 2 Path
        index1_path: Show Index 1 Path
        index2_path: Show Index 2 Path
        output: Set output format. If none use default from config file
    """

    if not dataset_id and not dataset_name:
        sys.stderr.write(
            "ReadStore Error: Must Provide Dataset ID (--id) or Name (--name)\n"
        )
        sys.stderr.write("ReadStore Error: Run readstore get -h for help\n")
        return

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if output is None:
        output = client.get_output_format()

    try:
        fq_dataset = client.get_fastq_dataset(dataset_id, dataset_name)

        path = False

        # Check if dataset is empty
        if fq_dataset == {}:
            out_data = {}
        elif meta:
            out_data = fq_dataset.pop("metadata", {})
        elif attachment:
            out_data = fq_dataset.pop("attachments", {})
            out_data = {"name": out_data}
        elif pro_data:
            out_data = fq_dataset.pop("pro_data", {})
            out_data = {"pro_data": out_data}

        # Return individual read files
        elif read1:
            if fq_dataset["fq_file_r1"]:
                out_data = client.get_fq_file(fq_dataset["fq_file_r1"])
            else:
                out_data = {}
        elif read2:
            if fq_dataset["fq_file_r2"]:
                out_data = client.get_fq_file(fq_dataset["fq_file_r2"])
            else:
                out_data = {}
        elif index1:
            if fq_dataset["fq_file_i1"]:
                out_data = client.get_fq_file(fq_dataset["fq_file_i1"])
            else:
                out_data = {}
        elif index2:
            if fq_dataset["fq_file_i2"]:
                out_data = client.get_fq_file(fq_dataset["fq_file_i2"])
            else:
                out_data = {}
        elif read1_path:
            path = True
            if fq_dataset["fq_file_r1"]:
                out_data = client.get_fq_file_upload_path(fq_dataset["fq_file_r1"])
                _ = _validate_read_path(out_data)
            else:
                out_data = ""
        elif read2_path:
            path = True
            if fq_dataset["fq_file_r2"]:
                out_data = client.get_fq_file_upload_path(fq_dataset["fq_file_r2"])
                _ = _validate_read_path(out_data)
            else:
                out_data = ""
        elif index1_path:
            path = True
            if fq_dataset["fq_file_i1"]:
                out_data = client.get_fq_file_upload_path(fq_dataset["fq_file_i1"])
                _ = _validate_read_path(out_data)
            else:
                out_data = ""
        elif index2_path:
            path = True
            if fq_dataset["fq_file_i2"]:
                out_data = client.get_fq_file_upload_path(fq_dataset["fq_file_i2"])
                _ = _validate_read_path(out_data)
            else:
                out_data = ""
        # Return individual read files
        else:
            # Reformat so that all data is in one dict
            out_data = fq_dataset

        if output == "json":
            print(out_data)
        elif output == "text":
            if path:
                print(out_data)
            else:
                header = list(out_data.keys())
                header_str = " | ".join(header)
                print(header_str)

                if attachment:
                    values_str = "\n".join(out_data["name"])
                else:
                    values = [str(out_data[key]) for key in header]
                    values_str = " | ".join(values)
                print(values_str)
        elif output == "csv":
            if path:
                print(out_data)
            else:
                header = list(out_data.keys())
                header_str = ",".join(header)
                print(header_str)

                if attachment:
                    values_str = "\n".join(out_data["name"])
                else:
                    values = [str(out_data[key]) for key in header]
                    values_str = ",".join(values)
                print(values_str)
        else:
            sys.stderr.write("Output Format Not Supported\n")
            return

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

get_project(project_id=None, project_name=None, meta=False, attachment=False, output=None)

Get individual Project

Must define project id or name Options to show only meta and attachments

Parameters:

Name Type Description Default
project_id int | None

Set Project ID

None
project_name str | None

Set Project Name

None
meta bool

Show only meta data

False
attachment bool

Show only attachments

False
output str | None

Set output format. If none use default from config file

None
Source code in readstore_cli/readstore.py
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
def get_project(
    project_id: int | None = None,
    project_name: str | None = None,
    meta: bool = False,
    attachment: bool = False,
    output: str | None = None,
):
    """Get individual Project

    Must define project id or name
    Options to show only meta and attachments

    Args:
        project_id: Set Project ID
        project_name: Set Project Name
        meta: Show only meta data
        attachment: Show only attachments
        output: Set output format. If none use default from config file
    """

    if not project_id and not project_name:
        sys.stderr.write(
            "ReadStore Error: Must Provide Project ID (--id) or Name (--name)\n"
        )
        sys.stderr.write("ReadStore Error: Run readstore project get -h for help\n")
        return

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if output is None:
        output = client.get_output_format()

    try:
        project = client.get_project(project_id, project_name)

        project.pop("dataset_metadata_keys", None)

        if meta:
            out_data = project.pop("metadata", {})
        elif attachment:
            out_data = project.pop("attachments", {})
            out_data = {"name": out_data}
        else:
            out_data = project

        if output == "json":
            print(out_data)
        elif output == "text":
            header = list(out_data.keys())
            header_str = " | ".join(header)
            print(header_str)

            if attachment:
                values_str = "\n".join(out_data["name"])
            else:
                values = [str(out_data[key]) for key in header]
                values_str = " | ".join(values)

            print(values_str)
        elif output == "csv":
            header = list(out_data.keys())
            header_str = ",".join(header)
            print(header_str)

            if attachment:
                values_str = "\n".join(out_data["name"])
            else:
                values = [str(out_data[key]) for key in header]
                values_str = ",".join(values)
            print(values_str)
        else:
            sys.stderr.write("Output Format Not Supported\n")
            return

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

import_fastq(fastq_template_csv)

Upload fastq files from template

Upload fastq files defined in template csv file Template csv file must have columns: FASTQFileName, ReadType, UploadPath

Parameters:

Name Type Description Default
fastq_template_csv str

Path to fastq template csv

required

Raises:

Type Description
ReadStoreError

If file is not found or not a csv file

ReadStoreError

If upload path is not found

ReadStoreError

If invalid FASTQ extension

ReadStoreError

If invalid Read Type

Source code in readstore_cli/readstore.py
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def import_fastq(fastq_template_csv: str):
    """Upload fastq files from template

    Upload fastq files defined in template csv file
    Template csv file must have columns:
    FASTQFileName, ReadType, UploadPath

    Args:
        fastq_template_csv (str): Path to fastq template csv

    Raises:
        rsexceptions.ReadStoreError: If file is not found or not a csv file
        rsecxeptions.ReadStoreError: If upload path is not found
        rsexceptions.ReadStoreError: If invalid FASTQ extension
        rsexceptions.ReadStoreError: If invalid Read Type
    """

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if not fastq_template_csv.endswith(".csv"):
        sys.stderr.write("ReadStore Error: File is not a .csv file\n")
        return

    if not os.path.isfile(fastq_template_csv):
        sys.stderr.write(f"ReadStore Error: File Not Found: {fastq_template_csv}\n")
        return

    fq_file_names = []
    read_types = []
    upload_paths = []

    with open(fastq_template_csv, "r") as f:
        header = False
        for line in f.readlines():
            line = line.rstrip("\n").split(",")
            if not header:
                header = line
                if not all(
                    e in ["FASTQFileName", "ReadType", "UploadPath"] for e in header
                ):
                    sys.stderr.write(
                        """ReadStore Error: Invalid Template Header.
                        Must be FASTQFileName,ReadType,UploadPath\n"""
                    )
                else:
                    header = True
            else:
                fq_file_name, read_type, upload_path = line

                if not _validate_read_path(upload_path):
                    sys.stderr.write(
                        f"\nReadStore Upload: File Not Found: {upload_path}\n"
                    )

                if not upload_path.endswith(tuple(DEFAULT_FASTQ_EXTENSIONS)):
                    sys.stderr.write(
                        f"\nReadStore Upload: Invalid FASTQ Extension: {upload_path}\n"
                    )

                if read_type not in ["R1", "R2", "I1", "I2"]:
                    sys.stderr.write(
                        f"ReadStore Error: Invalid Read Type for file: {upload_path}\n"
                    )

                if fq_file_name == "":
                    sys.stderr.write(
                        f"ReadStore Error: Invalid Read Type for file: {upload_path}\n"
                    )

                fq_file_names.append(fq_file_name)
                read_types.append(read_type)
                upload_paths.append(upload_path)

    for upload_path, fq_file_name, read_type in zip(
        upload_paths, fq_file_names, read_types
    ):
        print(f"ReadStore Upload: Start {fq_file_name}")
        try:
            client.upload_fastq(upload_path, fq_file_name, read_type)
        except rsexceptions.ReadStoreError as e:
            sys.stderr.write(f"ReadStore Error: {e.message}\n")

list_fq_datasets(project_name=None, project_id=None, role=None, meta=False, attachment=False, pro_data=False, output=None)

List Fastq Datasets

List all Fastq Datasets and Filter by Project Options to show only meta and attachments

Parameters:

Name Type Description Default
project_name str | None

Filter by Project Name

None
project_id int | None

Filter by Project Id

None
role str | None

Filter by Owner Role

None
meta bool

Show metadata

False
attachment bool

Show attachments

False
output str | None

Set output format. If none use default from config file

None
Source code in readstore_cli/readstore.py
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
def list_fq_datasets(
    project_name: str | None = None,
    project_id: int | None = None,
    role: str | None = None,
    meta: bool = False,
    attachment: bool = False,
    pro_data: bool = False,
    output: str | None = None,
):
    """List Fastq Datasets

    List all Fastq Datasets and Filter by Project
    Options to show only meta and attachments

    Args:
        project_name: Filter by Project Name
        project_id: Filter by Project Id
        role: Filter by Owner Role
        meta: Show metadata
        attachment: Show attachments
        output: Set output format. If none use default from config file
    """

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if output is None:
        output = client.get_output_format()

    try:
        fq_datasets = client.list_fastq_datasets(project_name, project_id, role)

        for fq in fq_datasets:
            if not meta:
                fq.pop("metadata", None)
            if not attachment:
                fq.pop("attachments", None)
            if not pro_data:
                fq.pop("pro_data", None)

        if output == "json":
            print(fq_datasets)
        elif output == "text":
            if len(fq_datasets) > 0:
                header = list(fq_datasets[0].keys())
                header_str = " | ".join(header)
                print(header_str)

                for fq in fq_datasets:
                    values = [str(fq[key]) for key in header]
                    values_str = " | ".join(values)
                    print(values_str)
        elif output == "csv":
            if len(fq_datasets) > 0:
                header = list(fq_datasets[0].keys())
                header_str = ",".join(header)
                print(header_str)

                for fq in fq_datasets:
                    values = [str(fq[key]) for key in header]
                    values_str = ",".join(values)
                    print(values_str)
        else:
            sys.stderr.write("Output Format Not Supported\n")
            return

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

list_pro_data(project_id=None, project_name=None, dataset_id=None, dataset_name=None, name=None, data_type=None, meta=False, archived=False, output=None)

List Processed Data

List all Processed Data Filter by Project, Dataset, Data Type, Metadata and Archive

Parameters:

Name Type Description Default
project_name str | None

Filter by Project Name

None
project_id int | None

Filter by Project ID

None
dataset_id int | None

Filter by Dataset ID

None
dataset_name str | None

Filter by Dataset Name

None
data_type str | None

Filter by Data Type

None
meta bool

Filter by Metadata

False
archived bool

Include Archived Data

False
output str | None

Set output format. If none use default from config file

None
Source code in readstore_cli/readstore.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
def list_pro_data(
    project_id: int | None = None,
    project_name: str | None = None,
    dataset_id: int | None = None,
    dataset_name: str | None = None,
    name: str | None = None,
    data_type: str | None = None,
    meta: bool = False,
    archived: bool = False,
    output: str | None = None,
):
    """List Processed Data

    List all Processed Data
    Filter by Project, Dataset, Data Type, Metadata and Archive

    Args:
        project_name: Filter by Project Name
        project_id: Filter by Project ID
        dataset_id: Filter by Dataset ID
        dataset_name: Filter by Dataset Name
        data_type: Filter by Data Type
        meta: Filter by Metadata
        archived: Include Archived Data
        output: Set output format. If none use default from config file
    """

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if output is None:
        output = client.get_output_format()

    try:
        pro_data = client.list_pro_data(
            project_id,
            project_name,
            dataset_id,
            dataset_name,
            name,
            data_type,
            archived,
        )

        for p in pro_data:
            if not meta:
                p.pop("metadata", None)

        if output == "json":
            print(pro_data)
        elif output == "text":
            if len(pro_data) > 0:
                header = list(pro_data[0].keys())
                header_str = " | ".join(header)
                print(header_str)

                for p in pro_data:
                    values = [str(p[key]) for key in header]
                    values_str = " | ".join(values)
                    print(values_str)
        elif output == "csv":
            if len(pro_data) > 0:
                header = list(pro_data[0].keys())
                header_str = ",".join(header)
                print(header_str)

                for p in pro_data:
                    values = [str(p[key]) for key in header]
                    values_str = ",".join(values)
                    print(values_str)
        else:
            sys.stderr.write("Output Format Not Supported\n")
            return

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

list_projects(role=None, meta=False, attachment=False, output=None)

List Projects

List all Fastq Projects. Options to add metadata and attachments

Role must be in owner, collaborator, creator

Parameters:

Name Type Description Default
role str | None

Filter by Owner Role

None
meta bool

Show metadata

False
attachment bool

Show attachments

False
output str | None

Set output format. If none use default from config file

None
Source code in readstore_cli/readstore.py
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
def list_projects(
    role: str | None = None,
    meta: bool = False,
    attachment: bool = False,
    output: str | None = None,
):
    """List Projects

    List all Fastq Projects.
    Options to add metadata and attachments

    Role must be in owner, collaborator, creator

    Args:
        role: Filter by Owner Role
        meta: Show metadata
        attachment: Show attachments
        output: Set output format. If none use default from config file
    """

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    if output is None:
        output = client.get_output_format()
    try:
        projects = client.list_projects(role)

        for p in projects:
            p.pop("dataset_metadata_keys", None)
            if not meta:
                p.pop("metadata", None)
            if not attachment:
                p.pop("attachments", None)

        if output == "json":
            print(projects)
        elif output == "text":
            if len(projects) > 0:
                header = list(projects[0].keys())
                header_str = " | ".join(header)
                print(header_str)

                for p in projects:
                    values = [str(p[key]) for key in header]
                    values_str = " | ".join(values)
                    print(values_str)
        elif output == "csv":
            if len(projects) > 0:
                header = list(projects[0].keys())
                header_str = ",".join(header)
                print(header_str)

                for p in projects:
                    values = [str(p[key]) for key in header]
                    values_str = ",".join(values)
                    print(values_str)
        else:
            sys.stderr.write("Output Format Not Supported\n")
            return

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

main()

Main function for ReadStore CLI

Source code in readstore_cli/readstore.py
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
def main():
    """
    Main function for ReadStore CLI

    """

    args = parser.parse_args()

    # Keep hierarchy of commands. First check for subparsers.
    if "config_list" in args:
        configure_list()

    elif "config_run" in args:
        configure()

    elif "upload_run" in args:
        upload(fastq_files=args.fastq_files)

    elif "list_fq_run" in args:
        list_fq_datasets(
            project_name=args.project_name,
            project_id=args.project_id,
            role=args.role,
            meta=args.meta,
            attachment=args.attachment,
            pro_data=args.pro_data,
            output=args.output,
        )

    elif "get_fq_run" in args:
        read1 = args.read1
        read2 = args.read2
        index1 = args.index1
        index2 = args.index2
        read1_path = args.read1_path
        read2_path = args.read2_path
        index1_path = args.index1_path
        index2_path = args.index2_path

        meta = args.meta
        attachment = args.attachment
        pro_data = args.pro_data

        if (
            sum([read1,
                 read2,
                 index1,
                 index2,
                 read1_path,
                 read2_path,
                 index1_path,
                 index2_path,
                 meta,
                 attachment,
                 pro_data]) > 1
        ):
            sys.stderr.write(
                """ReadStore Error: Only One Flag Allowed for -r1, -r2,
                             -i1, -i2, -m, -r1p, -r2p, -i1p, -i2p, -m, -a, -pd\n\n"""
            )
            get_fq_parser.print_help()
        else:
            get_fastq_dataset(
                dataset_id=args.id,
                dataset_name=args.name,
                meta=meta,
                attachment=attachment,
                pro_data=pro_data,
                read1=read1,
                read2=read2,
                index1=index1,
                index2=index2,
                read1_path=read1_path,
                read2_path=read2_path,
                index1_path=index1_path,
                index2_path=index2_path,
                output=args.output,
            )

    elif "create_fq_run" in args:

        if args.project_id:
            project_ids = [args.project_id]
        else:
            project_ids = []

        if args.project_name:
            project_names = [args.project_name]
        else:
            project_names = []

        create_fq_dataset(
            name=args.name,
            description=args.description,
            project_ids=project_ids,
            project_names=project_names,
            metadata=args.meta,
        )

    elif "update_fq_run" in args:

        if args.project_id:
            project_ids = [args.project_id]
        else:
            project_ids = None

        if args.project_name:
            project_names = [args.project_name]
        else:
            project_names = None

        update_fq_dataset(
            dataset_id=args.id,
            dataset_name=args.name,
            description=args.description,
            project_ids=project_ids,
            project_names=project_names,
            metadata=args.meta,
        )

    elif "download_run" in args:
        download_fq_dataset_attachment(
            attachment_name=args.attachment,
            outpath=args.outpath,
            dataset_id=args.id,
            dataset_name=args.name,
        )

    elif "dataset_run" in args:
        dataset_parser.print_help()

    elif "list_project_run" in args:
        list_projects(
            role=args.role,
            meta=args.meta,
            attachment=args.attachment,
            output=args.output,
        )

    elif "get_project_run" in args:
        get_project(
            project_id=args.id,
            project_name=args.name,
            meta=args.meta,
            attachment=args.attachment,
            output=args.output,
        )

    elif "create_project_run" in args:
        create_project(name=args.name, description=args.description, metadata=args.meta)

    elif "update_project_run" in args:
        update_project(
            project_id=args.id,
            project_name=args.name,
            description=args.description,
            metadata=args.meta,
        )

    elif "download_project_run" in args:
        download_project_attachment(
            attachment_name=args.attachment,
            outpath=args.outpath,
            project_id=args.id,
            project_name=args.name,
        )

    elif "project_run" in args:
        project_parser.print_help()

    elif "import_fastq_run" in args:
        import_fastq(args.fastq_template[0])

    elif "import_run" in args:
        import_parser.print_help()

    elif "pro_data_upload_run" in args:

        dataset_id = args.dataset_id
        dataset_name = args.dataset_name

        if (not dataset_id) and (not dataset_name):
            sys.stderr.write(
                "ReadStore Error: Must Provide Dataset ID (--did) or Dataset Name (--d) to attach ProData to\n"
            )
            pro_data_parser.print_help()
        else:       
            upload_pro_data(
                name=args.name,
                pro_data_file=args.pro_data_file,
                data_type=args.type,
                description=args.description,
                metadata=args.meta,
                dataset_id=args.dataset_id,
                dataset_name=args.dataset_name,
            )

    elif "pro_data_list_run" in args:
        list_pro_data(
            project_id=args.project_id,
            project_name=args.project_name,
            dataset_id=args.dataset_id,
            dataset_name=args.dataset_name,
            name=args.name,
            data_type=args.type,
            meta=args.meta,
            archived=args.archived,
            output=args.output,
        )

    elif "pro_data_get_run" in args:
        get_pro_data(
            pro_data_id=args.id,
            name=args.name,
            meta=args.meta,
            upload_path=args.upload_path,
            version=args.version,
            dataset_id=args.dataset_id,
            dataset_name=args.dataset_name,
            output=args.output,
        )

    elif "pro_data_delete_run" in args:
        delete_pro_data(
            pro_data_id=args.id,
            name=args.name,
            version=args.version,
            dataset_id=args.dataset_id,
            dataset_name=args.dataset_name,
        )

    elif "pro_data_run" in args:
        pro_data_parser.print_help()

    elif args.version:
        print(f"ReadStore CLI Version: {__version__}")
        sys.exit(0)

    else:
        parser.print_help()

upload(fastq_files)

Upload fastq files

Upload provided files

Check files by extension

Parameters:

Name Type Description Default
fastq_files List[str]

Fastq files to upload

required
Source code in readstore_cli/readstore.py
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def upload(fastq_files: List[str]):
    """Upload fastq files

    Upload provided files

    Check files by extension

    Args:
        fastq_files: Fastq files to upload
    """

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    for fq in fastq_files:
        print(f"ReadStore Upload: Start {fq}")

        if not os.path.isfile(fq):
            sys.stderr.write(f"\nReadStore Upload: File Not Found: {fq}\n")
            continue
        elif not fq.endswith(tuple(DEFAULT_FASTQ_EXTENSIONS)):
            sys.stderr.write(f"\nReadStore Upload: Invalid FASTQ Extension: {fq}\n")
        else:
            try:
                client.upload_fastq(fq)
            except rsexceptions.ReadStoreError as e:
                sys.stderr.write(f"ReadStore Error: {e.message}\n")

upload_pro_data(name, pro_data_file, data_type, description, metadata, dataset_id=None, dataset_name=None)

Upload Processed Data

Source code in readstore_cli/readstore.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def upload_pro_data(
    name: str,
    pro_data_file: str,
    data_type: str,
    description: str,
    metadata: str,
    dataset_id: int | None = None,
    dataset_name: str | None = None,
):
    """Upload Processed Data"""

    # Get ReadStore Client and Validate Connection
    try:
        client = _get_readstore_client()
    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")
        return

    fq_dataset = client.get_fastq_dataset(dataset_id, dataset_name)
    if fq_dataset == {}:
        sys.stderr.write("ReadStore Error: Dataset to attach ProData Not Found\n")
        return

    fq_dataset_id = fq_dataset["id"]

    # Convert metadata json string to dict
    try:
        metadata = json.loads(metadata)
    except json.JSONDecodeError:
        sys.stderr.write("ReadStore Error: Invalid Metadata JSON String\n")
        return

    print(f"ReadStore ProData Upload: Start {pro_data_file}")

    try:
        client.upload_pro_data(
            name,
            pro_data_file,
            data_type,
            dataset_id=fq_dataset_id,
            metadata=metadata,
            description=description,
        )

    except rsexceptions.ReadStoreError as e:
        sys.stderr.write(f"ReadStore Error: {e.message}\n")

rsclient module

Provides client for interacting with ReadStore API.

Classes:

Name Description
- RSClient

Provides client for interacting with ReadStore API.

RSClient

A client for interacting with the ReadStore API

Attributes:

Name Type Description
username

ReadStore username

token

ReadStore user token

endpoint

The endpoint URL for the ReadStore API

output_format

The default output format for the client

Methods:

Name Description
_test_server_connection

Validate server URL

_auth_user_token

Validate user and token

validate_charset

Validate charset for query string

validate_metadata

Validate metadata dict

get_output_format

Get Output Format set for client

upload_fastq

Upload Fastq Files

get_fq_file

Get Fastq File

list_fq_files

List Fastq Files

create_fq_file

Create Fastq File

update_fq_file

Update Fastq File

delete_fq_file

Delete Fastq File

get_fq_file_upload_path

Get FASTQ file upload path

list_fastq_datasets

List FASTQ Datasets

get_fastq_dataset

Get FASTQ dataset

create_fastq_dataset

Create Fastq Dataset

update_fastq_dataset

Update Fastq Dataset

delete_fastq_dataset

Delete Fastq Dataset

list_projects

List Projects

get_project

Get Project by id or name

create_project

Create Project

update_project

Update Project

delete_project

Delete Project

download_project_attachment

Download Project Attachments

download_fq_dataset_attachment

Download Fastq Attach

upload_pro_data

Upload Processed Data

list_pro_data

List Processed Data

get_pro_data

Get Processed Data

delete_pro_data

Delete Processed Data

Source code in readstore_cli/rsclient.py
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
class RSClient:
    """
        A client for interacting with the ReadStore API

        Attributes:
            username: ReadStore username
            token: ReadStore user token
            endpoint: The endpoint URL for the ReadStore API
            output_format: The default output format for the client

        Methods:
            _test_server_connection: Validate server URL
            _auth_user_token: Validate user and token
            validate_charset: Validate charset for query string
            validate_metadata: Validate metadata dict
            get_output_format: Get Output Format set for client
            upload_fastq: Upload Fastq Files
            get_fq_file: Get Fastq File
            list_fq_files: List Fastq Files
            create_fq_file: Create Fastq File
            update_fq_file: Update Fastq File
            delete_fq_file: Delete Fastq File
            get_fq_file_upload_path: Get FASTQ file upload  path
            list_fastq_datasets: List FASTQ Datasets
            get_fastq_dataset: Get FASTQ dataset
            create_fastq_dataset: Create Fastq Dataset
            update_fastq_dataset: Update Fastq Dataset
            delete_fastq_dataset: Delete Fastq Dataset
            list_projects: List Projects
            get_project: Get Project by id or name
            create_project: Create Project
            update_project: Update Project
            delete_project: Delete Project
            download_project_attachment: Download Project Attachments
            download_fq_dataset_attachment: Download Fastq Attach
            upload_pro_data: Upload Processed Data
            list_pro_data: List Processed Data
            get_pro_data: Get Processed Data
            delete_pro_data: Delete Processed Data
    """

    REST_API_VERSION = "api_x_v1/"
    USER_AUTH_TOKEN_ENDPOINT = "auth_token/"
    FASTQ_UPLOAD_ENDPOINT = "fq_file_upload/"
    FQ_DATASET_ENDPOINT = "fq_dataset/"
    FQ_FILE_ENDPOINT = "fq_file/"
    FQ_ATTACHMENT_ENDPOINT = "fq_attachment/"
    PROJECT_ENDPOINT = "project/"
    PROJECT_ATTACHMENT_ENDPOINT = "project_attachment/"
    PRO_DATA_ENDPOINT = "pro_data/"

    def __init__(
        self, username: str, token: str, endpoint_url: str, output_format: str
    ):
        """Constructor

        Initialize a new RSClient object

        Args:
            username: ReadStore username
            token: ReadStore user token
            endpoint_url: The endpoint URL for the ReadStore API
            output_format: The default output format for the client

        Raises:
            rsexceptions.ReadStoreError:
                Server Connection to API Failed
            rsexceptions.ReadStoreError:
                User Authentication Failed
        """

        self.username = username
        self.token = token
        self.endpoint = f"{endpoint_url}/{self.REST_API_VERSION}"
        self.output_format = output_format
        self.auth = HTTPBasicAuth(username, token)

        if not self._test_server_connection():
            raise rsexceptions.ReadStoreError(
                f"Server Connection Failed\nEndpoint URL: {self.endpoint}"
            )

        if not self._auth_user_token():
            raise rsexceptions.ReadStoreError(
                f"User Authentication Failed\nUsername: {self.username}"
            )

    def _test_server_connection(self) -> bool:
        """
        Validate server URL

        Returns:
            True if server can be reached else False
        """

        parsed_url = urlparse(self.endpoint)

        if parsed_url.scheme not in ["http", "https"]:
            return False
        else:
            try:
                response = requests.head(self.endpoint)

                if response.status_code == 200:
                    return True
                else:
                    return False
            except requests.exceptions.ConnectionError:
                return False

    def _auth_user_token(self) -> bool:
        """
        Validate user and token

        Returns:
            True if user token is valid else False
        """

        try:
            auth_endpoint = os.path.join(self.endpoint, self.USER_AUTH_TOKEN_ENDPOINT)

            res = requests.post(auth_endpoint, auth=self.auth)

            if res.status_code != 200:
                return False
            else:
                return True

        except requests.exceptions.ConnectionError:
            return False


    def validate_charset(self, query_str: str) -> bool:
        """
        Validate charset for query string

        Args:
            query_str (str): Query string to validate

        Returns:
            bool: 
        """

        allowed = string.digits + string.ascii_lowercase + string.ascii_uppercase + '_-.@'
        allowed = set(allowed)

        return set(query_str) <= allowed


    def get_output_format(self) -> str:
        """
        Get Output Format set for client

        Return:
            str output format
        """

        return self.output_format


    def upload_fastq(self,
                     fastq_path: str,
                     fastq_name: str | None = None,
                     read_type: str | None = None) -> None:
        """Upload Fastq Files

        Upload Fastq files to ReadStore.
        Check if file exists and has read permissions.

        fastq_name: List of Fastq names for files to upload
        read_type: List of read types for files to upload

        Args:
            fastq_path: List of Fastq files to upload
            fastq_name: List of Fastq names for files to upload
            read_types: List of read types for files to upload
            read_types: Must be in ['R1', 'R2', 'I1', 'I2']

        Raises:
            rsexceptions.ReadStoreError: If file not found
            rsexceptions.ReadStoreError: If no read permissions
            rsexceptions.ReadStoreError: If upload URL request failed
        """

        fq_upload_endpoint = os.path.join(self.endpoint, self.FASTQ_UPLOAD_ENDPOINT)

        # Run parallel uploads of fastq files
        fastq_path = os.path.abspath(fastq_path)

        # Make sure file exists and
        if not os.path.exists(fastq_path):
            raise rsexceptions.ReadStoreError(f"File Not Found: {fastq_path}")
        elif not os.access(fastq_path, os.R_OK):
            raise rsexceptions.ReadStoreError(f"No read permissions: {fastq_path}")

        payload = {
            "fq_file_path": fastq_path,
        }

        if not fastq_name is None:
            if fastq_name == "":
                raise rsexceptions.ReadStoreError("Fastq Name Is Empty")
            if not self.validate_charset(fastq_name):
                raise rsexceptions.ReadStoreError("Invalid Fastq Name")
            payload["fq_file_name"] = fastq_name

        if not read_type is None:
            if read_type not in ["R1", "R2", "I1", "I2"]:
                raise rsexceptions.ReadStoreError("Invalid Read Type")
            payload["read_type"] = read_type

        res = requests.post(fq_upload_endpoint, json=payload, auth=self.auth)

        if res.status_code not in [200, 204]:
            res_message = res.json().get("detail", "No Message")
            raise rsexceptions.ReadStoreError(
                f"Upload URL Request Failed: {res_message}"
            )


    def get_fq_file(self, fq_file_id: int) -> Dict:
        """Get Fastq File

        Return Fastq file data by fq_file ID

        Args:
            fq_file_id: ID (pk) of fq_file

        Returns:
            dict with fq file data
        """

        fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)


        res = requests.get(fq_file_endpoint + f'{fq_file_id}/',auth=self.auth)

        if res.status_code not in [200, 204]:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"get_fq_file failed: {detail}")
        else:
            return res.json()[0]


    def list_fq_files(self) -> List[Dict]:
        """List Fastq Files

        List Fastq files in ReadStore

        Returns:
            List of Fastq files
        """

        fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)

        res = requests.get(fq_file_endpoint, auth=self.auth)

        if res.status_code not in [200, 204]:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"list_fq_files failed: {detail}")
        else:
            return res.json()


    def create_fq_file(self,
                       name: str,
                       read_type: str,
                       qc_passed: bool,
                       read_length: int,
                       num_reads: int,
                       size_mb: int,
                       qc_phred_mean: float,
                       qc_phred: dict,
                       upload_path: str,
                       md5_checksum: str,
                       staging: bool,
                       pipeline_version: str) -> dict:

        """Create Fastq File

        Create Fastq file in ReadStore

        Args:
            name: Fastq file name
            read_type: Read type (R1, R2, I1, I2)
            qc_passed: QC Pass
            read_length: Read length
            num_reads: Number of reads
            size_mb: Size in MB
            qc_phred_mean: QC Phred Mean
            qc_phred: QC Phred
            upload_path: Upload Path
            md5_checksum: MD5 Checksum
            staging: Staging
            pipeline_version: Pipeline Version

        Returns:    
            dict: Fastq file data

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)

        # Define json for post request
        json = {
            "name": name,
            "read_type": read_type,
            "qc_passed": qc_passed,
            "read_length": read_length,
            "num_reads": num_reads,
            "size_mb": size_mb,
            "qc_phred_mean": qc_phred_mean,
            "qc_phred": qc_phred,
            "upload_path": upload_path,
            "md5_checksum": md5_checksum,
            "staging": staging,
            "pipeline_version": pipeline_version
        }

        res = requests.post(fq_file_endpoint, json=json, auth=self.auth)

        if res.status_code != 201:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"create_fq_file failed: {detail}")
        else:
            return res.json()


    def update_fq_file(self,
                       fq_file_id: int,
                       name: str,
                       read_type: str,
                       qc_passed: bool,
                       read_length: int,
                       num_reads: int,
                       size_mb: int,
                       qc_phred_mean: float,
                       qc_phred: dict,
                       upload_path: str,
                       md5_checksum: str,
                       staging: bool,
                       pipeline_version: str) -> dict:

        """Update Fastq File

        Update Fastq file in ReadStore

        Args:
            fq_file_id: ID of Fastq file
            name: Fastq file name
            read_type: Read type (R1, R2, I1, I2)
            qc_passed: QC Pass
            read_length: Read length
            num_reads: Number of reads
            size_mb: Size in MB
            qc_phred_mean: QC Phred Mean
            qc_phred: QC Phred
            upload_path: Upload Path
            md5_checksum: MD5 Checksum
            staging: Staging
            pipeline_version: Pipeline Version

        Returns:    
            dict: Fastq file data

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT, f'{fq_file_id}/')

        # Define json for post request
        json = {
            "name": name,
            "read_type": read_type,
            "qc_passed": qc_passed,
            "read_length": read_length,
            "num_reads": num_reads,
            "size_mb": size_mb,
            "qc_phred_mean": qc_phred_mean,
            "qc_phred": qc_phred,
            "upload_path": upload_path,
            "md5_checksum": md5_checksum,
            "staging": staging,
            "pipeline_version": pipeline_version
        }

        res = requests.put(fq_file_endpoint, json=json, auth=self.auth)

        if res.status_code != 200:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"update_fq_file failed: {detail}")
        else:
            return res.json()


    def delete_fq_file(self, fq_file_id: int):
        """Delete Fastq File

        Delete Fastq file in ReadStore

        Args:
            fq_file_id: ID of Fastq file

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT, f'{fq_file_id}/')

        res = requests.delete(fq_file_endpoint, auth=self.auth)

        if not res.status_code in [200, 204]:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"delete_fq_file failed: {detail}")        


    def get_fq_file_upload_path(self, fq_file_id: int) -> str:
        """Get FASTQ file upload path

        Get upload path for FASTQ file by fq_file ID

        Args:
            fq_file_id: ID (pk) of FASTQ file

        Raises:
            rsexceptions.ReadStoreError: If upload_path is not found

        Returns:
            str: Upload path
        """

        fq_file = self.get_fq_file(fq_file_id)

        if "upload_path" not in fq_file:
            raise rsexceptions.ReadStoreError("upload_path Not Found in FqFile entry")

        upload_path = fq_file.get("upload_path")

        return upload_path

    def list_fastq_datasets(
        self,
        project_name: str | None = None,
        project_id: int | None = None,
        role: str | None = None,
    ) -> List[dict]:
        """
        List FASTQ Datasets

        List FASTQ datasets and filter by project_name, project_id or role.
        Role can be owner, collaborator or creator.

        Args:
            project_name: Filter fq_datasets by project name
            project_id: Filter fq_datasets by project ID
            role: Filter fq_datasets by owner role (owner, collaborator, creator)

        Raises:
            rsexceptions.ReadStoreError if role is not valid
            rsexceptions.ReadStoreError request failed

        Returns:
            List[Dict]: FASTQ datasets in JSON format
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

        # Define json for post request
        json = {}

        if role:
            if role.lower() in ["owner", "collaborator", "creator"]:
                json["role"] = role
            else:
                raise rsexceptions.ReadStoreError("Invalid Role")

        if project_name:
            json["project_name"] = project_name
        if project_id:
            json["project_id"] = project_id

        res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("list_fastq_datasets Failed")
        else:
            return res.json()

    def get_fastq_dataset(
        self,
        dataset_id: int | None = None,
        dataset_name: str | None = None
    ) -> Dict:
        """Get FASTQ dataset

        Get FASTQ dataset by provided dataset_id or dataset_name
        If dataset_name is not unique an error is printed

        Args:
            dataset_id: fq_dataset ID (or pk) to select
            dataset_name: fq_dataset Name to select

        Raises:
            rsexceptions.ReadStoreError: If backend request failed
            rsexceptions.ReadStoreError:
                If multiple datasets found with same name.
                This can occur if datasets with identical name were shared with you.

        Returns:
            Dict: Json Detail response
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

        if dataset_id is None and dataset_name is None: 
            raise rsexceptions.ReadStoreError("Dataset ID or Name Required")

        # Define json for post request
        json = {}
        if dataset_id:
            json["id"] = dataset_id
        if dataset_name:
            json["name"] = dataset_name

        res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

        # Remove entries not requested
        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("get_fastq_dataset Failed")
        else:
            # If no dataset found, return empty dict
            if len(res.json()) == 0:
                return {}
            # If several datasets found, return error
            elif len(res.json()) > 1:
                raise rsexceptions.ReadStoreError(
                    """Multiple Datasets Found.\n
                    This can happen if datasets with identical name were
                    shared with you.\nUse dataset_id to get the correct dataset."""
                )
            else:
                return res.json()[0]

    def create_fastq_dataset(self,
                            name: str,
                            description: str,
                            qc_passed: bool,
                            paired_end: bool,
                            index_read: bool,
                            project_ids: List[int],
                            project_names: List[str],
                            metadata: dict,
                            fq_file_r1_id: int | None,
                            fq_file_r2_id: int | None,
                            fq_file_i1_id: int | None,
                            fq_file_i2_id: int | None) -> dict:

        """Create Fastq Dataset 

        Create Fastq dataset in ReadStore

        Args:
            name: Dataset name
            description: Dataset description
            qc_passed: QC Pass
            paired_end: Paired End
            index_read: Index Read
            project_ids: List of project IDs
            project_names: List of project names
            metadata: Metadata
            fq_file_r1_id: Fastq file R1 ID
            fq_file_r2_id: Fastq file R2 ID
            fq_file_i1_id: Fastq file I1 ID
            fq_file_i2_id: Fastq file I2 ID

        Returns:
            dict: Created Fastq dataset

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

        # Define json for post request
        json = {
            "name": name,
            "description": description,
            "qc_passed": qc_passed,
            "paired_end": paired_end,
            "index_read": index_read,
            "project_ids": project_ids,
            "project_names": project_names,
            "metadata": metadata,
            "fq_file_r1": fq_file_r1_id,
            "fq_file_r2": fq_file_r2_id,
            "fq_file_i1": fq_file_i1_id,
            "fq_file_i2": fq_file_i2_id
        }

        res = requests.post(fq_dataset_endpoint, json=json, auth=self.auth)

        if res.status_code != 201:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"create_fastq_dataset failed: {detail}")
        else:
            return res.json()

    def update_fastq_dataset(self,
                             dataset_id: int,
                             name: str,
                             description: str,
                             qc_passed: bool,
                             paired_end: bool,
                             index_read: bool,
                             project_ids: List[int],
                             project_names: List[str],
                             metadata: dict,
                             fq_file_r1_id: int | None,
                             fq_file_r2_id: int | None,
                             fq_file_i1_id: int | None,
                             fq_file_i2_id: int | None) -> dict:
        """Update Fastq Dataset

        Update Fastq dataset in ReadStore

        Args:
            dataset_id: ID of the dataset to update
            name: Dataset name
            description: Dataset description
            qc_passed: QC Pass
            paired_end: Paired End
            index_read: Index Read
            project_ids: List of project IDs
            project_names: List of project names
            metadata: Metadata
            fq_file_r1_id: Fastq file R1 ID
            fq_file_r2_id: Fastq file R2 ID
            fq_file_i1_id: Fastq file I1 ID
            fq_file_i2_id: Fastq file I2 ID

        Returns:
            dict: Updated Fastq dataset

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT, f'{dataset_id}/')

        # Define json for put request
        json = {
            "name": name,
            "description": description,
            "qc_passed": qc_passed,
            "paired_end": paired_end,
            "index_read": index_read,
            "project_ids": project_ids,
            "project_names": project_names,
            "metadata": metadata,
            "fq_file_r1": fq_file_r1_id,
            "fq_file_r2": fq_file_r2_id,
            "fq_file_i1": fq_file_i1_id,
            "fq_file_i2": fq_file_i2_id
        }

        res = requests.put(fq_dataset_endpoint, json=json, auth=self.auth)

        if res.status_code != 200:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"update_fastq_dataset failed: {detail}")
        else:
            return res.json()

    def delete_fastq_dataset(self, dataset_id: int):
        """Delete Fastq Dataset

        Delete Fastq dataset in ReadStore

        Args:
            dataset_id: ID of Fastq dataset

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT, f'{dataset_id}/')

        res = requests.delete(fq_dataset_endpoint, auth=self.auth)

        if not res.status_code in [200,204]:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"delete_fastq_dataset failed: {detail}")


    def list_projects(self, role: str | None = None) -> List[Dict]:
        """List Projects

        List projects and optionally filter by role

        Args:
            role: Owner role to filter (owner, collaborator, creator)

        Raises:
            rsexceptions.ReadStoreError: If role is not valid
            rsexceptions.ReadStoreError: If request failed

        Returns:
            List[Dict]: List of projects
        """

        project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

        # Define json for post request
        json = {}
        if role:
            if role.lower() in ["owner", "collaborator", "creator"]:
                json["role"] = role
            else:
                raise rsexceptions.ReadStoreError("Invalid Role")

        res = requests.get(project_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("list_projects Failed")
        else:
            return res.json()


    def get_project(
        self,
        project_id: int | None = None,
        project_name: str | None = None
    ) -> Dict:
        """Get Individual Project

        Return project details by project_id or project_name
        If name is duplicated, print error message

        Args:
            project_id: Project ID
            project_name: Project Name

        Raise
            rsexceptions.ReadStoreError: If request failed
            rsexceptions.ReadStoreError: If duplicate names are found

        Returns:
            project detail response
        """

        assert project_id or project_name, "project_id or project_name Required"

        project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

        # Define json for post request
        json = {"username": self.username, "token": self.token}

        if project_id:
            json["id"] = project_id
        if project_name:
            json["name"] = project_name

        res = requests.get(project_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("get_project Failed")
        else:
            if len(res.json()) == 0:
                return {}
            # If several datasets found, return error
            elif len(res.json()) > 1:
                raise rsexceptions.ReadStoreError(
                    """Multiple Projects Found.\n
                This can happen if Projects with identical name were shared with you.\n
                Use unique Project ID to access the correct dataset."""
                )
            else:
                return res.json()[0]

    def create_project(self,
                       name: str,
                       description: str,
                       metadata: dict,
                       dataset_metadata_keys: List[str]) -> dict:
        """Create Project

        Create a new project in ReadStore

        Args:
            name: Project name
            description: Project description
            metadata: Project metadata
            dataset_metadata_keys: Dataset metadata keys

        Returns:
            dict: Created project data

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """
        project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

        dataset_metadata_keys = {key: "" for key in dataset_metadata_keys}

        json = {
            "name": name,
            "description": description,
            "metadata": metadata,
            "dataset_metadata_keys": dataset_metadata_keys
        }

        res = requests.post(project_endpoint, json=json, auth=self.auth)

        if res.status_code != 201:
            try:
                detail = res.json()
            except: 
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"create_project failed: {detail}")
        else:
            return res.json()


    def update_project(self,
                       project_id: int,
                       name: str,
                       description: str,
                       metadata: dict,
                       dataset_metadata_keys: List[str]) -> dict:        
        """Update Project

        Update an existing project in ReadStore

        Args:
            project_id: ID of the project to update
            name: Project name
            description: Project description
            metadata: Project metadata
            dataset_metadata_keys: Dataset metadata keys

        Returns:
            dict: Updated project data

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """
        project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT, f'{project_id}/')

        dataset_metadata_keys = {key: "" for key in dataset_metadata_keys}

        json = {
            "name": name,
            "description": description,
            "metadata": metadata,
            "dataset_metadata_keys": dataset_metadata_keys
        }

        res = requests.put(project_endpoint, json=json, auth=self.auth)

        if res.status_code != 200:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"update_project failed: {detail}")
        else:
            return res.json()


    def delete_project(self, project_id: int):
        """Delete Project

        Delete a project in ReadStore

        Args:
            project_id: ID of the project to delete

        Raises:
            rsexceptions.ReadStoreError: If request failed
        """

        project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT, f'{project_id}/')

        res = requests.delete(project_endpoint, auth=self.auth)

        if not res.status_code in [200,204]:
            try:
                detail = res.json()
            except:
                detail = "No Message"

            raise rsexceptions.ReadStoreError(f"delete_project failed: {detail}")


    def download_project_attachment(
        self,
        attachment_name: str,
        outpath: str,
        project_id: int | None = None,
        project_name: str | None = None,
    ):
        """Download Project Attachments

        Download Project Attachment Files to local path

        Args:
            attachment_name: Attachment name
            outpath: Path to write to
            project_id: Id of project
            project_name: Project name.

        Raises:
            rsexceptions.ReadStoreError: Request failed
            rsexceptions.ReadStoreError: Attachment not Found
            rsexceptions.ReadStoreError: Multiple Attachments Found for Project.
        """

        project_attachment_endpoint = os.path.join(
            self.endpoint, self.PROJECT_ATTACHMENT_ENDPOINT
        )

        assert project_id or project_name, \
            "Either project_id or project_name required"

        # Define json for post request
        json = {
            "attachment_name": attachment_name
        }

        if project_id:
            json["project_id"] = project_id
        if project_name:
            json["project_name"] = project_name

        res = requests.get(project_attachment_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("download_project_attachment failed")
        elif len(res.json()) == 0:
            raise rsexceptions.ReadStoreError("Attachment Not Found")
        elif len(res.json()) > 1:
            raise rsexceptions.ReadStoreError(
                """Multiple Attachments Found For Project.
                This can happen if Projects with identical name were shared with you.\n
                Use unique Project ID to access the correct attachment."""
            )
        else:
            attachment = res.json()[0]
            with open(outpath, "wb") as fh:
                fh.write(base64.b64decode(attachment["body"]))


    def download_fq_dataset_attachment(
        self,
        attachment_name: str,
        outpath: str,
        dataset_id: int | None = None,
        dataset_name: str | None = None,
    ):
        """Fastq Attachments

        Download Fastq Attachments

        Args:
            attachment_name: Attachment name
            outpath: Path to write to
            dataset_id: Id of project
            dataset_name: Project name.

        Raises:
            rsexceptions.ReadStoreError: Request failed
            rsexceptions.ReadStoreError: Attachment not Found
            rsexceptions.ReadStoreError: Multiple Attachments Found for Project.
        """

        fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_ATTACHMENT_ENDPOINT)

        assert dataset_id or dataset_name, "dataset_id or dataset_name required"

        # Define json for post request
        json = {
            "attachment_name": attachment_name,
        }

        if dataset_id:
            json["dataset_id"] = dataset_id
        if dataset_name:
            json["dataset_name"] = dataset_name

        res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("download_fq_dataset_attachment failed")
        elif len(res.json()) == 0:
            raise rsexceptions.ReadStoreError("Attachment Not Found")
        elif len(res.json()) > 1:
            raise rsexceptions.ReadStoreError(
                """Multiple Attachments Found For Dataset.
                This can happen if Datasets with identical name were shared with you.\n
                Use unique Dataset ID to access the correct attachment."""
            )
        else:
            attachment = res.json()[0]
            with open(outpath, "wb") as fh:
                fh.write(base64.b64decode(attachment["body"]))

    def upload_pro_data(self,
                        name: str,
                        pro_data_path: str,
                        data_type: str,
                        dataset_id: int | None = None,
                        dataset_name: str | None = None,
                        metadata: dict = {},
                        description: str = "") -> None:
        """Upload Processed Data

        Upload Pro Data to ReadStore

        Args:
            pro_data: Pro Data in JSON format

        Raises:
            rsexceptions.ReadStoreError: If upload request failed
        """

        pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

        # Run parallel uploads of fastq files
        pro_data_path = os.path.abspath(pro_data_path)

        # Make sure file exists and
        if not os.path.exists(pro_data_path):
            raise rsexceptions.ReadStoreError(f"File Not Found: {pro_data_path}")
        elif not os.access(pro_data_path, os.R_OK):
            raise rsexceptions.ReadStoreError(f"No read permissions: {pro_data_path}")

        # Define json for post request
        json = {
            "name" : name,
            "data_type": data_type,
            "upload_path": pro_data_path,
            "metadata": metadata,
            "description" : description,
        }

        if dataset_id:
            json['dataset_id'] = dataset_id
        if dataset_name:
            json['dataset_name'] = dataset_name        

        res = requests.post(pro_data_endpoint, json=json, auth=self.auth)

        if res.status_code == 403:
            raise rsexceptions.ReadStoreError(f"Upload ProData Failed: {res.json().get('detail')}")
        elif res.status_code not in [201, 204]:
            raise rsexceptions.ReadStoreError("upload_pro_data failed")


    def list_pro_data(self,
                      project_id: int | None = None,
                      project_name: str | None = None,
                      dataset_id: int | None = None,
                      dataset_name: str | None = None,
                      name: str | None = None,
                      data_type: str | None = None,
                      include_archived: bool = False) -> List[Dict]:
        """List Processed Data

        List Pro Data for Dataset

        Args:
            dataset_id: Dataset ID

        Raises:
            rsexceptions.ReadStoreError: If request failed

        Returns:
            List[Dict]: List of Pro Data
        """

        pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

        # Define json for post request
        json = {
            'project_id': project_id,
            'project_name': project_name,
            'dataset_id': dataset_id,
            'dataset_name': dataset_name,
            'name': name,
            'data_type': data_type
        }

        if not include_archived:
            json['valid'] = True

        res = requests.get(pro_data_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("list_pro_data failed")
        else:
            return res.json()


    def get_pro_data(self,
                    pro_data_id: int | None = None,
                    name: str | None = None,
                    version: int | None = None,
                    dataset_id: int | None = None,
                    dataset_name: str | None = None) -> List[Dict]:   

        """List Processed Data

        List Pro Data for Dataset

        Args:
            dataset_id: Dataset ID

        Raises:
            rsexceptions.ReadStoreError: If request failed

        Returns:
            List[Dict]: List of Pro Data
        """

        if not pro_data_id:
            assert name and (dataset_id or dataset_name), "name and dataset_id or dataset_name required"

        pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

        if not version:
            valid = 'true'
        else:
            valid = 'false'


        # Define json for post request
        json = {
            'dataset_id': dataset_id,
            'dataset_name': dataset_name,
            'name': name,
            'version': version,
            'valid': valid,
            'detail': 'true'
        }

        if pro_data_id:
            res = requests.get(pro_data_endpoint + f'{pro_data_id}/', auth=self.auth)
        else:
            res = requests.get(pro_data_endpoint, params=json, auth=self.auth)

        if res.status_code not in [200, 204]:
            raise rsexceptions.ReadStoreError("list_pro_data failed")
        else:
            if len(res.json()) == 0:
                return {}
            # If several datasets found, return error
            elif len(res.json()) > 1:
                raise rsexceptions.ReadStoreError(
                    """Multiple Projects Found.\n
                This can happen if Projects with identical name were shared with you.\n
                Use unique Project ID to access the correct dataset."""
                )
            else:
                return res.json()[0]

    def delete_pro_data(self,
                        pro_data_id: int | None = None,
                        name: str | None = None,
                        dataset_id: int | None = None,
                        dataset_name: str | None = None,
                        version: int | None = None) -> List[Dict]:   

        """Delete Processed Data

        Delete Pro Data for Dataset

        Args:
            dataset_id: Dataset ID

        Raises:
            rsexceptions.ReadStoreError: If request failed

        Returns:
            List[Dict]: List of Pro Data
        """

        if not pro_data_id:
            assert name and (dataset_id or dataset_name), "name and dataset_id or dataset_name required"

        pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

        # Define json for post request
        json = {
            'dataset_id': dataset_id,
            'dataset_name': dataset_name,
            'name': name,
            'version': version,
        }

        if pro_data_id:
            res = requests.delete(pro_data_endpoint + f'{pro_data_id}/', auth=self.auth)
        else:
            res = requests.delete(pro_data_endpoint, params=json, auth=self.auth)

        if res.status_code == 400:
            detail = res.json().get('detail', 'No Message')
            if detail == 'ProData not found':
                raise rsexceptions.ReadStoreError("ProData not found")
            else:
                raise rsexceptions.ReadStoreError("delete_pro_data failed")
        elif res.status_code == 403:
            raise rsexceptions.ReadStoreError(f"ProData Delete Failed: {res.json().get('detail')}")
        elif res.status_code in [200, 204]:
            return res.json().get('id')
        else:
            raise rsexceptions.ReadStoreError("delete_pro_data failed")

__init__(username, token, endpoint_url, output_format)

Constructor

Initialize a new RSClient object

Parameters:

Name Type Description Default
username str

ReadStore username

required
token str

ReadStore user token

required
endpoint_url str

The endpoint URL for the ReadStore API

required
output_format str

The default output format for the client

required

Raises:

Type Description
ReadStoreError

Server Connection to API Failed

ReadStoreError

User Authentication Failed

Source code in readstore_cli/rsclient.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __init__(
    self, username: str, token: str, endpoint_url: str, output_format: str
):
    """Constructor

    Initialize a new RSClient object

    Args:
        username: ReadStore username
        token: ReadStore user token
        endpoint_url: The endpoint URL for the ReadStore API
        output_format: The default output format for the client

    Raises:
        rsexceptions.ReadStoreError:
            Server Connection to API Failed
        rsexceptions.ReadStoreError:
            User Authentication Failed
    """

    self.username = username
    self.token = token
    self.endpoint = f"{endpoint_url}/{self.REST_API_VERSION}"
    self.output_format = output_format
    self.auth = HTTPBasicAuth(username, token)

    if not self._test_server_connection():
        raise rsexceptions.ReadStoreError(
            f"Server Connection Failed\nEndpoint URL: {self.endpoint}"
        )

    if not self._auth_user_token():
        raise rsexceptions.ReadStoreError(
            f"User Authentication Failed\nUsername: {self.username}"
        )

_auth_user_token()

Validate user and token

Returns:

Type Description
bool

True if user token is valid else False

Source code in readstore_cli/rsclient.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def _auth_user_token(self) -> bool:
    """
    Validate user and token

    Returns:
        True if user token is valid else False
    """

    try:
        auth_endpoint = os.path.join(self.endpoint, self.USER_AUTH_TOKEN_ENDPOINT)

        res = requests.post(auth_endpoint, auth=self.auth)

        if res.status_code != 200:
            return False
        else:
            return True

    except requests.exceptions.ConnectionError:
        return False

_test_server_connection()

Validate server URL

Returns:

Type Description
bool

True if server can be reached else False

Source code in readstore_cli/rsclient.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def _test_server_connection(self) -> bool:
    """
    Validate server URL

    Returns:
        True if server can be reached else False
    """

    parsed_url = urlparse(self.endpoint)

    if parsed_url.scheme not in ["http", "https"]:
        return False
    else:
        try:
            response = requests.head(self.endpoint)

            if response.status_code == 200:
                return True
            else:
                return False
        except requests.exceptions.ConnectionError:
            return False

create_fastq_dataset(name, description, qc_passed, paired_end, index_read, project_ids, project_names, metadata, fq_file_r1_id, fq_file_r2_id, fq_file_i1_id, fq_file_i2_id)

Create Fastq Dataset

Create Fastq dataset in ReadStore

Parameters:

Name Type Description Default
name str

Dataset name

required
description str

Dataset description

required
qc_passed bool

QC Pass

required
paired_end bool

Paired End

required
index_read bool

Index Read

required
project_ids List[int]

List of project IDs

required
project_names List[str]

List of project names

required
metadata dict

Metadata

required
fq_file_r1_id int | None

Fastq file R1 ID

required
fq_file_r2_id int | None

Fastq file R2 ID

required
fq_file_i1_id int | None

Fastq file I1 ID

required
fq_file_i2_id int | None

Fastq file I2 ID

required

Returns:

Name Type Description
dict dict

Created Fastq dataset

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
def create_fastq_dataset(self,
                        name: str,
                        description: str,
                        qc_passed: bool,
                        paired_end: bool,
                        index_read: bool,
                        project_ids: List[int],
                        project_names: List[str],
                        metadata: dict,
                        fq_file_r1_id: int | None,
                        fq_file_r2_id: int | None,
                        fq_file_i1_id: int | None,
                        fq_file_i2_id: int | None) -> dict:

    """Create Fastq Dataset 

    Create Fastq dataset in ReadStore

    Args:
        name: Dataset name
        description: Dataset description
        qc_passed: QC Pass
        paired_end: Paired End
        index_read: Index Read
        project_ids: List of project IDs
        project_names: List of project names
        metadata: Metadata
        fq_file_r1_id: Fastq file R1 ID
        fq_file_r2_id: Fastq file R2 ID
        fq_file_i1_id: Fastq file I1 ID
        fq_file_i2_id: Fastq file I2 ID

    Returns:
        dict: Created Fastq dataset

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

    # Define json for post request
    json = {
        "name": name,
        "description": description,
        "qc_passed": qc_passed,
        "paired_end": paired_end,
        "index_read": index_read,
        "project_ids": project_ids,
        "project_names": project_names,
        "metadata": metadata,
        "fq_file_r1": fq_file_r1_id,
        "fq_file_r2": fq_file_r2_id,
        "fq_file_i1": fq_file_i1_id,
        "fq_file_i2": fq_file_i2_id
    }

    res = requests.post(fq_dataset_endpoint, json=json, auth=self.auth)

    if res.status_code != 201:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"create_fastq_dataset failed: {detail}")
    else:
        return res.json()

create_fq_file(name, read_type, qc_passed, read_length, num_reads, size_mb, qc_phred_mean, qc_phred, upload_path, md5_checksum, staging, pipeline_version)

Create Fastq File

Create Fastq file in ReadStore

Parameters:

Name Type Description Default
name str

Fastq file name

required
read_type str

Read type (R1, R2, I1, I2)

required
qc_passed bool

QC Pass

required
read_length int

Read length

required
num_reads int

Number of reads

required
size_mb int

Size in MB

required
qc_phred_mean float

QC Phred Mean

required
qc_phred dict

QC Phred

required
upload_path str

Upload Path

required
md5_checksum str

MD5 Checksum

required
staging bool

Staging

required
pipeline_version str

Pipeline Version

required

Returns:

Name Type Description
dict dict

Fastq file data

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def create_fq_file(self,
                   name: str,
                   read_type: str,
                   qc_passed: bool,
                   read_length: int,
                   num_reads: int,
                   size_mb: int,
                   qc_phred_mean: float,
                   qc_phred: dict,
                   upload_path: str,
                   md5_checksum: str,
                   staging: bool,
                   pipeline_version: str) -> dict:

    """Create Fastq File

    Create Fastq file in ReadStore

    Args:
        name: Fastq file name
        read_type: Read type (R1, R2, I1, I2)
        qc_passed: QC Pass
        read_length: Read length
        num_reads: Number of reads
        size_mb: Size in MB
        qc_phred_mean: QC Phred Mean
        qc_phred: QC Phred
        upload_path: Upload Path
        md5_checksum: MD5 Checksum
        staging: Staging
        pipeline_version: Pipeline Version

    Returns:    
        dict: Fastq file data

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)

    # Define json for post request
    json = {
        "name": name,
        "read_type": read_type,
        "qc_passed": qc_passed,
        "read_length": read_length,
        "num_reads": num_reads,
        "size_mb": size_mb,
        "qc_phred_mean": qc_phred_mean,
        "qc_phred": qc_phred,
        "upload_path": upload_path,
        "md5_checksum": md5_checksum,
        "staging": staging,
        "pipeline_version": pipeline_version
    }

    res = requests.post(fq_file_endpoint, json=json, auth=self.auth)

    if res.status_code != 201:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"create_fq_file failed: {detail}")
    else:
        return res.json()

create_project(name, description, metadata, dataset_metadata_keys)

Create Project

Create a new project in ReadStore

Parameters:

Name Type Description Default
name str

Project name

required
description str

Project description

required
metadata dict

Project metadata

required
dataset_metadata_keys List[str]

Dataset metadata keys

required

Returns:

Name Type Description
dict dict

Created project data

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
def create_project(self,
                   name: str,
                   description: str,
                   metadata: dict,
                   dataset_metadata_keys: List[str]) -> dict:
    """Create Project

    Create a new project in ReadStore

    Args:
        name: Project name
        description: Project description
        metadata: Project metadata
        dataset_metadata_keys: Dataset metadata keys

    Returns:
        dict: Created project data

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """
    project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

    dataset_metadata_keys = {key: "" for key in dataset_metadata_keys}

    json = {
        "name": name,
        "description": description,
        "metadata": metadata,
        "dataset_metadata_keys": dataset_metadata_keys
    }

    res = requests.post(project_endpoint, json=json, auth=self.auth)

    if res.status_code != 201:
        try:
            detail = res.json()
        except: 
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"create_project failed: {detail}")
    else:
        return res.json()

delete_fastq_dataset(dataset_id)

Delete Fastq Dataset

Delete Fastq dataset in ReadStore

Parameters:

Name Type Description Default
dataset_id int

ID of Fastq dataset

required

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def delete_fastq_dataset(self, dataset_id: int):
    """Delete Fastq Dataset

    Delete Fastq dataset in ReadStore

    Args:
        dataset_id: ID of Fastq dataset

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT, f'{dataset_id}/')

    res = requests.delete(fq_dataset_endpoint, auth=self.auth)

    if not res.status_code in [200,204]:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"delete_fastq_dataset failed: {detail}")

delete_fq_file(fq_file_id)

Delete Fastq File

Delete Fastq file in ReadStore

Parameters:

Name Type Description Default
fq_file_id int

ID of Fastq file

required

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def delete_fq_file(self, fq_file_id: int):
    """Delete Fastq File

    Delete Fastq file in ReadStore

    Args:
        fq_file_id: ID of Fastq file

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT, f'{fq_file_id}/')

    res = requests.delete(fq_file_endpoint, auth=self.auth)

    if not res.status_code in [200, 204]:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"delete_fq_file failed: {detail}")        

delete_pro_data(pro_data_id=None, name=None, dataset_id=None, dataset_name=None, version=None)

Delete Processed Data

Delete Pro Data for Dataset

Parameters:

Name Type Description Default
dataset_id int | None

Dataset ID

None

Raises:

Type Description
ReadStoreError

If request failed

Returns:

Type Description
List[Dict]

List[Dict]: List of Pro Data

Source code in readstore_cli/rsclient.py
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
def delete_pro_data(self,
                    pro_data_id: int | None = None,
                    name: str | None = None,
                    dataset_id: int | None = None,
                    dataset_name: str | None = None,
                    version: int | None = None) -> List[Dict]:   

    """Delete Processed Data

    Delete Pro Data for Dataset

    Args:
        dataset_id: Dataset ID

    Raises:
        rsexceptions.ReadStoreError: If request failed

    Returns:
        List[Dict]: List of Pro Data
    """

    if not pro_data_id:
        assert name and (dataset_id or dataset_name), "name and dataset_id or dataset_name required"

    pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

    # Define json for post request
    json = {
        'dataset_id': dataset_id,
        'dataset_name': dataset_name,
        'name': name,
        'version': version,
    }

    if pro_data_id:
        res = requests.delete(pro_data_endpoint + f'{pro_data_id}/', auth=self.auth)
    else:
        res = requests.delete(pro_data_endpoint, params=json, auth=self.auth)

    if res.status_code == 400:
        detail = res.json().get('detail', 'No Message')
        if detail == 'ProData not found':
            raise rsexceptions.ReadStoreError("ProData not found")
        else:
            raise rsexceptions.ReadStoreError("delete_pro_data failed")
    elif res.status_code == 403:
        raise rsexceptions.ReadStoreError(f"ProData Delete Failed: {res.json().get('detail')}")
    elif res.status_code in [200, 204]:
        return res.json().get('id')
    else:
        raise rsexceptions.ReadStoreError("delete_pro_data failed")

delete_project(project_id)

Delete Project

Delete a project in ReadStore

Parameters:

Name Type Description Default
project_id int

ID of the project to delete

required

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
def delete_project(self, project_id: int):
    """Delete Project

    Delete a project in ReadStore

    Args:
        project_id: ID of the project to delete

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT, f'{project_id}/')

    res = requests.delete(project_endpoint, auth=self.auth)

    if not res.status_code in [200,204]:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"delete_project failed: {detail}")

download_fq_dataset_attachment(attachment_name, outpath, dataset_id=None, dataset_name=None)

Fastq Attachments

Download Fastq Attachments

Parameters:

Name Type Description Default
attachment_name str

Attachment name

required
outpath str

Path to write to

required
dataset_id int | None

Id of project

None
dataset_name str | None

Project name.

None

Raises:

Type Description
ReadStoreError

Request failed

ReadStoreError

Attachment not Found

ReadStoreError

Multiple Attachments Found for Project.

Source code in readstore_cli/rsclient.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
def download_fq_dataset_attachment(
    self,
    attachment_name: str,
    outpath: str,
    dataset_id: int | None = None,
    dataset_name: str | None = None,
):
    """Fastq Attachments

    Download Fastq Attachments

    Args:
        attachment_name: Attachment name
        outpath: Path to write to
        dataset_id: Id of project
        dataset_name: Project name.

    Raises:
        rsexceptions.ReadStoreError: Request failed
        rsexceptions.ReadStoreError: Attachment not Found
        rsexceptions.ReadStoreError: Multiple Attachments Found for Project.
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_ATTACHMENT_ENDPOINT)

    assert dataset_id or dataset_name, "dataset_id or dataset_name required"

    # Define json for post request
    json = {
        "attachment_name": attachment_name,
    }

    if dataset_id:
        json["dataset_id"] = dataset_id
    if dataset_name:
        json["dataset_name"] = dataset_name

    res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("download_fq_dataset_attachment failed")
    elif len(res.json()) == 0:
        raise rsexceptions.ReadStoreError("Attachment Not Found")
    elif len(res.json()) > 1:
        raise rsexceptions.ReadStoreError(
            """Multiple Attachments Found For Dataset.
            This can happen if Datasets with identical name were shared with you.\n
            Use unique Dataset ID to access the correct attachment."""
        )
    else:
        attachment = res.json()[0]
        with open(outpath, "wb") as fh:
            fh.write(base64.b64decode(attachment["body"]))

download_project_attachment(attachment_name, outpath, project_id=None, project_name=None)

Download Project Attachments

Download Project Attachment Files to local path

Parameters:

Name Type Description Default
attachment_name str

Attachment name

required
outpath str

Path to write to

required
project_id int | None

Id of project

None
project_name str | None

Project name.

None

Raises:

Type Description
ReadStoreError

Request failed

ReadStoreError

Attachment not Found

ReadStoreError

Multiple Attachments Found for Project.

Source code in readstore_cli/rsclient.py
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def download_project_attachment(
    self,
    attachment_name: str,
    outpath: str,
    project_id: int | None = None,
    project_name: str | None = None,
):
    """Download Project Attachments

    Download Project Attachment Files to local path

    Args:
        attachment_name: Attachment name
        outpath: Path to write to
        project_id: Id of project
        project_name: Project name.

    Raises:
        rsexceptions.ReadStoreError: Request failed
        rsexceptions.ReadStoreError: Attachment not Found
        rsexceptions.ReadStoreError: Multiple Attachments Found for Project.
    """

    project_attachment_endpoint = os.path.join(
        self.endpoint, self.PROJECT_ATTACHMENT_ENDPOINT
    )

    assert project_id or project_name, \
        "Either project_id or project_name required"

    # Define json for post request
    json = {
        "attachment_name": attachment_name
    }

    if project_id:
        json["project_id"] = project_id
    if project_name:
        json["project_name"] = project_name

    res = requests.get(project_attachment_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("download_project_attachment failed")
    elif len(res.json()) == 0:
        raise rsexceptions.ReadStoreError("Attachment Not Found")
    elif len(res.json()) > 1:
        raise rsexceptions.ReadStoreError(
            """Multiple Attachments Found For Project.
            This can happen if Projects with identical name were shared with you.\n
            Use unique Project ID to access the correct attachment."""
        )
    else:
        attachment = res.json()[0]
        with open(outpath, "wb") as fh:
            fh.write(base64.b64decode(attachment["body"]))

get_fastq_dataset(dataset_id=None, dataset_name=None)

Get FASTQ dataset

Get FASTQ dataset by provided dataset_id or dataset_name If dataset_name is not unique an error is printed

Parameters:

Name Type Description Default
dataset_id int | None

fq_dataset ID (or pk) to select

None
dataset_name str | None

fq_dataset Name to select

None

Raises:

Type Description
ReadStoreError

If backend request failed

ReadStoreError

If multiple datasets found with same name. This can occur if datasets with identical name were shared with you.

Returns:

Name Type Description
Dict Dict

Json Detail response

Source code in readstore_cli/rsclient.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
def get_fastq_dataset(
    self,
    dataset_id: int | None = None,
    dataset_name: str | None = None
) -> Dict:
    """Get FASTQ dataset

    Get FASTQ dataset by provided dataset_id or dataset_name
    If dataset_name is not unique an error is printed

    Args:
        dataset_id: fq_dataset ID (or pk) to select
        dataset_name: fq_dataset Name to select

    Raises:
        rsexceptions.ReadStoreError: If backend request failed
        rsexceptions.ReadStoreError:
            If multiple datasets found with same name.
            This can occur if datasets with identical name were shared with you.

    Returns:
        Dict: Json Detail response
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

    if dataset_id is None and dataset_name is None: 
        raise rsexceptions.ReadStoreError("Dataset ID or Name Required")

    # Define json for post request
    json = {}
    if dataset_id:
        json["id"] = dataset_id
    if dataset_name:
        json["name"] = dataset_name

    res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

    # Remove entries not requested
    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("get_fastq_dataset Failed")
    else:
        # If no dataset found, return empty dict
        if len(res.json()) == 0:
            return {}
        # If several datasets found, return error
        elif len(res.json()) > 1:
            raise rsexceptions.ReadStoreError(
                """Multiple Datasets Found.\n
                This can happen if datasets with identical name were
                shared with you.\nUse dataset_id to get the correct dataset."""
            )
        else:
            return res.json()[0]

get_fq_file(fq_file_id)

Get Fastq File

Return Fastq file data by fq_file ID

Parameters:

Name Type Description Default
fq_file_id int

ID (pk) of fq_file

required

Returns:

Type Description
Dict

dict with fq file data

Source code in readstore_cli/rsclient.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def get_fq_file(self, fq_file_id: int) -> Dict:
    """Get Fastq File

    Return Fastq file data by fq_file ID

    Args:
        fq_file_id: ID (pk) of fq_file

    Returns:
        dict with fq file data
    """

    fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)


    res = requests.get(fq_file_endpoint + f'{fq_file_id}/',auth=self.auth)

    if res.status_code not in [200, 204]:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"get_fq_file failed: {detail}")
    else:
        return res.json()[0]

get_fq_file_upload_path(fq_file_id)

Get FASTQ file upload path

Get upload path for FASTQ file by fq_file ID

Parameters:

Name Type Description Default
fq_file_id int

ID (pk) of FASTQ file

required

Raises:

Type Description
ReadStoreError

If upload_path is not found

Returns:

Name Type Description
str str

Upload path

Source code in readstore_cli/rsclient.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def get_fq_file_upload_path(self, fq_file_id: int) -> str:
    """Get FASTQ file upload path

    Get upload path for FASTQ file by fq_file ID

    Args:
        fq_file_id: ID (pk) of FASTQ file

    Raises:
        rsexceptions.ReadStoreError: If upload_path is not found

    Returns:
        str: Upload path
    """

    fq_file = self.get_fq_file(fq_file_id)

    if "upload_path" not in fq_file:
        raise rsexceptions.ReadStoreError("upload_path Not Found in FqFile entry")

    upload_path = fq_file.get("upload_path")

    return upload_path

get_output_format()

Get Output Format set for client

Return

str output format

Source code in readstore_cli/rsclient.py
188
189
190
191
192
193
194
195
196
def get_output_format(self) -> str:
    """
    Get Output Format set for client

    Return:
        str output format
    """

    return self.output_format

get_pro_data(pro_data_id=None, name=None, version=None, dataset_id=None, dataset_name=None)

List Processed Data

List Pro Data for Dataset

Parameters:

Name Type Description Default
dataset_id int | None

Dataset ID

None

Raises:

Type Description
ReadStoreError

If request failed

Returns:

Type Description
List[Dict]

List[Dict]: List of Pro Data

Source code in readstore_cli/rsclient.py
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
def get_pro_data(self,
                pro_data_id: int | None = None,
                name: str | None = None,
                version: int | None = None,
                dataset_id: int | None = None,
                dataset_name: str | None = None) -> List[Dict]:   

    """List Processed Data

    List Pro Data for Dataset

    Args:
        dataset_id: Dataset ID

    Raises:
        rsexceptions.ReadStoreError: If request failed

    Returns:
        List[Dict]: List of Pro Data
    """

    if not pro_data_id:
        assert name and (dataset_id or dataset_name), "name and dataset_id or dataset_name required"

    pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

    if not version:
        valid = 'true'
    else:
        valid = 'false'


    # Define json for post request
    json = {
        'dataset_id': dataset_id,
        'dataset_name': dataset_name,
        'name': name,
        'version': version,
        'valid': valid,
        'detail': 'true'
    }

    if pro_data_id:
        res = requests.get(pro_data_endpoint + f'{pro_data_id}/', auth=self.auth)
    else:
        res = requests.get(pro_data_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("list_pro_data failed")
    else:
        if len(res.json()) == 0:
            return {}
        # If several datasets found, return error
        elif len(res.json()) > 1:
            raise rsexceptions.ReadStoreError(
                """Multiple Projects Found.\n
            This can happen if Projects with identical name were shared with you.\n
            Use unique Project ID to access the correct dataset."""
            )
        else:
            return res.json()[0]

get_project(project_id=None, project_name=None)

Get Individual Project

Return project details by project_id or project_name If name is duplicated, print error message

Parameters:

Name Type Description Default
project_id int | None

Project ID

None
project_name str | None

Project Name

None

Raise rsexceptions.ReadStoreError: If request failed rsexceptions.ReadStoreError: If duplicate names are found

Returns:

Type Description
Dict

project detail response

Source code in readstore_cli/rsclient.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
def get_project(
    self,
    project_id: int | None = None,
    project_name: str | None = None
) -> Dict:
    """Get Individual Project

    Return project details by project_id or project_name
    If name is duplicated, print error message

    Args:
        project_id: Project ID
        project_name: Project Name

    Raise
        rsexceptions.ReadStoreError: If request failed
        rsexceptions.ReadStoreError: If duplicate names are found

    Returns:
        project detail response
    """

    assert project_id or project_name, "project_id or project_name Required"

    project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

    # Define json for post request
    json = {"username": self.username, "token": self.token}

    if project_id:
        json["id"] = project_id
    if project_name:
        json["name"] = project_name

    res = requests.get(project_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("get_project Failed")
    else:
        if len(res.json()) == 0:
            return {}
        # If several datasets found, return error
        elif len(res.json()) > 1:
            raise rsexceptions.ReadStoreError(
                """Multiple Projects Found.\n
            This can happen if Projects with identical name were shared with you.\n
            Use unique Project ID to access the correct dataset."""
            )
        else:
            return res.json()[0]

list_fastq_datasets(project_name=None, project_id=None, role=None)

List FASTQ Datasets

List FASTQ datasets and filter by project_name, project_id or role. Role can be owner, collaborator or creator.

Parameters:

Name Type Description Default
project_name str | None

Filter fq_datasets by project name

None
project_id int | None

Filter fq_datasets by project ID

None
role str | None

Filter fq_datasets by owner role (owner, collaborator, creator)

None

Returns:

Type Description
List[dict]

List[Dict]: FASTQ datasets in JSON format

Source code in readstore_cli/rsclient.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def list_fastq_datasets(
    self,
    project_name: str | None = None,
    project_id: int | None = None,
    role: str | None = None,
) -> List[dict]:
    """
    List FASTQ Datasets

    List FASTQ datasets and filter by project_name, project_id or role.
    Role can be owner, collaborator or creator.

    Args:
        project_name: Filter fq_datasets by project name
        project_id: Filter fq_datasets by project ID
        role: Filter fq_datasets by owner role (owner, collaborator, creator)

    Raises:
        rsexceptions.ReadStoreError if role is not valid
        rsexceptions.ReadStoreError request failed

    Returns:
        List[Dict]: FASTQ datasets in JSON format
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT)

    # Define json for post request
    json = {}

    if role:
        if role.lower() in ["owner", "collaborator", "creator"]:
            json["role"] = role
        else:
            raise rsexceptions.ReadStoreError("Invalid Role")

    if project_name:
        json["project_name"] = project_name
    if project_id:
        json["project_id"] = project_id

    res = requests.get(fq_dataset_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("list_fastq_datasets Failed")
    else:
        return res.json()

list_fq_files()

List Fastq Files

List Fastq files in ReadStore

Returns:

Type Description
List[Dict]

List of Fastq files

Source code in readstore_cli/rsclient.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def list_fq_files(self) -> List[Dict]:
    """List Fastq Files

    List Fastq files in ReadStore

    Returns:
        List of Fastq files
    """

    fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT)

    res = requests.get(fq_file_endpoint, auth=self.auth)

    if res.status_code not in [200, 204]:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"list_fq_files failed: {detail}")
    else:
        return res.json()

list_pro_data(project_id=None, project_name=None, dataset_id=None, dataset_name=None, name=None, data_type=None, include_archived=False)

List Processed Data

List Pro Data for Dataset

Parameters:

Name Type Description Default
dataset_id int | None

Dataset ID

None

Raises:

Type Description
ReadStoreError

If request failed

Returns:

Type Description
List[Dict]

List[Dict]: List of Pro Data

Source code in readstore_cli/rsclient.py
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
def list_pro_data(self,
                  project_id: int | None = None,
                  project_name: str | None = None,
                  dataset_id: int | None = None,
                  dataset_name: str | None = None,
                  name: str | None = None,
                  data_type: str | None = None,
                  include_archived: bool = False) -> List[Dict]:
    """List Processed Data

    List Pro Data for Dataset

    Args:
        dataset_id: Dataset ID

    Raises:
        rsexceptions.ReadStoreError: If request failed

    Returns:
        List[Dict]: List of Pro Data
    """

    pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

    # Define json for post request
    json = {
        'project_id': project_id,
        'project_name': project_name,
        'dataset_id': dataset_id,
        'dataset_name': dataset_name,
        'name': name,
        'data_type': data_type
    }

    if not include_archived:
        json['valid'] = True

    res = requests.get(pro_data_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("list_pro_data failed")
    else:
        return res.json()

list_projects(role=None)

List Projects

List projects and optionally filter by role

Parameters:

Name Type Description Default
role str | None

Owner role to filter (owner, collaborator, creator)

None

Raises:

Type Description
ReadStoreError

If role is not valid

ReadStoreError

If request failed

Returns:

Type Description
List[Dict]

List[Dict]: List of projects

Source code in readstore_cli/rsclient.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def list_projects(self, role: str | None = None) -> List[Dict]:
    """List Projects

    List projects and optionally filter by role

    Args:
        role: Owner role to filter (owner, collaborator, creator)

    Raises:
        rsexceptions.ReadStoreError: If role is not valid
        rsexceptions.ReadStoreError: If request failed

    Returns:
        List[Dict]: List of projects
    """

    project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT)

    # Define json for post request
    json = {}
    if role:
        if role.lower() in ["owner", "collaborator", "creator"]:
            json["role"] = role
        else:
            raise rsexceptions.ReadStoreError("Invalid Role")

    res = requests.get(project_endpoint, params=json, auth=self.auth)

    if res.status_code not in [200, 204]:
        raise rsexceptions.ReadStoreError("list_projects Failed")
    else:
        return res.json()

update_fastq_dataset(dataset_id, name, description, qc_passed, paired_end, index_read, project_ids, project_names, metadata, fq_file_r1_id, fq_file_r2_id, fq_file_i1_id, fq_file_i2_id)

Update Fastq Dataset

Update Fastq dataset in ReadStore

Parameters:

Name Type Description Default
dataset_id int

ID of the dataset to update

required
name str

Dataset name

required
description str

Dataset description

required
qc_passed bool

QC Pass

required
paired_end bool

Paired End

required
index_read bool

Index Read

required
project_ids List[int]

List of project IDs

required
project_names List[str]

List of project names

required
metadata dict

Metadata

required
fq_file_r1_id int | None

Fastq file R1 ID

required
fq_file_r2_id int | None

Fastq file R2 ID

required
fq_file_i1_id int | None

Fastq file I1 ID

required
fq_file_i2_id int | None

Fastq file I2 ID

required

Returns:

Name Type Description
dict dict

Updated Fastq dataset

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def update_fastq_dataset(self,
                         dataset_id: int,
                         name: str,
                         description: str,
                         qc_passed: bool,
                         paired_end: bool,
                         index_read: bool,
                         project_ids: List[int],
                         project_names: List[str],
                         metadata: dict,
                         fq_file_r1_id: int | None,
                         fq_file_r2_id: int | None,
                         fq_file_i1_id: int | None,
                         fq_file_i2_id: int | None) -> dict:
    """Update Fastq Dataset

    Update Fastq dataset in ReadStore

    Args:
        dataset_id: ID of the dataset to update
        name: Dataset name
        description: Dataset description
        qc_passed: QC Pass
        paired_end: Paired End
        index_read: Index Read
        project_ids: List of project IDs
        project_names: List of project names
        metadata: Metadata
        fq_file_r1_id: Fastq file R1 ID
        fq_file_r2_id: Fastq file R2 ID
        fq_file_i1_id: Fastq file I1 ID
        fq_file_i2_id: Fastq file I2 ID

    Returns:
        dict: Updated Fastq dataset

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_dataset_endpoint = os.path.join(self.endpoint, self.FQ_DATASET_ENDPOINT, f'{dataset_id}/')

    # Define json for put request
    json = {
        "name": name,
        "description": description,
        "qc_passed": qc_passed,
        "paired_end": paired_end,
        "index_read": index_read,
        "project_ids": project_ids,
        "project_names": project_names,
        "metadata": metadata,
        "fq_file_r1": fq_file_r1_id,
        "fq_file_r2": fq_file_r2_id,
        "fq_file_i1": fq_file_i1_id,
        "fq_file_i2": fq_file_i2_id
    }

    res = requests.put(fq_dataset_endpoint, json=json, auth=self.auth)

    if res.status_code != 200:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"update_fastq_dataset failed: {detail}")
    else:
        return res.json()

update_fq_file(fq_file_id, name, read_type, qc_passed, read_length, num_reads, size_mb, qc_phred_mean, qc_phred, upload_path, md5_checksum, staging, pipeline_version)

Update Fastq File

Update Fastq file in ReadStore

Parameters:

Name Type Description Default
fq_file_id int

ID of Fastq file

required
name str

Fastq file name

required
read_type str

Read type (R1, R2, I1, I2)

required
qc_passed bool

QC Pass

required
read_length int

Read length

required
num_reads int

Number of reads

required
size_mb int

Size in MB

required
qc_phred_mean float

QC Phred Mean

required
qc_phred dict

QC Phred

required
upload_path str

Upload Path

required
md5_checksum str

MD5 Checksum

required
staging bool

Staging

required
pipeline_version str

Pipeline Version

required

Returns:

Name Type Description
dict dict

Fastq file data

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def update_fq_file(self,
                   fq_file_id: int,
                   name: str,
                   read_type: str,
                   qc_passed: bool,
                   read_length: int,
                   num_reads: int,
                   size_mb: int,
                   qc_phred_mean: float,
                   qc_phred: dict,
                   upload_path: str,
                   md5_checksum: str,
                   staging: bool,
                   pipeline_version: str) -> dict:

    """Update Fastq File

    Update Fastq file in ReadStore

    Args:
        fq_file_id: ID of Fastq file
        name: Fastq file name
        read_type: Read type (R1, R2, I1, I2)
        qc_passed: QC Pass
        read_length: Read length
        num_reads: Number of reads
        size_mb: Size in MB
        qc_phred_mean: QC Phred Mean
        qc_phred: QC Phred
        upload_path: Upload Path
        md5_checksum: MD5 Checksum
        staging: Staging
        pipeline_version: Pipeline Version

    Returns:    
        dict: Fastq file data

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """

    fq_file_endpoint = os.path.join(self.endpoint, self.FQ_FILE_ENDPOINT, f'{fq_file_id}/')

    # Define json for post request
    json = {
        "name": name,
        "read_type": read_type,
        "qc_passed": qc_passed,
        "read_length": read_length,
        "num_reads": num_reads,
        "size_mb": size_mb,
        "qc_phred_mean": qc_phred_mean,
        "qc_phred": qc_phred,
        "upload_path": upload_path,
        "md5_checksum": md5_checksum,
        "staging": staging,
        "pipeline_version": pipeline_version
    }

    res = requests.put(fq_file_endpoint, json=json, auth=self.auth)

    if res.status_code != 200:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"update_fq_file failed: {detail}")
    else:
        return res.json()

update_project(project_id, name, description, metadata, dataset_metadata_keys)

Update Project

Update an existing project in ReadStore

Parameters:

Name Type Description Default
project_id int

ID of the project to update

required
name str

Project name

required
description str

Project description

required
metadata dict

Project metadata

required
dataset_metadata_keys List[str]

Dataset metadata keys

required

Returns:

Name Type Description
dict dict

Updated project data

Raises:

Type Description
ReadStoreError

If request failed

Source code in readstore_cli/rsclient.py
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
def update_project(self,
                   project_id: int,
                   name: str,
                   description: str,
                   metadata: dict,
                   dataset_metadata_keys: List[str]) -> dict:        
    """Update Project

    Update an existing project in ReadStore

    Args:
        project_id: ID of the project to update
        name: Project name
        description: Project description
        metadata: Project metadata
        dataset_metadata_keys: Dataset metadata keys

    Returns:
        dict: Updated project data

    Raises:
        rsexceptions.ReadStoreError: If request failed
    """
    project_endpoint = os.path.join(self.endpoint, self.PROJECT_ENDPOINT, f'{project_id}/')

    dataset_metadata_keys = {key: "" for key in dataset_metadata_keys}

    json = {
        "name": name,
        "description": description,
        "metadata": metadata,
        "dataset_metadata_keys": dataset_metadata_keys
    }

    res = requests.put(project_endpoint, json=json, auth=self.auth)

    if res.status_code != 200:
        try:
            detail = res.json()
        except:
            detail = "No Message"

        raise rsexceptions.ReadStoreError(f"update_project failed: {detail}")
    else:
        return res.json()

upload_fastq(fastq_path, fastq_name=None, read_type=None)

Upload Fastq Files

Upload Fastq files to ReadStore. Check if file exists and has read permissions.

fastq_name: List of Fastq names for files to upload read_type: List of read types for files to upload

Parameters:

Name Type Description Default
fastq_path str

List of Fastq files to upload

required
fastq_name str | None

List of Fastq names for files to upload

None
read_types

List of read types for files to upload

required
read_types

Must be in ['R1', 'R2', 'I1', 'I2']

required

Raises:

Type Description
ReadStoreError

If file not found

ReadStoreError

If no read permissions

ReadStoreError

If upload URL request failed

Source code in readstore_cli/rsclient.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def upload_fastq(self,
                 fastq_path: str,
                 fastq_name: str | None = None,
                 read_type: str | None = None) -> None:
    """Upload Fastq Files

    Upload Fastq files to ReadStore.
    Check if file exists and has read permissions.

    fastq_name: List of Fastq names for files to upload
    read_type: List of read types for files to upload

    Args:
        fastq_path: List of Fastq files to upload
        fastq_name: List of Fastq names for files to upload
        read_types: List of read types for files to upload
        read_types: Must be in ['R1', 'R2', 'I1', 'I2']

    Raises:
        rsexceptions.ReadStoreError: If file not found
        rsexceptions.ReadStoreError: If no read permissions
        rsexceptions.ReadStoreError: If upload URL request failed
    """

    fq_upload_endpoint = os.path.join(self.endpoint, self.FASTQ_UPLOAD_ENDPOINT)

    # Run parallel uploads of fastq files
    fastq_path = os.path.abspath(fastq_path)

    # Make sure file exists and
    if not os.path.exists(fastq_path):
        raise rsexceptions.ReadStoreError(f"File Not Found: {fastq_path}")
    elif not os.access(fastq_path, os.R_OK):
        raise rsexceptions.ReadStoreError(f"No read permissions: {fastq_path}")

    payload = {
        "fq_file_path": fastq_path,
    }

    if not fastq_name is None:
        if fastq_name == "":
            raise rsexceptions.ReadStoreError("Fastq Name Is Empty")
        if not self.validate_charset(fastq_name):
            raise rsexceptions.ReadStoreError("Invalid Fastq Name")
        payload["fq_file_name"] = fastq_name

    if not read_type is None:
        if read_type not in ["R1", "R2", "I1", "I2"]:
            raise rsexceptions.ReadStoreError("Invalid Read Type")
        payload["read_type"] = read_type

    res = requests.post(fq_upload_endpoint, json=payload, auth=self.auth)

    if res.status_code not in [200, 204]:
        res_message = res.json().get("detail", "No Message")
        raise rsexceptions.ReadStoreError(
            f"Upload URL Request Failed: {res_message}"
        )

upload_pro_data(name, pro_data_path, data_type, dataset_id=None, dataset_name=None, metadata={}, description='')

Upload Processed Data

Upload Pro Data to ReadStore

Parameters:

Name Type Description Default
pro_data

Pro Data in JSON format

required

Raises:

Type Description
ReadStoreError

If upload request failed

Source code in readstore_cli/rsclient.py
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
def upload_pro_data(self,
                    name: str,
                    pro_data_path: str,
                    data_type: str,
                    dataset_id: int | None = None,
                    dataset_name: str | None = None,
                    metadata: dict = {},
                    description: str = "") -> None:
    """Upload Processed Data

    Upload Pro Data to ReadStore

    Args:
        pro_data: Pro Data in JSON format

    Raises:
        rsexceptions.ReadStoreError: If upload request failed
    """

    pro_data_endpoint = os.path.join(self.endpoint, self.PRO_DATA_ENDPOINT)

    # Run parallel uploads of fastq files
    pro_data_path = os.path.abspath(pro_data_path)

    # Make sure file exists and
    if not os.path.exists(pro_data_path):
        raise rsexceptions.ReadStoreError(f"File Not Found: {pro_data_path}")
    elif not os.access(pro_data_path, os.R_OK):
        raise rsexceptions.ReadStoreError(f"No read permissions: {pro_data_path}")

    # Define json for post request
    json = {
        "name" : name,
        "data_type": data_type,
        "upload_path": pro_data_path,
        "metadata": metadata,
        "description" : description,
    }

    if dataset_id:
        json['dataset_id'] = dataset_id
    if dataset_name:
        json['dataset_name'] = dataset_name        

    res = requests.post(pro_data_endpoint, json=json, auth=self.auth)

    if res.status_code == 403:
        raise rsexceptions.ReadStoreError(f"Upload ProData Failed: {res.json().get('detail')}")
    elif res.status_code not in [201, 204]:
        raise rsexceptions.ReadStoreError("upload_pro_data failed")

validate_charset(query_str)

Validate charset for query string

Parameters:

Name Type Description Default
query_str str

Query string to validate

required

Returns:

Name Type Description
bool bool
Source code in readstore_cli/rsclient.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def validate_charset(self, query_str: str) -> bool:
    """
    Validate charset for query string

    Args:
        query_str (str): Query string to validate

    Returns:
        bool: 
    """

    allowed = string.digits + string.ascii_lowercase + string.ascii_uppercase + '_-.@'
    allowed = set(allowed)

    return set(query_str) <= allowed

rsexceptions module

ReadStoreError

Bases: Exception

Base class for ReadStoreError exceptions.

Source code in readstore_cli/rsexceptions.py
18
19
20
21
22
class ReadStoreError(Exception):
    """Base class for ReadStoreError exceptions."""
    def __init__(self, message: str):
        super().__init__(message)
        self.message = message