2 # -*- coding: utf-8 -*-
6 # configuration (codes d'accès à la base MS-SQL)
7 sys.path.append('/home/thomas/public_html/')
10 # pour savoir quel objet interroger : Routes
11 from routes import Mapper
12 from routes.middleware import RoutesMiddleware
13 # et analyse des paramètres (POST et query_string) pour filtrage
14 from paste.request import parse_formvars
16 # pour chercher les données sur MS-SQL
17 from pymssql import connect
19 # pour afficher le résultat : jinja
20 from jinja import Environment, FileSystemLoader
21 from jinja.filters import stringfilter
23 # TODO systeme de cache : beaker
24 # from beaker.middleware import CacheMiddleware
26 # formats de sortie autorisés, et content-type correspondant
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' }
30 # les routes RESTful (cf http://routes.groovie.org/manual.html#restful-services)
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')
38 mapper.resource('comare','comare')
39 # pour les comarexxx où xxx est un code d'implantation
40 mapper.resource('comarei','comare:(impl)',controller='comare')
41 mapper.resource('comsra','comsre')
42 mapper.resource('comsrai','comsre:(impl)',controller='comsre')
43 mapper.resource('dem','dem')
44 mapper.resource('com','com')
46 class objetsql(object):
47 """objet de base : dispose d'un accès à MS-SQL (lire les données) et d'un accès à jinja (rendu des données)"""
48 def __init__(self, environ):
49 self.bd = connect(host=rest_config.host,user=rest_config.user,password=rest_config.password,database=rest_config.database)
50 self.cursor = self.bd.cursor()
51 self.jinja = Environment(loader=FileSystemLoader('/home/thomas/public_html/'))
52 self.environ = environ
53 self.outputformat = environ['wsgiorg.routing_args'][1].get('format','xml')
55 class document(objetsql):
56 """objet document CODA (demlog, comlog, demdep... ils ont tous le même format)"""
57 def __init__(self, environ, code_document='%', basename_template='document'):
58 super(document, self).__init__(environ)
59 self.code_document = code_document
60 self.basename_template = basename_template
63 self.cursor.execute("select top 30 * from auf_v_acces_demcom where code like '%s' order by date_modif desc" % (self.code_document))
65 documents['code'] = self.code_document
68 document = dict_fetchone(self.cursor)
69 if document == None: break
70 document['code_rest'] = coda2rest(document['code'])
71 documents_liste.append(document)
72 documents['documents'] = documents_liste
73 template = self.jinja.get_template('%s-index.%s' % (self.basename_template, self.outputformat))
74 output = template.render(documents)
75 return self.outputformat, output
78 return 'txt', '%s' % self.environ
81 id = int(self.environ['wsgiorg.routing_args'][1]['id'])
82 self.cursor.execute("select top 1 * from auf_v_acces_demcom where code like '%s' and numero = %d" % (self.code_document, id))
83 document = dict_fetchone(self.cursor)
85 raise "document inexistant"
86 document['code_rest'] = coda2rest(document['code'])
88 self.cursor.execute("select * from auf_v_acces_dtls_demcom where code like '%s' and numero = %d" % (self.code_document, id))
90 detail = dict_fetchone(self.cursor)
91 if detail == None: break
92 details.append(detail)
93 document['details']=details
94 template = self.jinja.get_template('%s.%s' % (self.basename_template, self.outputformat))
95 output = template.render(document)
96 return self.outputformat, output
99 def __init__(self, environ):
100 super(dem, self).__init__(environ, code_document = 'DEM-%')
103 def __init__(self, environ):
104 super(com, self).__init__(environ, code_document = 'COM-%')
106 class demlog(document):
107 def __init__(self, environ):
108 super(demlog, self).__init__(environ, code_document = 'DEM-LOG-AUF')
110 class comlog(document):
111 def __init__(self, environ):
112 super(comlog, self).__init__(environ, code_document = 'COM-LOG-AUF')
114 class demdep(document):
115 def __init__(self, environ):
116 super(demdep, self).__init__(environ, code_document = 'DEM-DEP-AUF')
118 class comdep(document):
119 def __init__(self, environ):
120 super(comdep, self).__init__(environ, code_document = 'COM-DEP-AUF')
122 class dempub(document):
123 def __init__(self, environ):
124 super(dempub, self).__init__(environ, code_document = 'DEM-PUB-AUF')
126 class compub(document):
127 def __init__(self, environ):
128 super(compub, self).__init__(environ, code_document = 'COM-PUB-AUF')
130 class comsre(document):
131 def __init__(self, environ):
132 # est-ce un appel de comsre ou comsrexxx (avec xxx = implantation)
133 impl = environ['wsgiorg.routing_args'][1].get('impl','%')
134 super(comsre, self).__init__(environ, code_document = 'COM-SRE-%s' % impl)
136 class comare(document):
137 def __init__(self, environ):
138 impl = environ['wsgiorg.routing_args'][1].get('impl','%')
139 super(comare, self).__init__(environ, code_document = 'COM-ARE-%s' % impl)
141 def dispatcher(environ, start_response):
142 """dispatch vers la bonne methode du bon objet, et retour WSGI"""
143 parse_formvars(environ)
144 results = environ['wsgiorg.routing_args'][1]
146 target_class = globals()[results['controller']]
147 method_name = results['action']
148 method = getattr(target_class,method_name)
149 type, output = method(target_class(environ))
150 start_response("200 OK", [('Content-type', formats[type])])
151 return output.encode('utf-8')
153 start_response("404 NOT FOUND", [('Content-type', 'text/plain')])
154 return 'erreur lors du traitement\n%s: %s\n%s' % ( sys.exc_info()[0] , sys.exc_info()[1] , traceback.format_exc())
156 # application qui sera lancée par mod_wsgi : on route et on dispatche
157 application = RoutesMiddleware( dispatcher, mapper)
158 # TODO : ajouter un middleware de cache (beaker)
164 def dict_fetchone(cursor):
165 """Renvoie le resultat d'un fetchone dans un dictionnaire"""
166 result = cursor.fetchone()
167 if result == None: return None
169 for i in range(len(result)):
170 if isinstance( result[i], str ):
171 result_dict[cursor.description[i][0]] = result[i].decode('iso-8859-1')
173 result_dict[cursor.description[i][0]] = result[i]
177 p = re.compile('(dem|com)-(...)-(...)',re.IGNORECASE)
178 def coda2rest(value):
179 """Traduit un nom CODA vers la base REST correspodante,
180 par exemple DEM-LOG-AUF en demlog ou COM-ARE-VN3 en comarevn3"""
182 if m == None: return value
183 if m.group(3).lower() == 'auf':
184 return m.group(1).lower() + m.group(2).lower()
186 return m.group(1).lower() + m.group(2).lower() + m.group(3).lower()