queries.py 3.95 KB
Newer Older
Franziska Koehn's avatar
Franziska Koehn committed
1
2
3
from threading import Lock
requests_lock = Lock()

4
5
6
7
8
9
def get_query_methods():
    return ["AND", "OR"]

def get_operators():
    return ["LIKE", ">", "<", "<=", ">=", "="]

Franziska Koehn's avatar
Franziska Koehn committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def get_credentials(force=False,username="", password="" ):
    if get_credentials.cache and not force:
        return get_credentials.cache
    from getpass import getpass
    while not len(username):
        username = raw_input("Username: ").strip()
    while not len(password):
        password = getpass().strip()
    get_credentials.cache = username, password
    return get_credentials()
get_credentials.cache = None



Franziska Koehn's avatar
Franziska Koehn committed
24
def download_all(results, host):
25
    for r in results:
26
27
        download(r, host)

Franziska Koehn's avatar
Franziska Koehn committed
28
def download_async(result, host, dest_folder='', cb=(lambda *_: None), cb_args=()):
Franziska Koehn's avatar
Franziska Koehn committed
29
    from threading import Thread
Franziska Koehn's avatar
Franziska Koehn committed
30
    download_thread = Thread(target=download, args=(result, host, dest_folder, cb, cb_args))
Franziska Koehn's avatar
Franziska Koehn committed
31
32
    download_thread.start()
    return download_thread
Franziska Koehn's avatar
Franziska Koehn committed
33

Franziska Koehn's avatar
Franziska Koehn committed
34
def download(result, host, dest_folder='', cb=(lambda *_: None), cb_args=()):
Franziska Koehn's avatar
Franziska Koehn committed
35
    requests_lock.acquire()
36
    print(result)
Franziska Koehn's avatar
Franziska Koehn committed
37
    subject = result['xnat_mrsessiondata_subject_id']   #TODO download andere typen
38
39
40
    experiment = result['xnat_mrsessiondata_session_id']
    project = result['xnat_mrsessiondata_project']
    scan = result['id']
41
    file_name = "%s/%s-%s-%s-%s" % (dest_folder, project, subject, experiment, scan)
42
    download_file(host, project, subject, experiment, scan, file_name)
Franziska Koehn's avatar
Franziska Koehn committed
43
44
    requests_lock.release()
    cb(*cb_args)
45

Franziska Koehn's avatar
Franziska Koehn committed
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
def download_file(host, project, subject, experiment, scan, file_name):
    import requests
    from base64 import b64encode
    from requests.auth import HTTPBasicAuth

    if not file_name.endswith(".zip"):
        file_name += ".zip"

    url= "%s/data/archive/projects/%s/subjects/%s/experiments/%s/scans/%s/resources/DICOM/files?format=zip" % (host, project, subject, experiment, scan)

    user, passw = get_credentials()

    try:
        with open(file_name, 'wb') as handle:
            response = requests.get(url, stream=True, auth=HTTPBasicAuth(user, passw))
            if not response.ok:
                raise ValueError(response.status_code)
            for block in response.iter_content(1024):
                if not block:
                    break
                handle.write(block)
    except IOError as e:
        print "Error writing file %s, %s" % (file_name, e)
    except ValueError as e:
        print "Error downloading file %s, Status Code %s" % (url, e)


73
def search_for(host, root_element, constraints, search_fields, user, passw):
74
75
    import xsa.errors as xsa_errors

76
77
    from pyxnat.core import errors
    from httplib2 import ServerNotFoundError
78
79
    from httplib import ResponseNotReady

80

81
    get_credentials(username=user, password=passw, force=True)
82
83
84
    user, passw = get_credentials() # TODO

    from tempfile import mkdtemp
85
    tmp_dir=mkdtemp()
86

87
    from pyxnat import Interface
88
    try:
89
90
91
92
93
94
        central = Interface(server=host,
                            user=user,
                            password=passw,
                            cachedir=tmp_dir)
    except IndexError as e:
        raise xsa_errors.ServerNotFoundError("Server not found, check your host-address.") #TODO Ok?
95

96
97
98
99
    result = []

    try:
        result =  central.select(root_element,search_fields).where(constraints)
100
101
102
    except errors.DatabaseError as e:
        if '401' in str(e):
            raise xsa_errors.UnauthorizedError("Unauthorizied attempt. Check your User and Password")
103
    except ServerNotFoundError:
104
105
106
107
108
109
        raise xsa_errors.ServerNotFoundError("Server not found, check your host-address.")
    except ResponseNotReady:
        raise xsa_errors.ResponseNotReady("Please check your Host-Address")

    if result == []:
        raise xsa_errors.QueryError("Please check your query.")
110
111
112
113
114
115
116
117
118
119
120

    try:
        central.disonnect()
    except AttributeError:
        print "can\'t close connection (wrong pyxnat version?)"

    try:
        from shutil import rmtree
        rmtree(tmp_dir)
    except:
        pass
121

122
    return result