eventman_server.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 json
  17. import utils
  18. import datetime
  19. import tornado.httpserver
  20. import tornado.ioloop
  21. import tornado.options
  22. from tornado.options import define, options
  23. import tornado.web
  24. from tornado import gen, escape
  25. import backend
  26. class ImprovedEncoder(json.JSONEncoder):
  27. """Enhance the default JSON encoder to serialize datetime objects."""
  28. def default(self, o):
  29. if isinstance(o, (datetime.datetime, datetime.date,
  30. datetime.time, datetime.timedelta)):
  31. return str(o)
  32. return json.JSONEncoder.default(self, o)
  33. json._default_encoder = ImprovedEncoder()
  34. class BaseHandler(tornado.web.RequestHandler):
  35. """Base class for request handlers."""
  36. def initialize(self, **kwargs):
  37. """Add every passed (key, value) as attributes of the instance."""
  38. for key, value in kwargs.iteritems():
  39. setattr(self, key, value)
  40. class RootHandler(BaseHandler):
  41. """Handler for the / path."""
  42. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  43. @gen.coroutine
  44. def get(self):
  45. # serve the ./angular_app/index.html file
  46. with open(self.angular_app_path + "/index.html", 'r') as fd:
  47. self.write(fd.read())
  48. class CollectionHandler(BaseHandler):
  49. """Base class for handlers that need to interact with the database backend.
  50. Introduce basic CRUD operations."""
  51. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  52. collection = None
  53. @gen.coroutine
  54. def get(self, id_=None):
  55. if id_ is not None:
  56. # read a single document
  57. self.write(self.db.get(self.collection, id_))
  58. else:
  59. # return an object containing the list of all objects in the collection;
  60. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  61. # Please, never return JSON lists that are not encapsulated into an object,
  62. # to avoid XSS vulnerabilities.
  63. self.write({self.collection: self.db.query(self.collection)})
  64. @gen.coroutine
  65. def post(self, id_=None, **kwargs):
  66. data = escape.json_decode(self.request.body or {})
  67. if id_ is None:
  68. # insert a new document
  69. newData = self.db.add(self.collection, data)
  70. else:
  71. # update an existing document
  72. newData = self.db.update(self.collection, id_, data)
  73. self.write(newData)
  74. # PUT (update an existing document) is handled by the POST (create a new document) method
  75. put = post
  76. @gen.coroutine
  77. def delete(self, id_=None, **kwargs):
  78. self.db.delete(self.collection, id_)
  79. class PersonsHandler(CollectionHandler):
  80. """Handle requests for Persons."""
  81. collection = 'persons'
  82. class EventsHandler(CollectionHandler):
  83. """Handle requests for Events."""
  84. collection = 'events'
  85. class ImportPersonsHandler(BaseHandler):
  86. pass
  87. class EbCSVImportPersonsHandler(ImportPersonsHandler):
  88. csvRemap = {
  89. 'Nome evento': 'event_title',
  90. 'ID evento': 'event_id',
  91. 'N. codice a barre': 'ebqrcode',
  92. 'Cognome acquirente': 'surname',
  93. 'Nome acquirente': 'name',
  94. 'E-mail acquirente': 'email',
  95. 'Cognome': 'original_surname',
  96. 'Nome': 'original_name',
  97. 'E-mail': 'original_email',
  98. 'Tipologia biglietto': 'ticket_kind',
  99. 'Data partecipazione': 'attending_datetime',
  100. 'Data check-in': 'checkin_datetime',
  101. 'Ordine n.': 'order_nr',
  102. }
  103. @gen.coroutine
  104. def post(self, **kwargs):
  105. targetEvent = None
  106. try:
  107. targetEvent = self.get_body_argument('targetEvent')
  108. except:
  109. pass
  110. reply = dict(total=0, valid=0, merged=0)
  111. for fieldname, contents in self.request.files.iteritems():
  112. for content in contents:
  113. filename = content['filename']
  114. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  115. reply['total'] += parseStats['total']
  116. reply['valid'] += parseStats['valid']
  117. for person in persons:
  118. if self.db.merge('persons', person,
  119. searchBy=[('email',), ('name', 'surname')]):
  120. reply['merged'] += 1
  121. self.write(reply)
  122. def run():
  123. """Run the Tornado web application."""
  124. # command line arguments; can also be written in a configuration file,
  125. # specified with the --config argument.
  126. define("port", default=5242, help="run on the given port", type=int)
  127. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  128. help="specify the directory used to store the data")
  129. define("mongodbURL", default=None,
  130. help="URL to MongoDB server", type=str)
  131. define("dbName", default='eventman',
  132. help="Name of the MongoDB database to use", type=str)
  133. define("debug", default=False, help="run in debug mode")
  134. define("config", help="read configuration file",
  135. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  136. tornado.options.parse_command_line()
  137. # database backend connector
  138. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  139. init_params = dict(db=db_connector)
  140. application = tornado.web.Application([
  141. (r"/persons/?(?P<id_>\w+)?", PersonsHandler, init_params),
  142. (r"/events/?(?P<id_>\w+)?", EventsHandler, init_params),
  143. (r"/(?:index.html)?", RootHandler, init_params),
  144. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  145. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  146. ],
  147. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  148. static_path=os.path.join(os.path.dirname(__file__), "static"),
  149. debug=options.debug)
  150. http_server = tornado.httpserver.HTTPServer(application)
  151. http_server.listen(options.port)
  152. tornado.ioloop.IOLoop.instance().start()
  153. if __name__ == '__main__':
  154. run()