def message(self, request, db_session, clean_channel_repo, clean_notifications_repo): self.db_session = db_session self.message1 = Message(payload={"receiver": "AU"}) self.message2 = Message(payload={"receiver": "AU"}) with freeze_time('2020-06-17 12:04:01.111111'): messages = [ self.message1, self.message2, Message(payload={"receiver": "SG"}), ] for m in messages: self.db_session.add(m) self.db_session.commit() with freeze_time('2020-06-17 12:04:03.111111'): messages = [ Message(payload={"receiver": "SG"}), ] for m in messages: self.db_session.add(m) self.message1.status = MessageStatus.REVOKED self.db_session.commit() self.channel_repo = clean_channel_repo self.notifications_repo = clean_notifications_repo self.use_case = NewMessagesNotifyUseCase('AU', clean_channel_repo, clean_notifications_repo)
def checkUpload(): """ 检查上传截图是否过期 :return: """ now = datetime.datetime.now() start = now - datetime.timedelta(minutes=30) #半个小时之外,并且到上传截图这步骤 oas = OrderApply.objects.filter(update_time__lte=start,finished=0,teacher_willing=2,parent_willing=2) for oa in oas: try: with transaction.atomic(): #没有上传截图,当做老师拒绝操作 oa.finished =1 oa.teacher_willing = 0 oa.save() #给老师发送消息,老师过期 message_title = u"你的订单已过期,没有在相应的时间内上传截图!" message_content = u"你的订单已过期,没有在相应的时间内上传截图!" #应该是管理员发送 message = Message(sender=oa.tea.wechat, receiver=oa.tea.wechat, message_title=message_title, message_content=message_content,status=0) message.save() #老家长发送消息,审核不通过 message_title = u"订单审核不通过!" message_content = u"订单审核不通过!" message = Message(sender=oa.tea.wechat, receiver=oa.pd.wechat, message_title=message_title, message_content=message_content,status=0) message.save() #推送到微信端 except Exception,e: print e.message
def setUp(self): """ Set up test application. """ self.app = create_app('testing') self.client = self.app.test_client() self.client.headers = {'Authorization': getenv('TEST_TOKEN')} self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() self.board1 = Board() self.board2 = Board() self.conversation1 = Conversation() self.conversation2 = Conversation() self.deposit1 = Deposit() self.deposit2 = Deposit() self.estate1 = Estate(address="Random Address 1") self.estate2 = Estate(address="Random Address 2") self.estate3 = Estate() self.headers = {'Authorization': getenv('TEST_TOKEN')} self.message1 = Message(sender=1, content='Random Content') self.message2 = Message(sender=2, content='Random Content') self.message3 = Message() self.payment1 = Payment() self.payment2 = Payment() self.role1 = Role(title='basic') self.role2 = Role(title='admin') self.role3 = Role(title='super_admin') self.role4 = Role() self.unit1 = Unit(name="Random Unit 1") self.unit2 = Unit(name="Random Unit 2") self.unit3 = Unit() self.user1 = User(name="First1 Middle1 Last1", phone_number="000 12 3456781", email="*****@*****.**", password=digest('ABC123!@#')) self.user2 = User(name="First2 Middle2 Last2", phone_number="000 12 3456782", email="*****@*****.**", password=digest('ABC123!@#')) self.user3 = User() self.user_new_data1 = {'phone_number': "000 12 3456783"} self.user_new_data2 = {'bad_field': "random"} self.wallet1 = Wallet() self.wallet2 = Wallet() self.user1_dict = { "name": "First1 Middle1 Last1", "phone_number": "000 12 3456781", "email": "*****@*****.**", "password": "******" } self.conversation3_dict = {"participants": [1, 2]} self.message4_dict = {"content": "New Message."} self.board3_dict = {'members': [1, 2]}
def test_list_all_messages(self): Message.objects.bulk_create([ Message(content='message1'), Message(content='message2'), Message(content='message3'), ]) response = self.client.get(f'{self.BASE_URL}/messages', **self.bearer_token) self.assertEqual(response.status_code, HTTP_200_OK) self.assertEqual(len(response.json()), 3)
def test_asctime(self): message = Message() dt = datetime.datetime(2016, 10, 22, 10, 16, 40) message.date = dt asctime = message.get_asctime() self.assertEqual(asctime, "Sat Oct 22 10:16:40 2016") message = Message() dt = datetime.datetime(2016, 10, 22, 9, 6, 4) message.date = dt asctime = message.get_asctime() self.assertEqual(asctime, "Sat Oct 22 9:06:04 2016")
def post(self, conversation_id): """ Send a message into a conversation. """ payload = request.get_json() required = ['content'] result = validate_json(required, payload, empty=True) if isinstance(result, bool) is False: return { 'status': 'fail', 'message': 'Content required for a message.' }, 400 else: current_user_id = current_user_id = view_token( request.headers.get('Authorization'))['id'] message = Message(sender=current_user_id, content=payload['content']) conversation = Conversation.get(id=conversation_id) conversation.insert('messages', [message]) return { 'status': 'success', 'data': { 'updated_conversation': conversation.view() } }, 201
def test_put_message(when, client): source = Source(name="test_5", environment="env_5", encoding="encoding_5") run.db.session.add(source) run.db.session.commit() assert source.id source_id = source.id message = Message(source_id=source_id, message="message_5", status="status_5") run.db.session.add(message) run.db.session.commit() assert message.id message_id = message.id res = client.put( url_for("put_message", id=message_id, _method="PUT"), json={"message": "message_5_updated"}, ) assert res.status == "200 OK" assert res.json["message"] == "message_5_updated" assert "id" in res.json and res.json["id"] assert ("created_at" in res.json and res.json["created_at"] == message.created_at.replace(tzinfo=timezone.utc).isoformat()) assert "updated_at" in res.json and res.json["updated_at"]
def remindFeedBack(request): """ 提醒某个用户提交反馈 :param request: :return: """ id = request.data.get('id',None) userType = request.data.get('user',None) user = AuthUser.objects.get(username=request.user.username) message_title = u"好学吧家教邀请您填写反馈意见!" message_content = u"好学吧家教邀请您填写反馈意见!" if userType == "parent": objs = ParentOrder.objects.filter(pd_id = id) elif userType == "teacher": objs = Teacher.objects.filter(tea_id = id) else: return JsonError(u"输入数据的user值不对") if len(objs): obj = objs[0] now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) message = Message(sender=user, receiver=obj.wechat, message_title=message_title, message_content=message_content,status=0,update_time=now,create_time=now) message.save() return JsonResponse() else: return JsonError(u"找不到用户!")
def test_get_message_status__when_exist__should_return_delivered(self): message = self.channel_repo.save_message(Message(payload={'obj': 'test'})) url = url_for('views.get_message', id=str(message.id)) response = self.client.get(f'{url}?fields=status') assert response.status_code == 200 assert response.json == {'status': 'received'}
def test_1_day(self): from api.models import Message message = Message() dt = datetime.datetime.fromtimestamp(time.time() - 3600 * 25) message.date = dt age = message.get_age() self.assertEqual(age, "1 day")
def get_replies(flyer_id): data = request.get_json() logger.info("Data recieved: %s", data) if "sender" not in data: msg = "No sender provided for reply." logger.info(msg) return create_response(status=422, message=msg) flyer = SearchFlyer.query.get(flyer_id) sender = data['sender'] data['content'] = f'{sender} se quiere contactar con vos por tu aviso.' data['flyer_id'] = flyer_id data['recipient'] = flyer.created_by data['status'] = 'sent' # create SQLAlchemy Object message = Message(**data) # commit it to database db.session.add_all([message]) db.session.commit() submit_notification( flyer.created_by, { 'title': '¡Respondieron tu aviso!', 'body': f'{sender} se quiere contactar con vos por tu aviso.', 'flyer_id': flyer_id }) return create_response( message=f"Successfully created message with id: {message.id}", data={"message": message.to_dict()})
def handle(self, *args, **options): end = date2timestamp(now().date()) start = end - 86400 instances = Instance.objects.values_list('cluster_id', 'owner_id', 'app_id'). \ filter(timestamp__gte=start, timestamp__lt=end).order_by('owner_id'). \ annotate(Count('app_id')) for instance in instances: config_fee(instance, start, end) volume_fee(instance, start, end) network_fee(instance, start, end) fs = Funding.objects.distinct('owner_id').filter(credit__lt=0).order_by( 'owner_id', '-created').values_list('owner_id', 'credit') msgs = [] for f in fs: msg_data = { 'owner_id': f[0], 'code': 2, 'sender': 'system', 'body': 'You are in arrears, please recharge in time.', } msg = Message( **msg_data ) msgs.append(msg) Message.objects.bulk_create(msgs) self.stdout.write("done")
def post_message(): """ Post a new message endpoint --- post: requestBody: content: application/json: schema: MessagePayloadSchema responses: 201: description: Returns message id content: application/json: schema: PostedMessageSchema """ schema = MessagePayloadSchema() try: schema.load(request.json) except ValidationError as e: return JsonResponse(e.messages, status=400) message = Message(payload=request.json) db.session.add(message) db.session.commit() return_schema = PostedMessageSchema() return JsonResponse(return_schema.dump(message), status=201)
def post(self: View, request: HttpRequest, slug: str) -> JsonResponse: """Add a new message to the specified room.""" payload = json.loads(request.body.decode()) content = str(payload.get('content', '')) if not 1 <= len(content) <= 256: return error('Content length must be between 1 and 256.') if not request.session.get('registered'): return error('You are not registered.') room = Room.objects.filter(slug=slug).first() if room is None: return error('That room does not exist.') message = Message( author=request.session.get('username'), content=content, room=room ) message.save() return JsonResponse({ 'success': True, 'message': { 'content': message.content, 'author': message.author } })
def sendPhone(request): """ 发送联系方式给某个老师 :param request:{"tea_id":1,"tel":18812345678,"oa_id":3} :return: """ tea_id = request.data.get('tea_id',None) oa_id = request.data.get('oa_id',None) tel = request.data.get('tel',None) teas = Teacher.objects.filter(tea_id=tea_id) oas = OrderApply.objects.filter(oa_id=oa_id) user = AuthUser.objects.get(username=request.user.username) if len(teas) and len(oas): tea = teas[0] oa = oas[0] pd_name = oa.pd.name message_title = u"向您发送了" + pd_name +u"家长的联系方式!" message_content = pd_name + u"家长的联系方式是" + str(tel) now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) message = Message(sender=user, receiver=tea.wechat, message_title=message_title, message_content=message_content,status=0,update_time=now,create_time=now) message.save() oa.tel = str(tel) oa.finished = 1 oa.save() return JsonResponse() else: return JsonError(u"输入数据有误")
def test_0_second(self): from api.models import Message message = Message() message.date = datetime.datetime.utcnow() age = message.get_age() self.assertEqual(age, "0 second")
def handle(self, *args, **kwargs): if len(Message.objects.all()) == 0: nowID = Message(stopID=15753) else: nowID = Message.objects.all()[0] tokens = AccessToken.objects.all() url = "http://www.ttsh.tp.edu.tw/module.php?i=news&cat_id=2&start=0" html = requests.get(url) soup = BeautifulSoup(html.text, 'html.parser') className = 'list-group-item' newsLists = soup.find_all('a', {'class': className}) newsLists = newsLists[3:] for i in range(len(newsLists)): x, newsdict = newsLists[i], dict() newsdict['link'] = "http://www.ttsh.tp.edu.tw" + x['href'][1:] query = urlparse.urlsplit(newsdict['link']).query newsdict['id'] = int(urlparse.parse_qs(query)['news_id'][0]) className = 'title' title = x.find('span', {'class': className}) newsdict['title'] = title.get_text(strip=True) newsLists[i] = newsdict second = True newsLists.reverse() for x in newsLists: if x['id'] <= nowID.stopID: continue nowID.message = x['title'] nowID.stopID = x['id'] if second: tokens = AccessToken.objects.all() second = False status = self.send_pro(x['title'] + "\n" + x['link'], tokens) if status is not None: print(status) nowID.save()
def test_now(self): from api.models import Message message = Message() dt = datetime.datetime.fromtimestamp(time.time() + 100) message.date = dt age = message.get_age() self.assertEqual(age, "now")
def post_message(): message = Message(message=json.loads(request.data)) channel_repo = ChannelRepo(current_app.config['CHANNEL_REPO_CONF']) channel_queue_repo = ChannelQueueRepo(current_app.config['CHANNEL_QUEUE_REPO_CONF']) use_case = ReceiveMessageUseCase(channel_repo, channel_queue_repo) use_case.receive(message) message_data = message.to_dict() return JsonResponse(message_data, status=200)
def test_message__can_be_created(db_session): message = Message(id=42, payload={"sender": "AU"}) db_session.add(message) db_session.commit() message = db_session.query(Message).get(42) assert message.status == MessageStatus.CONFIRMED assert message.payload == {"sender": "AU"} assert message.created_at == datetime(2020, 4, 7, 14, 21, 22, 123456)
def create_message(id, user_id, date, text): message = Message() message.id = id message.user_id = user_id message.date = date message.text = text message.save() return message
def post_message(): message_json = request.get_json() message = Message( source_id=message_json.get("source_id"), message=message_json.get("message"), status=message_json.get("status"), ) db.session.add(message) db.session.commit() return message_schema.jsonify(message)
def create_message(user_id: int, args: dict): message = Message(**args) db.session.add(message) db.session.commit() return jsonify({ "success": True, "data": message_schema.dump(message) }), 201
def messages(request): if request.method == 'GET': return JsonResponse( [message.serialize() for message in Message.objects.all()], safe=False) else: data = request.POST message = Message(author=data['author'], content=data['content']) message.save() return JsonResponse(message.serialize(), safe=False)
def create(self, request, *args, **kwargs): """ parameters: 'recipientID', 'textFirstMessage' """ for parameter in ['recipientID', 'textFirstMessage']: if parameter not in request.data: print(3333) return Response(status=status.HTTP_400_BAD_REQUEST) recipientID = request.data['recipientID'] textFirstMessage = request.data['textFirstMessage'] querysetDialogsUser = list() querysetDialogsRecipient = list() #exist dialog? for item in DialogOwners.objects.filter(owner=request.user): querysetDialogsUser.append(item.dialog) for item in DialogOwners.objects.filter(owner=User.objects.get(id=recipientID)): querysetDialogsRecipient.append(item.dialog) #if dialog exist for item in querysetDialogsUser: if querysetDialogsRecipient.count(item) != 0: return Response(status=status.HTTP_400_BAD_REQUEST) dialog = Dialog() dialog.save() message = Message() message.owner = request.user message.ownerDialog = dialog message.text = textFirstMessage message.date = timezone.now() message.save() dialog.textLastMessage = textFirstMessage dialog.dateLastMessage = message.date dialog.idLastMessage = message.id dialog.save() dialogOwner1 = DialogOwners() dialogOwner2 = DialogOwners() dialogOwner1.owner = request.user dialogOwner1.dialog = dialog dialogOwner2.owner = User.objects.get(id=recipientID) dialogOwner2.dialog = dialog dialogOwner1.save() dialogOwner2.save() #data = [{ 'id':dialog.id }] return Response(status=status.HTTP_201_CREATED)
def incoming_message(): message = Message(message=json.loads(request.data)) logger.debug("Received message %r", message.message) channel_repo = ChannelRepo(current_app.config['CHANNEL_REPO_CONF']) channel_repo.save_message(message) notifications_repo = NotificationsRepo(current_app.config['NOTIFICATIONS_REPO_CONF']) use_case = use_cases.PublishNewMessageUseCase(current_app.config['JURISDICTION'], notifications_repo) use_case.publish(message) return JsonResponse({ 'status': 'delivered', 'id': message.id, }, status=200)
def create_message(helper_portfolio_manager, helper_field_partner, to_fp, helper_doc, description): temp_message = Message({ "pm_id": helper_portfolio_manager.id, "fp_id": helper_field_partner.id, "to_fp": to_fp, "doc_id": helper_doc.id, "description": description, }) db.session.add(temp_message) return temp_message
def test_get_message__when_exist__should_return_it(client, db_session): message = Message(id=42, payload={"sender": "AU"}) db_session.add(message) db_session.commit() response = client.get(url_for('views.get_message', id=42)) assert response.status_code == 200 assert response.json == { 'id': 42, 'status': 'confirmed', 'message': { 'sender': 'AU' } }
def post(self, request): data = parsers.JSONParser().parse(request) try: jwt.decode(data['auth_token'], 'secret', algorithm='HS256') except jwt.InvalidSignatureError: return HttpResponse('Unathorized', status=401) message = Message( user_id=UserAuthen.objects.get(token=data['auth_token']).user_id, text=data['text']) try: message.save() except db.IntegrityError: return HttpResponse('Conflict', status=409) return HttpResponse('OK', status=200)
def post_message(): """ --- post: servers: - url: https://sharedchannel-c1.services.devnet.trustbridge.io/ description: Post a new message endpoint requestBody: content: application/json: schema: MessagePayloadSchema example: sender: AU receiver: CN subject: AU.abn0000000000.XXXX-XXXXX-XXXXX-XXXXXX obj: QmQtYtUS7K1AdKjbuMsmPmPGDLaKL38M5HYwqxW9RKW49n predicate: UN.CEFACT.Trade.CertificateOfOrigin.created responses: 201: description: Returns message id content: application/json: schema: PostedMessageSchema example: id: 1 """ schema = MessagePayloadSchema() try: schema.load(request.json) except marshmallow.ValidationError as e: return JsonResponse(e.messages, status=400) message = Message(payload=request.json) db.session.add(message) db.session.commit() return_schema = PostedMessageSchema() notifications_repo = NotificationsRepo( current_app.config['NOTIFICATIONS_REPO_CONF']) use_case = use_cases.PublishStatusChangeUseCase(notifications_repo) use_case.publish(message) hub_url = current_app.config['HUB_URL'] topic = use_cases.PublishStatusChangeUseCase.get_topic(message) headers = {'Link': f'<{hub_url}>; rel="hub", <{topic}>; rel="self"'} return JsonResponse(return_schema.dump(message), status=201, headers=headers)