util.py 2.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
from flask import request
from collections import defaultdict
import re
from secret import DB
import psycopg2,psycopg2.extras

def get_db_connection():
    """Getting a DB connection based on a loaded config that contains the ip and login. This file is not part of repositor
    """
    conn = psycopg2.connect(host=DB["host"],database=DB["database"], user=DB["user"], password=DB["password"])
    dictCur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    return dictCur


def get_url_params(testing=False,req=None):
    """Parses the URL send by user and returns a dictionary, cleaning of string goes here
    >>> get_url_params(testing=True,req=[('country', [u'BR,Es'])])
    defaultdict(<type 'list'>, {'country': [u'BR', u'Es']})
    
    >>> get_url_params(testing=True,req=[('country', [u'BR#$'])])
    defaultdict(<type 'list'>, {'country': [u'BR']})
    
    >>> get_url_params(testing=True,req=[('country', [u'BR,ES']), ('limit', [u''])])
    defaultdict(<type 'list'>, {'country': [u'BR', u'ES']})
    
    >>> get_url_params(testing=True,req=[('country', [u'BR,ES']), ('limit', [u''])])
    defaultdict(<type 'list'>, {'country': [u'BR', u'ES']})
    
    >>> get_url_params(testing=True,req=[('country', [u'BR,ES']), ('limit', [u'1'])])
    defaultdict(<type 'list'>, {'country': [u'BR', u'ES'], 'limit': 1})
    
    >>> get_url_params(testing=True,req=[('country', [u'BR,ES']), ('limit', [u'15.3'])])
    defaultdict(<type 'list'>, {'country': [u'BR', u'ES']})
    """
       
    if testing:
        l=req
    else:
        l=request.args.lists()
    
    d=defaultdict(list)

    for k,v in l:
        #Checkcing and cleaning the country structure
        if (k.lower()=='country'): 
            countryStr=v[0]
            countryList=countryStr.split(",") 
            countryList=[re.sub('\W+','',country) for country in countryList] #only leters and numbers allowed 
            d[k]=countryList
        
        #cleaning and making an int
        elif (k.lower()=='limit'):
            try:
                d[k]=int(v[0])
            except:
                pass
        else:
            d[k]=v
   
    return  d
if __name__ == "__main__":
    #print get_url_params(testing=True,req=[('country', [u'BR,ES']), ('limit', [u'15.3'])])
    import doctest
    doctest.testmod(verbose=1)