Advertisement
Guest User

new_eve_demo

a guest
Feb 13th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.45 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import os
  4. from eve import Eve
  5. from eve.auth import BasicAuth
  6. import datetime
  7. import time
  8. import bcrypt
  9. import helper
  10. from flask import current_app as app, abort, request, Response
  11. from settings import DATE_FORMAT
  12. from apscheduler.schedulers.background import BackgroundScheduler
  13. from apscheduler.jobstores.base import JobLookupError
  14.  
  15.  
  16. scheduler = BackgroundScheduler()
  17. scheduler.start()
  18.  
  19.  
  20. class MyBasicAuth(BasicAuth):
  21.     def check_auth(self, username, password, allowed_roles, resource, method):
  22.         print(username)
  23.         print(password)
  24.         print(method)
  25.         users = app.data.driver.db['users']
  26.         user = users.find_one({'username': username})
  27.         if not user:
  28.             abort(401)
  29.         if user and 'username' in user:
  30.             self.set_request_auth_value(user['username'])
  31.  
  32.         hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
  33.         if bcrypt.checkpw(password.encode('utf-8'), hashed):
  34.             print("Done!")
  35.         else:
  36.             print("Fail!")
  37.         return username
  38.  
  39.  
  40. def test_hooks(response):
  41.     print("test ok: %s" % response)
  42.  
  43.  
  44. def before_insert_users(items):
  45.     for user in items:
  46.         password = user['password'].encode('utf-8')
  47.         user['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
  48.         print(user['password'])
  49.     return items
  50.  
  51.  
  52. def on_update_users(updates, original):
  53.     password = updates['password'].encode('utf-8')
  54.     updates['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
  55.     print(updates['password'])
  56.     return updates
  57.  
  58.  
  59. def on_replace_users(item, original):
  60.     password = item['password'].encode('utf-8')
  61.     item['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
  62.     return item
  63.  
  64.  
  65. def post_get_callback(resource, request, payload):
  66.     print('A GET on the "%s" endpoint was just performed!' % resource)
  67.     now = datetime.datetime.now()
  68.     print(now)
  69.  
  70.  
  71. ###POST REQEST###
  72. def before_insert_notifications(items):
  73.     items_dict = items[0]
  74.     datetime_publication = items_dict['datetime_publication']
  75.     time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
  76.     if time.time() < time_publication:
  77.         items[0]['active'] = True
  78.         print("...Записалось...")
  79.     return items
  80.  
  81.  
  82. def after_insert_notifications(items):
  83.     items_dict = items[0]
  84.     print("...После добавления...")
  85.     notification_id = items_dict['_id']
  86.     kwargs = {"resource": "notifications", "document_id": notification_id,
  87.               "field_name": "active", "value": True}
  88.     datetime_publication = items_dict['datetime_publication']
  89.     if items_dict['active'] is True:
  90.         scheduler.add_job(helper.update_document,
  91.                           'date', run_date=datetime_publication, id=str(notification_id),
  92.                           kwargs=kwargs, replace_existing=True)
  93.         print("...Все добавилось в скедьюлер...")
  94.     scheduler.print_jobs()
  95.  
  96. ###PUT request###
  97. def before_replace_notifications(item, original):
  98.     datetime_publication = item['datetime_publication']
  99.     if str(datetime_publication) not in str(original['datetime_publication']):
  100.         time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
  101.         if time.time() < time_publication:
  102.             item['active'] = True
  103.             print("Запиь поменялась, активна")
  104.         else:
  105.             item['active'] = False
  106.             print("Запись поменялась, не активна")
  107.     else:
  108.         print("...Дата/время не было изменено...")
  109.     return item
  110.  
  111.  
  112. def after_replaced_notifications(item, original):
  113.     item_dict = item
  114.     if str(item['datetime_publication']) not in str(original['datetime_publication']):
  115.         print("...После изменения...")
  116.         notification_id = item_dict['_id']
  117.         kwargs = {"resource": "notifications", "document_id": notification_id,
  118.                   "field_name": "active", "value": True}
  119.         datetime_publication = item_dict['datetime_publication']
  120.         if item_dict['active'] is True:
  121.             print("...Все изменилось и добавилось в скедьюлер...")
  122.             scheduler.add_job(helper.update_document,
  123.                               'date', run_date=datetime_publication, id=str(notification_id), kwargs=kwargs,
  124.                               replace_existing=True)
  125.         else:
  126.             if scheduler.get_job(job_id=str(notification_id)) is None:
  127.                 print("Объекта с таким ID не существует")
  128.             else:
  129.                 print("...Неверные данные, запись будет удалена...")
  130.                 scheduler.remove_job(job_id=str(notification_id))
  131.         scheduler.print_jobs()
  132.     else:
  133.         print("...Дата/время не было изменено...")
  134.     return item
  135.     scheduler.print_jobs()
  136.  
  137. ###PATCH request###
  138. def before_update_notifications(updates, original):
  139.     print("...Обновление...")
  140.     datetime_publication = updates['datetime_publication']
  141.     old_times = original['datetime_publication']
  142.     if str(datetime_publication) not in str(old_times):
  143.         time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
  144.         if time.time() < time_publication:
  145.             updates['active'] = True
  146.             print("...Запись обновилась, активна...")
  147.         else:
  148.                 updates['active'] = False
  149.                 print("...Запись обновилась, неверное время, не активна")
  150.  
  151.         notification_id = original['_id']
  152.         kwargs = {"resource": "notifications", "document_id": notification_id,
  153.                   "field_name": "active", "value": True}
  154.         datetime_publication = updates['datetime_publication']
  155.  
  156.         if updates['active'] is True:
  157.             print("...Все обновилось и добавилось в скедьюлер...")
  158.             scheduler.add_job(helper.update_document,
  159.                               'date', run_date=datetime_publication, id=str(notification_id), kwargs=kwargs,
  160.                               replace_existing=True)
  161.         else:
  162.             if scheduler.get_job(job_id=str(notification_id)) is None:
  163.                 print("...Объекта с таким ID не существует...")
  164.             else:
  165.                 print("...Неверные данные, запись будет удалена...")
  166.                 scheduler.remove_job(job_id=str(notification_id))
  167.         scheduler.print_jobs()
  168.     else:
  169.         print("...Дата/время не было изменено...")
  170.         scheduler.print_jobs()
  171.     return updates
  172.  
  173. ###DELETE request###
  174. def before_delete_item_notifications(item):
  175.     print("...Удаление из скедьюлера...")
  176.     notification_id = item['_id']
  177.     scheduler.remove_job(job_id=str(notification_id))
  178.     scheduler.print_jobs()
  179.  
  180.  
  181. def before_delete_resource_notifications():
  182.     print("....Удаление из скедьюлера всего")
  183.     scheduler.remove_all_jobs()
  184.     scheduler.print_jobs()
  185.  
  186.  
  187. ###GET request###
  188. stats_dict = {'Да': 0, 'Нет': 0, 'Не знаю': 0}
  189.  
  190.  
  191. def before_returning_answers(response):
  192.     if 'Да' in response['answers']:
  193.         stats_dict['Да'] += 1
  194.     elif 'Нет' in response['answers']:
  195.         stats_dict['Нет'] += 1
  196.     else:
  197.         stats_dict['Не знаю'] += 1
  198.     print(stats_dict)
  199.  
  200.  
  201. if 'PORT' in os.environ:
  202.     port = int(os.environ.get('PORT'))
  203.     host = '0.0.0.0'
  204. else:
  205.     port = 5000
  206.     host = '127.0.0.1'
  207.  
  208. app = Eve(auth=MyBasicAuth)
  209.  
  210. app.on_post_GET += post_get_callback
  211.  
  212. app.on_insert_users += before_insert_users
  213. app.on_update_users += on_update_users
  214. app.on_replace_users += on_replace_users
  215.  
  216. app.on_insert_notifications += before_insert_notifications
  217. app.on_inserted_notifications += after_insert_notifications
  218. app.on_replace_notifications += before_replace_notifications
  219. app.on_replaced_notifications += after_replaced_notifications
  220. app.on_update_notifications += before_update_notifications
  221. app.on_delete_item_notifications += before_delete_item_notifications
  222. app.on_delete_resource_notifications += before_delete_resource_notifications
  223.  
  224. #app.on_fetched_resource += before_returning_answers
  225.  
  226. if __name__ == '__main__':
  227.     app.run(host=host, port=port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement