Completed
Push — master ( 5644bc...b87258 )
by Paolo
17s queued 13s
created

image_app.helpers.parse_image_alias()   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 17
rs 9.9
c 0
b 0
f 0
cc 3
nop 1
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Tue Feb  6 12:41:05 2018
5
6
@author: Paolo Cozzi <[email protected]>
7
8
Common functions in image_app
9
10
"""
11
12
import re
13
14
from .models import Animal, Sample
15
16
# a pattern to correctly parse aliases
17
ALIAS_PATTERN = re.compile(r"IMAGE([AS])([0-9]+)")
18
19
20
def parse_image_alias(alias):
21
    """Parse alias and return table and pk"""
22
23
    match = re.search(ALIAS_PATTERN, alias)
24
25
    letter, padded_pk = match.groups()
26
    table, pk = None, None
27
28
    if letter == "A":
29
        table = "Animal"
30
31
    elif letter == "S":
32
        table = "Sample"
33
34
    pk = int(padded_pk)
35
36
    return table, pk
37
38
39
def get_model_object(table, pk):
40
    """Get a model object relying on table name (Sample/Alias) and pk"""
41
42
    # get sample object
43
    if table == "Animal":
44
        sample_obj = Animal.objects.get(pk=pk)
45
46
    elif table == "Sample":
47
        sample_obj = Sample.objects.get(pk=pk)
48
49
    else:
50
        raise Exception("Unknown table '%s'" % (table))
51
52
    return sample_obj
53