Ejemplo n.º 1
0
def send_mail(email, subject, body):

    try:
        msg = Message(
            subject=subject,
            sender='*****@*****.**',
            recipients=[email],
        )
        msg.body = body

        mail.send(msg)

    except Exception:
        raise RuntimeError('Something went wrong while sending email message.')
Ejemplo n.º 2
0
 def execute(community_id, date_range):
     date_filter = {'gte': date_range.start, 'lte': date_range.end}
     response = Message.search() \
         .filter('range', date=date_filter) \
         .filter('match', community=community_id) \
         .execute()
     messages = [message.text for message in response]
     g = analysis.TextacyKeywordExtractor().get_keyword_graph(messages)
     return g
Ejemplo n.º 3
0
def decode_message(msg):
    msg_dict = yaml.safe_load(msg)
    m = Message(msg_dict["mtype"], msg_dict["request_id"], msg_dict["client_id"], msg_dict["client_request_id"], msg_dict["sender_id"], msg_dict["value"], msg_dict["received_propose_list"])
    '''
    if m.request_id != None: m.request_id = int(m.request_id)
    if m.sender_id != None: m.sender_id = int(m.sender_id)
    if m.client_id != None: m.client_id = int(m.client_id)
    if m.client_request_id != None: m.client_request_id = int(m.client_request_id)
    if m.mtype != None: m.mtype = int(m.mtype)
    '''
    return m
Ejemplo n.º 4
0
 def execute():
     s = Message.search()
     s.aggs.bucket('communities', 'terms', field='community')
     communities = [
         hit['key'] for hit in s.execute().aggregations.communities.buckets
     ]
     # hack to get rid of the r returned by the query
     return [{
         'identifier': c,
         'displayName': c
     } for c in communities if c != 'r']
Ejemplo n.º 5
0
 def on_get(self, request, response):
     community = request.get_param('community')
     term = request.get_param('term')
     r = Message.search() \
         .filter('match', community=community) \
         .filter('match', text=term) \
         .highlight('text', fragment_size=80) \
         .execute()
     highlights = [
         fragment for hit in r for fragment in hit.meta.highlight.text
     ]
     response.body = json.dumps(highlights)
Ejemplo n.º 6
0
 def handle_IAmYourLeader(self, m):
     if self.debug:
         print 'handle_IAmYourLeader', m
     # if sender_id > view, update self.view
     # send YouAreMyLeader back with message = jsonify received_propose_list
     if m.sender_id >= self.view:
         self.view = m.sender_id
         msg = Message(1, None, None, None, self.uid, None,
                       self.received_propose_list)
         print 'Recieve I Am Your Leader!', msg.sender_id, msg.client_id, msg.client_request_id
         #print self.ports_info[self.view][0],self.ports_info[self.view][1]
         send_message(self.ports_info[self.view][0],
                      self.ports_info[self.view][1], encode_message(msg))
Ejemplo n.º 7
0
 def _data_deal(cls, args, *a):
     phoneNum = args['phoneNum']
     data = {
         'status': 0,
         'msg': ''
     }
     status = Message.send_message(phoneNum)
     if status == 0:
         data['status'] = 1
         data['msg'] = '发送成功'
     elif status == 1:
         data['msg'] = '您输入的手机号码格式有误,请重新输入'
     elif status == 2:
         data['msg'] = '您当前操作频繁,请稍后再试'
     elif status == 3:
         data['msg'] = '抱歉,您当日验证失败次数已达上限,请于次日重试'
     return data
Ejemplo n.º 8
0
    def execute(community_id, date_range, interval):
        date_filter = {'gte': date_range.start, 'lte': date_range.end}
        s = Message.search().filter('range', date=date_filter)\
            .filter('match', community=community_id)
        s.aggs \
            .bucket(
                'activity',
                'date_histogram',
                field='date',
                min_doc_count=0,
                interval=interval) \
            .metric('score', 'avg', field='score') \
            .metric('positive', 'avg', field='positive') \
            .metric('negative', 'avg', field='negative') \
            .metric('neutral', 'avg', field='neutral')

        response = s.execute()
        return response.aggregations.activity.buckets
Ejemplo n.º 9
0
 def _data_deal(cls, args, *a):
     phone = args['phoneNum']
     code = args['code']
     password = args['password']
     data = {
         'status': 0,
         'msg': ''
     }
     status = Message.verify_message(phone, code)
     if status == 0:
         user = User.query.filter(User.phoneNum == phone).first()
         if user:
             user.password = password
             db.session.commit()
             data['msg'] = '修改成功'
             data['status'] = 1
         else:
             data['msg'] = '没有找到该用户,请检查号码后重试'
     else:
         data['msg'] = '验证码错误, 请重试'
     return data
Ejemplo n.º 10
0
 def handle_ProposeValue(self, m):
     if self.debug:
         print 'handle_ProposeValue', m.client_id, m.client_request_id
     # if sender_id > view, update view & update
     #   update received_propose_list
     #   broadcast AcceptValue(proposorid + req_id + value)
     if m.sender_id >= self.view:
         if self.debug:
             print 'handle_ProposeValue', m.client_id, m.client_request_id
         self.view = m.sender_id
         if self.debug:
             print 'handle_ProposeValue', m.client_id, m.client_request_id
         self.received_propose_list[m.request_id] = [
             m.client_id, m.sender_id, m.value, m.client_request_id
         ]
         if self.debug:
             print 'handle_ProposeValue', m.client_id, m.client_request_id
         msg = Message(3, m.request_id, m.client_id, m.client_request_id,
                       self.uid, m.value, None)
         if self.debug:
             print 'handle_ProposeValue', m.client_id, m.client_request_id
         self.broadcast_msg(encode_message(msg))
         if self.debug:
             print 'handle_ProposeValue', m.client_id, m.client_request_id
Ejemplo n.º 11
0
 def execute(community_ids, date_range, interval, search_terms):
     date_filter = {'gte': date_range.start, 'lte': date_range.end}
     results = []
     for term in search_terms:
         responses = []
         for _id in community_ids:
             s = Message.search() \
                 .query('match', text=term) \
                 .filter('range', date=date_filter) \
                 .filter('match', community=_id)
             s.aggs.bucket('activity',
                           'date_histogram',
                           field='date',
                           interval=interval)
             response = s.execute()
             responses.append({
                 'community':
                 _id,
                 'activity':
                 map(lambda r: r.to_dict(),
                     response.aggregations.activity.buckets)
             })
         results.append({'term': term, 'data': responses})
     return results
Ejemplo n.º 12
0
    def handle_YouAreMyLeader(self, m):
        #if self.debug:
        print 'handle_YouAreMyLeader', m.sender_id, m.client_id, m.client_request_id
        # update the most recent value for each blank in received_propose_list.
        self.num_followers += 1
        for key in m.received_propose_list.keys():
            x = m.received_propose_list[key]
            key = int(key)
            # if update every value to the newest proposer value
            if key not in self.received_propose_list.keys():
                print key, x
                self.received_propose_list[key] = x
            elif x[1] > self.received_propose_list[key][1]:
                self.received_propose_list[key] = x

        if self.num_followers == self.f + 1:
            #   fill the holes with NOOP
            #print "replica %d becomes leader!!! view %d" % (self.uid , self.view)
            if len(self.received_propose_list) > 0:
                for i in range(0,
                               max(self.received_propose_list.keys(),
                                   key=int)):
                    if not i in self.received_propose_list:
                        self.received_propose_list[i] = [
                            -1, self.uid, "NOOP", None
                        ]
            #print "replica %d becomes leader!!! view %d" % (self.uid , self.view)
            #print 'length:', len(self.received_propose_list.keys())
            #for key in self.received_propose_list.keys():
            #    print key , self.received_propose_list[key]
            #print self.received_propose_list
            #   propose everything in the list
            for key in self.received_propose_list.keys():
                x = self.received_propose_list[key]
                msg = Message(2, key, x[0], x[3], self.uid, x[2], None)
                #print key
                self.broadcast_msg(encode_message(msg))
                #print key
                if x[2] != 'NOOP':
                    self.request_mapping[(x[0], x[3])] = int(key)
            print "replica %d becomes leader!!! view %d" % (self.uid,
                                                            self.view)
            print len(self.waiting_request_list)
            #   propose everything in waiting_request_list
            while len(self.waiting_request_list) != 0:
                m = self.waiting_request_list.pop(0)
                if (m.client_id, m.client_request_id
                    ) not in self.request_mapping.keys():
                    # edit message
                    m.sender_id = self.uid
                    #req_id is next index in request_mapping
                    if len(self.request_mapping) == 0: req_id = 0
                    else: req_id = max(self.request_mapping.values()) + 1
                    m.request_id = req_id
                    # change message type to proposeValue
                    m.mtype = 2
                    # encode message
                    msg = encode_message(m)
                    # broadcast message
                    self.broadcast_msg(msg)
                    # add req_id to mapping list
                    self.request_mapping[(m.client_id,
                                          m.client_request_id)] = req_id
        print 'handle_YouAreMyLeader', m.sender_id, m.client_id, m.client_request_id
Ejemplo n.º 13
0
 def beProposor(self):
     self.num_followers = 0
     self.request_mapping = {}
     msg = Message(0, None, None, None, self.uid, None, None)
     self.broadcast_msg(encode_message(msg))
Ejemplo n.º 14
0
 def send_response_to_client(self, client_id, client_request_id):
     # client_id = self.received_propose_list[req_id][0]
     # client_request_id = self.received_propose_list[req_id][3]
     msg = Message(6, None, None, client_request_id, None, None, None)
     send_message(self.client_ports_info[client_id][0],
                  self.client_ports_info[client_id][1], encode_message(msg))
Ejemplo n.º 15
0
    def _data_deal(cls, args, *a):
        phoneNum = args['phoneNum']
        password = args['password']
        data = {'status': 0, 'user': {}, 'msg': '验证码错误'}
        status = Message.verify_message(phoneNum, password)
        if status == 0:
            user = User.query.filter(
                or_(User.phoneNum == phoneNum, User.username == phoneNum,
                    User.email == phoneNum)).first()
            if user:
                old_token = user.token
                user.token = str(uuid.uuid4()).replace('-', '')
                AccountLogin.set_cache(user, old_token)
            else:
                username = '******' + phoneNum
                new_user = User(username, phoneNum)
                new_user.username = username
                new_user.token = str(uuid.uuid4()).replace('-', '')
                user = new_user
                db.session.add(new_user)
                user_info = {
                    'phoneNum':
                    phoneNum,
                    'coupons': {},
                    'integral': {
                        'count': 0,
                        'record': []
                    },
                    'collect_goods': [],
                    'collect_store': [],
                    'wish': {},
                    'daily_lottery': {},
                    'sign_lottery':
                    0,
                    'default':
                    '',
                    'address': {},
                    'info_count':
                    0,
                    'info_list': [],
                    "message_setting": [[{
                        "type_id": "15",
                        "type_name": "接收新消息通知",
                        "status": 1
                    }],
                                        [{
                                            "type_id": "1",
                                            "type_name": "小美通知",
                                            "status": 1
                                        }, {
                                            "type_id": "2",
                                            "type_name": "交易物流",
                                            "status": 1
                                        }, {
                                            "type_id": "4",
                                            "type_name": "收货评价",
                                            "status": 1
                                        }, {
                                            "type_id": "8",
                                            "type_name": "粉丝",
                                            "status": 1
                                        }, {
                                            "type_id": "10",
                                            "type_name": "点赞",
                                            "status": 1
                                        }, {
                                            "type_id": "12",
                                            "type_name": "评论",
                                            "status": 1
                                        }],
                                        [{
                                            "type_id": "13",
                                            "type_name": "直播通知",
                                            "status": 1
                                        }],
                                        [{
                                            "type_id": "14",
                                            "type_name": "开售提醒",
                                            "status": 1
                                        }]]
                }
                mongo[cls.collect_set].insert(user_info)
                AccountLogin.set_cache(user, '')

            db.session.commit()
            SetIntegral.integral_deal(user.phoneNum, 1, 0, cls.last_timestamp)
            data['status'] = 1
            data['user'] = {
                'token': user.token,
                'username': user.username,
                'header': user.header,
                'phoneNum': user.phoneNum
            }
            data['msg'] = '登录成功'
        elif status == 2:
            data['msg'] = '您当前操作频繁,请稍后再试'
        elif status == 3:
            data['msg'] = '抱歉,您当日验证失败次数已达上限,请于次日重试'
        return data