def update(doc_id: str) -> None: """ To do unit test passes test as true """ ModelNotification.objects(id=doc_id).update_one( read=True, updated_at=datetime.utcnow() )
def create(provider_id: str, msg: str) -> None: """ To do unit test passes test as true """ object = ModelNotification( content=msg, recipient_id=provider_id ) object.save() return object.id
def test_update_notification(db: Session) -> None: provider = utils.create_random_provider(db) notification = utils.create_random_notification(provider) crud_notification.update(notification.id) update_notification = Notification.objects(id=notification.id).first() assert update_notification db.delete(provider) db.commit() Notification.delete(notification)
def test_create_notification(db: Session) -> None: provider = utils.create_random_provider(db) message = utils.random_lower_string() document_id = crud_notification.create(str(provider.id), message) notification = Notification.objects(id=document_id).first() assert notification assert notification.content == message assert notification.recipient_id == str(provider.id) db.delete(provider) db.commit() Notification.delete(notification)
def send_notification(user, title, message, actions=None): """ Helper function to send notifications. :param user: :param title: :param message: :param actions: :return: """ notification = Notification(user_id=user.id, title=title, message=message) if not actions: actions = [] notification.actions = actions save_to_db(notification, msg="Notification saved") record_activity('notification_event', user=user, title=title, actions=actions)
def add_notification(self, name, data): if self.notifications: self.notifications.filter_by(name=name).delete() n = Notification(name=name, payload_json=json.dumps(data), user=self) db.session.add(n) return n
def test_notification_get_data(self): """ WHEN getting a notification's data THEN return the data as JSON """ payload = dict(test=1) user = create_user(A_USERNAME, A_PASSWORD, AN_EMAIL) notification = Notification( name="test", user_profile=user.profile, timestamp=23.4324324, payload_json=json.dumps(payload), ) data = notification.get_data() self.assertEqual(data, payload)
def send_notification(user, title, message, actions=None): """ Helper function to send notifications. :param user: :param title: :param message: :param actions: :return: """ if not current_app.config['TESTING']: notification = Notification(user_id=user.id, title=title, message=message ) if not actions: actions = [] notification.actions = actions save_to_db(notification, msg="Notification saved") record_activity('notification_event', user=user, title=title, actions=actions)
def send_notification(user, action, title, message): if not current_app.config['TESTING']: notification = Notification(user_id=user.id, title=title, message=message, action=action) save_to_db(notification, msg="Notification saved") record_activity('notification_event', user=user, action=action, title=title)
def test_list_provider_notifications(client: TestClient, db: Session) -> None: user = utils.create_random_user(db) user = utils.activate_random_user(db, user) provider = utils.create_random_provider(db) provider = utils.activate_random_user(db, provider) notification = utils.create_random_notification(provider) appointment = utils.create_random_appointment(db, provider, user) token = security.generate_token(str(provider.id), "access", datetime.utcnow() + timedelta(hours=2)) header = {'Authorization': f'Bearer {token}'} response = client.get("/providers/notifications", headers=header) data = response.json() assert response.status_code == 200 assert data assert data[0]['recipient_id'] == str(provider.id) db.delete(user) db.delete(provider) db.delete(appointment) db.commit() Notification.delete(notification)
def get_all_notifications(provider_id: str) -> List[dict]: queryset: ModelNotification = ModelNotification.objects( recipient_id=provider_id, read=False ).all() notification = [] for q in queryset: value = q.to_mongo().to_dict() value['id'] = value['_id'] notification.append(value) return notification
def test_update_notification(client: TestClient, db: Session) -> None: user = utils.create_random_user(db) user = utils.activate_random_user(db, user) provider = utils.create_random_provider(db) provider = utils.activate_random_user(db, provider) notification = utils.create_random_notification(provider) appointment = utils.create_random_appointment(db, provider, user) token = security.generate_token(str(provider.id), "access", datetime.utcnow() + timedelta(hours=2)) header = {'Authorization': f'Bearer {token}'} response = client.put("/providers/notifications", headers=header, json={"doc_id": str(notification.id)}) document = Notification.objects(id=notification.id).first() assert response.status_code == 204 assert document.read == True db.delete(user) db.delete(provider) db.delete(appointment) db.commit() Notification.delete(notification)
def save_notification(self, type, message, receiver_id, sender_id): notification = Notification() notification.sender_uid = sender_id notification.receiver_uid = receiver_id notification.message = message notification.type = type db.session.add(notification) try: db.session.commit() return True except SQLAlchemyError as e: data = e.orig.args return False
def create(self, payloads): response = ResponseBuilder() notification = Notification() notification.message = payloads['message'] notification.receiver_uid = payloads['receiver'] notification.type = payloads['type'] notification.sender_uid = payloads['user']['id'] db.session.add(notification) try: db.session.commit() data = notification.as_dict() data['receiver'] = notification.receiver.include_photos().as_dict() data['sender'] = notification.sender.include_photos().as_dict() return response.set_data(data).build() except SQLAlchemyError as e: data = e.orig.args return response.set_data(data).set_error(True).build()
def send(cls, query: dict, session: dict) -> Notification: """ Business method to send a new notification. """ assert isinstance(session, dict) SendNotificationQueryValidation.validate(query) user = User.objects.get(pk=query[cls.USER_ID]) notification = Notification() notification.code = query[cls.CODE] notification.is_error = query.get(cls.IS_ERROR) notification.title = query[cls.TITLE] notification.message = query[cls.MESSAGE] user.notifications.append(notification) user.save() queue = Queue(f"notifications-{user.id}") queue.add(notification.to_json()) return notification
def send_notification(notification_content: NotificationContent, user=None, users=None): if not NotificationSettings.is_enabled(notification_content.type): logger.info( 'Notification of type %s are disabled, hence skipping', notification_content.type, ) return users = users or [] if user: users.append(user) if not users: raise ValueError( 'Either provide user or users for sending notification') for user in set(users): notification = Notification(content=notification_content, user=user) db.session.add(notification) db.session.commit()
def insert_notification(message, status): notification = Notification(message=message, status=status) db.session.add(notification) db.session.commit() return notification.serialize
def create_random_notification(provider: User) -> Notification: message = random_lower_string() document_id = crud_notification.create(str(provider.id), message) return Notification.objects(id=document_id).first()
def notify_observers(self, book_id): reservations = reservation_service.get_reservations_by_book_id(book_id) for reservation in reservations: message = f"The book titled {reservation.book.title} is now available" notificationn = Notification(message, reservation.member) reservation.member.receive_notification(notificationn)
def create_app(config_name): from config import config, logger app.config.from_object(config[config_name]) # 中文化 Babel(app) # 注册flask-login login.init_app(app) # bootstrap bootstrap.init_app(app) @login.user_loader def load_user(user_id): return User.query.get(user_id) # 注册蓝图 from app.main.views import bp as main_bp app.register_blueprint(main_bp) # 注册数据库 db.init_app(app) # 注册flask-admin admin.init_app(app, index_view=AdminIndexView(template='admin/index.html', url='/')) # 注册APScheduler scheduler.init_app(app) scheduler.start() # 视图 from app.models.task import Task from app.models.rss_task import RSSTask from app.models.mail_setting import MailSetting from app.models.notification import Notification from app.models.task_status import TaskStatus from app.models.user import User admin.add_view(TaskStatusView(TaskStatus, db.session, name='任务状态')) admin.add_view(TaskView(Task, db.session, name='网页监控任务管理')) admin.add_view(RSSTaskView(RSSTask, db.session, name='RSS监控任务管理')) admin.add_view(NotificationView(Notification, db.session, name='通知方式管理')) admin.add_view(MailSettingView(MailSetting, db.session, name='系统邮箱设置')) admin.add_view(UserView(User, db.session, name='账号密码管理')) with app.test_request_context(): db.create_all() mail_setting = MailSetting.query.first() # 插入默认邮箱配置 if mail_setting is None: mail_setting = MailSetting() db.session.add(mail_setting) db.session.commit() # 初始化账号密码 user = User.query.first() if user is None: user = User('admin', 'admin') db.session.add(user) db.session.commit() # 插入默认通知方式 notis = Notification.query.all() mail_exist = False wechat_exist = False if len(notis) != 0: for noti in notis: if noti.type == 'mail': mail_exist = True if noti.type == 'wechat': wechat_exist = True if not mail_exist: mail_noti = Notification('mail') db.session.add(mail_noti) db.session.commit() if not wechat_exist: wechat_noti = Notification('wechat') db.session.add(wechat_noti) db.session.commit() # 在系统重启时重启任务 from app.main.scheduler import add_job task_statuss = TaskStatus.query.all() count = 0 for task_status in task_statuss: if task_status.task_status == 'run': count += 1 task_id = task_status.task_id if task_status.task_type == 'html': task = Task.query.filter_by(id=task_id).first() add_job(task.id, task.frequency) logger.info('重启task_' + str(task_id)) elif task_status.task_type == 'rss': task = RSSTask.query.filter_by(id=task_id).first() add_job(task_id, task.frequency, 'rss') logger.info('重启task_rss' + str(task_id)) logger.info('重启{}个任务'.format(count)) return app
def email_a_review(): current_app.logger.debug('emailing review for a draft') if 'did' in request.form and 'uid' in request.form and 'email' in request.form: did = request.form['did'] uid = request.form['uid'] email = request.form['email'] draft = Draft.query.filter_by(did=did).first() if not draft or draft.uid != g.user.uid: return jsonify(error="Invalid draft"), 400 if not validate_email(email, check_mx=True): return jsonify(error="Invalid email"), 400 # create review pointing to the draft review = Review() review.did = draft.did review.email = email # really good code to generate a unique url hash for the review unique_hash = False gen_hash = '' while not unique_hash: gen_hash = uuid.uuid4().hex queried_review = Review.query.filter_by(urlhash=gen_hash).first() if not queried_review: unique_hash = True review.urlhash = gen_hash db.session.add(review) # if the draft was not finalized, finalize it and create a new one new_did = None new_version = None new_timestamp = None if not draft.finalized: draft.finalized = True db.session.add(draft) db.session.flush() # make a new draft for the writer new_draft = Draft.next_draft(draft) db.session.add(new_draft) db.session.flush() new_did = new_draft.did new_version = new_draft.version new_timestamp = new_draft.pretty_modified_date() else: db.session.flush() review_url = 'http://' + app.config.get('SERVER_HOST') + '/essays/review/' + review.urlhash # send emailz params = { 'sender': g.user.first_name + ' ' + g.user.last_name, 'review_url': review_url } mailer = Mailer() mailer.send(ReviewADraft(), params, email) # create notification for user receiving review if necessary receiving_user = User.query.filter_by(email=email).first() if receiving_user: notification = Notification() notification.uid = receiving_user.uid notification.from_uid = uid notification.short_template = 'requested a review.' notification.url = review_url notification.long_template = '{{ sender }} wrote an essay and wants you to <a href="' + review_url +'"> review </a> it.' db.session.add(notification) db.session.commit() return jsonify(status='success', new_did=new_did, new_version=new_version, new_timestamp=new_timestamp ) else: return jsonify(error="Bad params"), 400
def create_app(config_name): from config import config, logger app.config.from_object(config[config_name]) # 中文化 Babel(app) # 注册flask-login login.init_app(app) # bootstrap bootstrap.init_app(app) @login.user_loader def load_user(user_id): return User.query.get(user_id) # 注册蓝图 from app.main.views import bp as main_bp app.register_blueprint(main_bp) # 注册数据库 db.init_app(app) # 注册flask-admin admin.init_app( app, index_view=AdminIndexView(template='admin/index.html', url='/')) # 注册APScheduler scheduler.init_app(app) scheduler.start() # 视图 from app.models.task import Task from app.models.rss_task import RSSTask from app.models.mail_setting import MailSetting from app.models.notification import Notification from app.models.task_status import TaskStatus from app.models.user import User admin.add_view(TaskStatusView(TaskStatus, db.session, name='任务状态')) admin.add_view(TaskView(Task, db.session, name='网页监控任务管理')) admin.add_view(RSSTaskView(RSSTask, db.session, name='RSS监控任务管理')) admin.add_view(NotificationView(Notification, db.session, name='通知方式管理')) admin.add_view(MailSettingView(MailSetting, db.session, name='系统邮箱设置')) admin.add_view(UserView(User, db.session, name='账号密码管理')) with app.test_request_context(): db.create_all() mail_setting = MailSetting.query.first() # 插入默认邮箱配置 if mail_setting is None: mail_setting = MailSetting() db.session.add(mail_setting) db.session.commit() # 初始化账号密码 user = User.query.first() if user is None: import random import string random_password = ''.join( random.sample(string.ascii_letters + string.digits, 10)) logger.info('数据库初始化成功,初始密码为' + random_password) user = User('admin', random_password) db.session.add(user) db.session.commit() # 插入默认通知方式 notis = Notification.query.all() mail_exist = False wechat_exist = False if len(notis) != 0: for noti in notis: if noti.type == 'mail': mail_exist = True if noti.type == 'wechat': wechat_exist = True if not mail_exist: mail_noti = Notification('mail') db.session.add(mail_noti) db.session.commit() if not wechat_exist: wechat_noti = Notification('wechat') db.session.add(wechat_noti) db.session.commit() ppid = psutil.Process(os.getppid()) ppid_name = ppid.name() # 加这一步判断主要是因为, # 在debug模式下,会启动另外一个线程来自动重载, # 这样会导致在两个线程中都启动任务,造成重复 if ('python' in ppid_name and config_name == 'development') or config_name != 'development': # 在系统重启时重启任务 from app.main.scheduler import add_job task_statuss = TaskStatus.query.all() count = 0 for task_status in task_statuss: if task_status.task_status == 'run': count += 1 task_id = task_status.task_id if task_status.task_type == 'html': task = Task.query.filter_by(id=task_id).first() add_job(task.id, task.frequency) logger.info('重启task_' + str(task_id)) elif task_status.task_type == 'rss': task = RSSTask.query.filter_by(id=task_id).first() add_job(task_id, task.frequency, 'rss') logger.info('重启task_rss' + str(task_id)) logger.info('重启{}个任务'.format(count)) return app