Commit | Line | Data |
---|---|---|
1795efcd TN |
1 | #!/usr/bin/python |
2 | # -*- coding: utf-8 -*- | |
3 | ||
4 | import sys, traceback | |
5 | ||
a6627284 TN |
6 | # configuration (codes d'accès à la base MS-SQL) |
7 | sys.path.append('/home/thomas/public_html/') | |
8 | import rest_config | |
9 | ||
0a4c31d4 | 10 | # pour savoir quel objet interroger : Routes |
1795efcd | 11 | from routes import Mapper |
a6627284 | 12 | from routes.middleware import RoutesMiddleware |
0a4c31d4 | 13 | # et analyse de query_string (TODO: etudier parse au lieu de cgi) |
1795efcd TN |
14 | from cgi import parse_qs |
15 | ||
a6627284 | 16 | # pour chercher les données sur MS-SQL |
1795efcd | 17 | from pymssql import connect |
a6627284 TN |
18 | |
19 | # pour afficher le résultat : jinja | |
1795efcd TN |
20 | from jinja import Environment, FileSystemLoader |
21 | from jinja.filters import stringfilter | |
22 | ||
0a4c31d4 TN |
23 | # TODO systeme de cache : beaker |
24 | # from beaker.middleware import CacheMiddleware | |
1795efcd | 25 | |
a6627284 | 26 | # formats de sortie autorisés, et content-type correspondant |
d588d902 TN |
27 | # formats = { 'xml': 'application/xml', 'html': 'text/html', 'txt': 'text/plain', 'json': 'application/json', 'rss': 'application/rss+xml' } |
28 | formats = { 'xml': 'application/xml', 'html': 'text/html', 'txt': 'text/plain', 'json': 'text/plain', 'rss': 'application/rss+xml' } | |
1795efcd | 29 | |
0a4c31d4 | 30 | # les routes RESTful (cf http://routes.groovie.org/manual.html#restful-services) |
1795efcd | 31 | mapper = Mapper() |
0a4c31d4 TN |
32 | mapper.resource('demlog','demlog') |
33 | mapper.resource('comlog','comlog') | |
34 | mapper.resource('demdep','demdep') | |
35 | mapper.resource('comdep','comdep') | |
36 | mapper.resource('dempub','dempub') | |
37 | mapper.resource('compub','compub') | |
0a4c31d4 | 38 | mapper.resource('comare','comare') |
db1681c0 TN |
39 | # pour les comarexxx où xxx est un code d'implantation |
40 | mapper.resource('comarei','comare:(impl)',controller='comare') | |
0a4c31d4 | 41 | mapper.resource('comsra','comsre') |
db1681c0 | 42 | mapper.resource('comsrai','comsre:(impl)',controller='comsre') |
1795efcd TN |
43 | |
44 | class objetsql(object): | |
0a4c31d4 | 45 | """objet de base : dispose d'un accès à MS-SQL (lire les données) et d'un accès à jinja (rendu des données)""" |
1795efcd | 46 | def __init__(self, environ): |
a6627284 | 47 | self.bd = connect(host=rest_config.host,user=rest_config.user,password=rest_config.password,database=rest_config.database) |
1795efcd TN |
48 | self.cursor = self.bd.cursor() |
49 | self.jinja = Environment(loader=FileSystemLoader('/home/thomas/public_html/')) | |
1795efcd | 50 | self.environ = environ |
0a4c31d4 | 51 | self.outputformat = environ['wsgiorg.routing_args'][1].get('format','xml') |
a6627284 | 52 | |
1795efcd | 53 | class document(objetsql): |
0a4c31d4 | 54 | """objet document CODA (demlog, comlog, demdep... ils ont tous le même format)""" |
1795efcd TN |
55 | def __init__(self, environ, code_document='%', basename_template='document'): |
56 | super(document, self).__init__(environ) | |
57 | self.code_document = code_document | |
58 | self.basename_template = basename_template | |
59 | ||
60 | def index(self): | |
61 | self.cursor.execute("select top 30 * from auf_v_acces_demcom where code like '%s' order by date_modif desc" % (self.code_document)) | |
62 | documents={} | |
63 | documents['code'] = self.code_document | |
64 | documents_liste=[] | |
65 | while 1: | |
66 | document = dict_fetchone(self.cursor) | |
67 | if document == None: break | |
68 | document['code_rest'] = coda2rest(document['code']) | |
69 | documents_liste.append(document) | |
70 | documents['documents'] = documents_liste | |
71 | template = self.jinja.get_template('%s-index.%s' % (self.basename_template, self.outputformat)) | |
72 | output = template.render(documents) | |
73 | return self.outputformat, output | |
74 | ||
db1681c0 TN |
75 | def show_debug(self): |
76 | return 'txt', '%s' % self.environ | |
77 | ||
0a4c31d4 | 78 | def show(self): |
a6627284 | 79 | id = int(self.environ['wsgiorg.routing_args'][1]['id']) |
1795efcd TN |
80 | self.cursor.execute("select top 1 * from auf_v_acces_demcom where code like '%s' and numero = %d" % (self.code_document, id)) |
81 | document = dict_fetchone(self.cursor) | |
82 | if document == None: | |
83 | raise "document inexistant" | |
84 | document['code_rest'] = coda2rest(document['code']) | |
85 | details = [] | |
86 | self.cursor.execute("select * from auf_v_acces_dtls_demcom where code like '%s' and numero = %d" % (self.code_document, id)) | |
87 | while 1: | |
88 | detail = dict_fetchone(self.cursor) | |
89 | if detail == None: break | |
90 | details.append(detail) | |
91 | document['details']=details | |
92 | template = self.jinja.get_template('%s.%s' % (self.basename_template, self.outputformat)) | |
93 | output = template.render(document) | |
94 | return self.outputformat, output | |
95 | ||
96 | class demlog(document): | |
97 | def __init__(self, environ): | |
98 | super(demlog, self).__init__(environ, code_document = 'DEM-LOG-AUF') | |
99 | ||
100 | class comlog(document): | |
101 | def __init__(self, environ): | |
102 | super(comlog, self).__init__(environ, code_document = 'COM-LOG-AUF') | |
103 | ||
0a4c31d4 TN |
104 | class demdep(document): |
105 | def __init__(self, environ): | |
106 | super(demdep, self).__init__(environ, code_document = 'DEM-DEP-AUF') | |
107 | ||
108 | class comdep(document): | |
109 | def __init__(self, environ): | |
110 | super(comdep, self).__init__(environ, code_document = 'COM-DEP-AUF') | |
111 | ||
112 | class dempub(document): | |
113 | def __init__(self, environ): | |
114 | super(dempub, self).__init__(environ, code_document = 'DEM-PUB-AUF') | |
115 | ||
116 | class compub(document): | |
117 | def __init__(self, environ): | |
118 | super(compub, self).__init__(environ, code_document = 'COM-PUB-AUF') | |
119 | ||
0a4c31d4 TN |
120 | class comsre(document): |
121 | def __init__(self, environ): | |
db1681c0 TN |
122 | # est-ce un appel de comsre ou comsrexxx (avec xxx = implantation) |
123 | impl = environ['wsgiorg.routing_args'][1].get('impl','%') | |
124 | super(comsre, self).__init__(environ, code_document = 'COM-SRE-%s' % impl) | |
0a4c31d4 TN |
125 | |
126 | class comare(document): | |
127 | def __init__(self, environ): | |
db1681c0 TN |
128 | impl = environ['wsgiorg.routing_args'][1].get('impl','%') |
129 | super(comare, self).__init__(environ, code_document = 'COM-ARE-%s' % impl) | |
0a4c31d4 | 130 | |
a6627284 | 131 | def dispatcher(environ, start_response): |
1795efcd | 132 | """sera lancée par mod_wsgi""" |
a6627284 TN |
133 | if environ.has_key('QUERY_STRING'): |
134 | environ['org.auf.filters'] = parse_qs(environ['QUERY_STRING']) | |
135 | else: | |
136 | environ['org.auf.filters'] = {} | |
137 | results = environ['wsgiorg.routing_args'][1] | |
1795efcd TN |
138 | try: |
139 | target_class = globals()[results['controller']] | |
140 | method_name = results['action'] | |
1795efcd TN |
141 | method = getattr(target_class,method_name) |
142 | type, output = method(target_class(environ)) | |
143 | start_response("200 OK", [('Content-type', formats[type])]) | |
144 | return output.encode('utf-8') | |
145 | except: | |
146 | start_response("404 NOT FOUND", [('Content-type', 'text/plain')]) | |
147 | return 'erreur lors du traitement\n%s: %s\n%s' % ( sys.exc_info()[0] , sys.exc_info()[1] , traceback.format_exc()) | |
148 | ||
a6627284 | 149 | application = RoutesMiddleware( dispatcher, mapper) |
1795efcd | 150 | |
0a4c31d4 TN |
151 | |
152 | # | |
153 | # petits utilitaires | |
154 | # | |
1795efcd TN |
155 | def dict_fetchone(cursor): |
156 | """Renvoie le resultat d'un fetchone dans un dictionnaire""" | |
157 | result = cursor.fetchone() | |
158 | if result == None: return None | |
159 | result_dict = {} | |
160 | for i in range(len(result)): | |
161 | if isinstance( result[i], str ): | |
162 | result_dict[cursor.description[i][0]] = result[i].decode('iso-8859-1') | |
163 | else: | |
164 | result_dict[cursor.description[i][0]] = result[i] | |
165 | return result_dict | |
166 | ||
a6627284 | 167 | import re |
db1681c0 | 168 | p = re.compile('(dem|com)-(...)-(...)',re.IGNORECASE) |
a6627284 | 169 | def coda2rest(value): |
db1681c0 TN |
170 | """Traduit un nom CODA vers la base REST correspodante, |
171 | par exemple DEM-LOG-AUF en demlog ou COM-ARE-VN3 en comarevn3""" | |
a6627284 TN |
172 | m = p.search(value) |
173 | if m == None: return value | |
db1681c0 TN |
174 | if m.group(3).lower() == 'auf': |
175 | return m.group(1).lower() + m.group(2).lower() | |
176 | else: | |
177 | return m.group(1).lower() + m.group(2).lower() + m.group(3).lower() | |
a6627284 | 178 |