Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import os
- from eve import Eve
- from eve.auth import BasicAuth
- import datetime
- import time
- import bcrypt
- import helper
- from flask import current_app as app, abort, request, Response
- from settings import DATE_FORMAT
- from apscheduler.schedulers.background import BackgroundScheduler
- from apscheduler.jobstores.base import JobLookupError
- scheduler = BackgroundScheduler()
- scheduler.start()
- class MyBasicAuth(BasicAuth):
- def check_auth(self, username, password, allowed_roles, resource, method):
- print(username)
- print(password)
- print(method)
- users = app.data.driver.db['users']
- user = users.find_one({'username': username})
- if not user:
- abort(401)
- if user and 'username' in user:
- self.set_request_auth_value(user['username'])
- hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
- if bcrypt.checkpw(password.encode('utf-8'), hashed):
- print("Done!")
- else:
- print("Fail!")
- return username
- def test_hooks(response):
- print("test ok: %s" % response)
- def before_insert_users(items):
- for user in items:
- password = user['password'].encode('utf-8')
- user['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
- print(user['password'])
- return items
- def on_update_users(updates, original):
- password = updates['password'].encode('utf-8')
- updates['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
- print(updates['password'])
- return updates
- def on_replace_users(item, original):
- password = item['password'].encode('utf-8')
- item['password'] = bcrypt.hashpw(password, bcrypt.gensalt())
- return item
- def post_get_callback(resource, request, payload):
- print('A GET on the "%s" endpoint was just performed!' % resource)
- now = datetime.datetime.now()
- print(now)
- ###POST REQEST###
- def before_insert_notifications(items):
- items_dict = items[0]
- datetime_publication = items_dict['datetime_publication']
- time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
- if time.time() < time_publication:
- items[0]['active'] = True
- print("...Записалось...")
- return items
- def after_insert_notifications(items):
- items_dict = items[0]
- print("...После добавления...")
- notification_id = items_dict['_id']
- kwargs = {"resource": "notifications", "document_id": notification_id,
- "field_name": "active", "value": True}
- datetime_publication = items_dict['datetime_publication']
- if items_dict['active'] is True:
- scheduler.add_job(helper.update_document,
- 'date', run_date=datetime_publication, id=str(notification_id),
- kwargs=kwargs, replace_existing=True)
- print("...Все добавилось в скедьюлер...")
- scheduler.print_jobs()
- ###PUT request###
- def before_replace_notifications(item, original):
- datetime_publication = item['datetime_publication']
- if str(datetime_publication) not in str(original['datetime_publication']):
- time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
- if time.time() < time_publication:
- item['active'] = True
- print("Запиь поменялась, активна")
- else:
- item['active'] = False
- print("Запись поменялась, не активна")
- else:
- print("...Дата/время не было изменено...")
- return item
- def after_replaced_notifications(item, original):
- item_dict = item
- if str(item['datetime_publication']) not in str(original['datetime_publication']):
- print("...После изменения...")
- notification_id = item_dict['_id']
- kwargs = {"resource": "notifications", "document_id": notification_id,
- "field_name": "active", "value": True}
- datetime_publication = item_dict['datetime_publication']
- if item_dict['active'] is True:
- print("...Все изменилось и добавилось в скедьюлер...")
- scheduler.add_job(helper.update_document,
- 'date', run_date=datetime_publication, id=str(notification_id), kwargs=kwargs,
- replace_existing=True)
- else:
- if scheduler.get_job(job_id=str(notification_id)) is None:
- print("Объекта с таким ID не существует")
- else:
- print("...Неверные данные, запись будет удалена...")
- scheduler.remove_job(job_id=str(notification_id))
- scheduler.print_jobs()
- else:
- print("...Дата/время не было изменено...")
- return item
- scheduler.print_jobs()
- ###PATCH request###
- def before_update_notifications(updates, original):
- print("...Обновление...")
- datetime_publication = updates['datetime_publication']
- old_times = original['datetime_publication']
- if str(datetime_publication) not in str(old_times):
- time_publication = time.mktime(time.strptime(str(datetime_publication), DATE_FORMAT))
- if time.time() < time_publication:
- updates['active'] = True
- print("...Запись обновилась, активна...")
- else:
- updates['active'] = False
- print("...Запись обновилась, неверное время, не активна")
- notification_id = original['_id']
- kwargs = {"resource": "notifications", "document_id": notification_id,
- "field_name": "active", "value": True}
- datetime_publication = updates['datetime_publication']
- if updates['active'] is True:
- print("...Все обновилось и добавилось в скедьюлер...")
- scheduler.add_job(helper.update_document,
- 'date', run_date=datetime_publication, id=str(notification_id), kwargs=kwargs,
- replace_existing=True)
- else:
- if scheduler.get_job(job_id=str(notification_id)) is None:
- print("...Объекта с таким ID не существует...")
- else:
- print("...Неверные данные, запись будет удалена...")
- scheduler.remove_job(job_id=str(notification_id))
- scheduler.print_jobs()
- else:
- print("...Дата/время не было изменено...")
- scheduler.print_jobs()
- return updates
- ###DELETE request###
- def before_delete_item_notifications(item):
- print("...Удаление из скедьюлера...")
- notification_id = item['_id']
- scheduler.remove_job(job_id=str(notification_id))
- scheduler.print_jobs()
- def before_delete_resource_notifications():
- print("....Удаление из скедьюлера всего")
- scheduler.remove_all_jobs()
- scheduler.print_jobs()
- ###GET request###
- stats_dict = {'Да': 0, 'Нет': 0, 'Не знаю': 0}
- def before_returning_answers(response):
- if 'Да' in response['answers']:
- stats_dict['Да'] += 1
- elif 'Нет' in response['answers']:
- stats_dict['Нет'] += 1
- else:
- stats_dict['Не знаю'] += 1
- print(stats_dict)
- if 'PORT' in os.environ:
- port = int(os.environ.get('PORT'))
- host = '0.0.0.0'
- else:
- port = 5000
- host = '127.0.0.1'
- app = Eve(auth=MyBasicAuth)
- app.on_post_GET += post_get_callback
- app.on_insert_users += before_insert_users
- app.on_update_users += on_update_users
- app.on_replace_users += on_replace_users
- app.on_insert_notifications += before_insert_notifications
- app.on_inserted_notifications += after_insert_notifications
- app.on_replace_notifications += before_replace_notifications
- app.on_replaced_notifications += after_replaced_notifications
- app.on_update_notifications += before_update_notifications
- app.on_delete_item_notifications += before_delete_item_notifications
- app.on_delete_resource_notifications += before_delete_resource_notifications
- #app.on_fetched_resource += before_returning_answers
- if __name__ == '__main__':
- app.run(host=host, port=port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement