eventman_server.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #!/usr/bin/env python
  2. """Event Man(ager)
  3. Your friendly manager of attendees at an event.
  4. Copyright 2015 Davide Alberani <da@erlug.linux.it>
  5. RaspiBO <info@raspibo.org>
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. """
  15. import os
  16. import csv
  17. import json
  18. import StringIO
  19. import datetime
  20. import tornado.httpserver
  21. import tornado.ioloop
  22. import tornado.options
  23. from tornado.options import define, options
  24. import tornado.web
  25. from tornado import gen, escape
  26. import backend
  27. class ImprovedEncoder(json.JSONEncoder):
  28. """Enhance the default JSON encoder to serialize datetime objects."""
  29. def default(self, o):
  30. if isinstance(o, (datetime.datetime, datetime.date,
  31. datetime.time, datetime.timedelta)):
  32. return str(o)
  33. return json.JSONEncoder.default(self, o)
  34. json._default_encoder = ImprovedEncoder()
  35. class BaseHandler(tornado.web.RequestHandler):
  36. """Base class for request handlers."""
  37. def initialize(self, **kwargs):
  38. """Add every passed (key, value) as attributes of the instance."""
  39. for key, value in kwargs.iteritems():
  40. setattr(self, key, value)
  41. class RootHandler(BaseHandler):
  42. """Handler for the / path."""
  43. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  44. @gen.coroutine
  45. def get(self):
  46. # serve the ./angular_app/index.html file
  47. with open(self.angular_app_path + "/index.html", 'r') as fd:
  48. self.write(fd.read())
  49. class CollectionHandler(BaseHandler):
  50. """Base class for handlers that need to interact with the database backend.
  51. Introduce basic CRUD operations."""
  52. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  53. collection = None
  54. @gen.coroutine
  55. def get(self, id_=None):
  56. if id_ is not None:
  57. # read a single document
  58. self.write(self.db.get(self.collection, id_))
  59. else:
  60. # return an object containing the list of all objects in the collection;
  61. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  62. # Please, never return JSON lists that are not encapsulated into an object,
  63. # to avoid XSS vulnerabilities.
  64. self.write({self.collection: self.db.query(self.collection)})
  65. @gen.coroutine
  66. def post(self, id_=None, **kwargs):
  67. data = escape.json_decode(self.request.body or {})
  68. if id_ is None:
  69. # insert a new document
  70. newData = self.db.add(self.collection, data)
  71. else:
  72. # update an existing document
  73. newData = self.db.update(self.collection, id_, data)
  74. self.write(newData)
  75. # PUT (update an existing document) is handled by the POST (create a new document) method
  76. put = post
  77. @gen.coroutine
  78. def delete(self, id_=None, **kwargs):
  79. self.db.delete(self.collection, id_)
  80. class PersonsHandler(CollectionHandler):
  81. """Handle requests for Persons."""
  82. collection = 'persons'
  83. class EventsHandler(CollectionHandler):
  84. """Handle requests for Events."""
  85. collection = 'events'
  86. class ImportPersonsHandler(BaseHandler):
  87. pass
  88. def csvParse(csvStr, remap=None, merge=None):
  89. fd = StringIO.StringIO(csvStr)
  90. reader = csv.reader(fd)
  91. remap = remap or {}
  92. merge = merge or {}
  93. fields = 0
  94. reply = dict(total=0, valid=0)
  95. results = []
  96. try:
  97. headers = reader.next()
  98. fields = len(headers)
  99. except (StopIteration, csv.Error):
  100. return reply, {}
  101. for idx, header in enumerate(headers):
  102. if header in remap:
  103. headers[idx] = remap[header]
  104. try:
  105. for row in reader:
  106. try:
  107. reply['total'] += 1
  108. if len(row) != fields:
  109. continue
  110. row = [unicode(cell, 'utf-8', 'replace') for cell in row]
  111. values = dict(map(None, headers, row))
  112. values.update(merge)
  113. results.append(values)
  114. reply['valid'] += 1
  115. except csv.Error:
  116. continue
  117. except csv.Error:
  118. pass
  119. fd.close()
  120. return reply, results
  121. class EbCSVImportPersonsHandler(ImportPersonsHandler):
  122. csvRemap = {
  123. 'Nome evento': 'event_title',
  124. 'ID evento': 'event_id',
  125. 'N. codice a barre': 'ebqrcode',
  126. 'Cognome acquirente': 'surname',
  127. 'Nome acquirente': 'name',
  128. 'E-mail acquirente': 'email',
  129. 'Cognome': 'original_surname',
  130. 'Nome': 'original_name',
  131. 'E-mail': 'original_email',
  132. 'Tipologia biglietto': 'ticket_kind',
  133. 'Data partecipazione': 'attending_datetime',
  134. 'Data check-in': 'checkin_datetime',
  135. 'Ordine n.': 'order_nr',
  136. }
  137. @gen.coroutine
  138. def post(self, **kwargs):
  139. targetEvent = None
  140. try:
  141. targetEvent = self.get_body_argument('targetEvent')
  142. except:
  143. pass
  144. reply = dict(total=0, valid=0, merged=0)
  145. for fieldname, contents in self.request.files.iteritems():
  146. for content in contents:
  147. filename = content['filename']
  148. parseStats, persons = csvParse(content['body'], remap=self.csvRemap)
  149. reply['total'] += parseStats['total']
  150. reply['valid'] += parseStats['valid']
  151. for person in persons:
  152. if self.db.merge('persons', person,
  153. searchBy=[('email',), ('name', 'surname')]):
  154. reply['merged'] += 1
  155. self.write(reply)
  156. def run():
  157. """Run the Tornado web application."""
  158. # command line arguments; can also be written in a configuration file,
  159. # specified with the --config argument.
  160. define("port", default=5242, help="run on the given port", type=int)
  161. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  162. help="specify the directory used to store the data")
  163. define("mongodbURL", default=None,
  164. help="URL to MongoDB server", type=str)
  165. define("dbName", default='eventman',
  166. help="Name of the MongoDB database to use", type=str)
  167. define("debug", default=False, help="run in debug mode")
  168. define("config", help="read configuration file",
  169. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  170. tornado.options.parse_command_line()
  171. # database backend connector
  172. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  173. init_params = dict(db=db_connector)
  174. application = tornado.web.Application([
  175. (r"/persons/?(?P<id_>\w+)?", PersonsHandler, init_params),
  176. (r"/events/?(?P<id_>\w+)?", EventsHandler, init_params),
  177. (r"/(?:index.html)?", RootHandler, init_params),
  178. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  179. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  180. ],
  181. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  182. static_path=os.path.join(os.path.dirname(__file__), "static"),
  183. debug=options.debug)
  184. http_server = tornado.httpserver.HTTPServer(application)
  185. http_server.listen(options.port)
  186. tornado.ioloop.IOLoop.instance().start()
  187. if __name__ == '__main__':
  188. run()