예제 #1
0
파일: ecbusiness.py 프로젝트: jcsy521/ydws
    def post(self, ecmobile):
        """Modify a business.
        """
        fields = DotDict(ecname=" name = '%s'",
                         ecmobile=" mobile = '%s'",
                         linkman="linkman = '%s'",
                         address="address = '%s'",
                         email="email = '%s'",
                         bizcode="bizcode = '%s'",
                         type="type = '%s'")

        for key in fields:
            v = self.get_argument(key, None)
            if v is not None:
                # if not check_sql_injection(v):
                # call get method
                #   self.get(tmobile)
                #   return
                fields[key] = fields[key] % v
            else:
                fields[key] = None
        set_cmd = ', '.join([v for v in fields.itervalues()
                             if v is not None])

        sql = "UPDATE T_CORP SET " + set_cmd + " WHERE mobile = %s" % ecmobile
        self.db.execute(sql)

        self.redirect("/ecbusiness/list/%s" % ecmobile)
예제 #2
0
파일: line.py 프로젝트: jcsy521/ydws
    def get(self):
        """ """ 
        status = ErrorCode.SUCCESS
        try:
            page_number = int(self.get_argument('pagenum'))
            page_count = int(self.get_argument('pagecnt'))
            #reserved API
            fields = DotDict(name="name LIKE '%%%%%s%%%%'")
            
            for key in fields.iterkeys():
                v = self.get_argument(key, None)
                if v:
                    if not check_sql_injection(v):
                        status = ErrorCode.SELECT_CONDITION_ILLEGAL
                        self.write_ret(status)
                        return  
                    fields[key] = fields[key] % (v,)
                else:
                    fields[key] = None
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] cid: %s get line data format illegal. Exception: %s", 
                              self.current_user.cid, e.args) 
            self.write_ret(status)
            return
        
        try:
            where_clause = ' AND '.join([v for v in fields.itervalues()
                                         if v is not None])
            page_size = UWEB.LIMIT.PAGE_SIZE
            if where_clause:
                where_clause = ' AND ' + where_clause
            if page_count == -1:
                sql = "SELECT count(id) as count FROM T_LINE" + \
                      "  WHERE 1=1 " + where_clause
                sql += " AND cid = %s" % (self.current_user.cid,)
                res = self.db.get(sql) 
                count = res.count
                d, m = divmod(count, page_size)
                page_count = (d + 1) if m else d

            sql = "SELECT id AS line_id, name AS line_name FROM T_LINE" +\
                  "  WHERE 1=1 " + where_clause
            sql += " AND cid = %s LIMIT %s, %s" % (self.current_user.cid, page_number * page_size, page_size)
            lines = self.db.query(sql)
            for line in lines:
                stations = self.db.query("SELECT name, latitude, longitude, seq "
                                         "  FROM T_STATION "
                                         "  WHERE line_id = %s",
                                         line.line_id)
                line["stations"] = stations
                
            self.write_ret(status,
                           dict_=DotDict(lines=lines,
                                         pagecnt=page_count))
        except Exception as e:
            logging.exception("[UWEB] cid: %s get line failed. Exception: %s", 
                              self.current_user.cid, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #3
0
파일: public.py 프로젝트: jcsy521/ydws
def update_operator(operator, oid, db, redis):
    """Update operator status.

    :arg operator: dict, e.g.

        {
          'address':'',
          'email':'',          
        }

    :arg oid: string
    :arg db: database instance
    :arg redis: redis instance

    """
    set_clause_dct = DotDict()
    fields = DotDict(address="address = '%s'",
                     email="email = '%s'")
    for key, value in operator.iteritems():
        set_clause_dct.setdefault(key, fields[key] % value)

    set_clause = ','.join(
        [v for v in set_clause_dct.itervalues() if v is not None])
    if set_clause:
        db.execute("UPDATE T_OPERATOR SET " + set_clause +
                   "  WHERE oid = %s",
                   oid)
예제 #4
0
파일: information.py 프로젝트: jcsy521/ydws
    def get(self):
        """ """ 
        status = ErrorCode.SUCCESS
        try:
            page_number = int(self.get_argument('pagenum'))
            page_count = int(self.get_argument('pagecnt'))
            #reserved API
            fields = DotDict(name="name LIKE '%%%%%s%%%%'",
                             mobile="mobile LIKE '%%%%%s%%%%'")
            for key in fields.iterkeys():
                v = self.get_argument(key, None)
                if v:
                    fields[key] = fields[key] % (v,)
                else:
                    fields[key] = None
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] cid: %s Send message to ios push server data format illegal. Exception: %s", 
                              self.current_user.cid, e.args) 
            self.write_ret(status)
            return

        try:
            where_clause = ' AND '.join([v for v in fields.itervalues()
                                         if v is not None])
            page_size = 20
            if where_clause:
                where_clause = ' AND ' + where_clause
            if page_count == -1:
                sql = "SELECT count(id) as count FROM T_PASSENGER" + \
                      "  WHERE 1=1 " + where_clause
                sql += " AND cid = %s" % (self.current_user.cid,)
                res = self.db.get(sql) 
                count = res.count
                d, m = divmod(count, page_size)
                page_count = (d + 1) if m else d

            sql = "SELECT id, pid, name, mobile FROM T_PASSENGER" +\
                  "  WHERE 1=1 " + where_clause
            sql += " AND cid = %s LIMIT %s, %s" % (self.current_user.cid, page_number * page_size, page_size)
            passengers = self.db.query(sql)
            for passenger in passengers:
                for key in passenger.keys():
                    passenger[key] = passenger[key] if passenger[key] else ''
            self.write_ret(status,
                           dict_=DotDict(passengers=passengers,
                                         pagecnt=page_count))
        except Exception as e:
            logging.exception("[UWEB] cid: %s get passenger failed. Exception: %s", 
                              self.current_user.cid, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #5
0
파일: delegate.py 프로젝트: jcsy521/ydws
    def post(self):
        """Retrieve the log of delegation.
        """
        # check administrator_id
        start_time = int(self.get_argument("start_time"))
        end_time = int(self.get_argument("end_time"))
        select_clause = (
            "SELECT T_ADMINISTRATOR.name as administrator, T_ADMINISTRATOR.login,"
            + " T_DELEGATION_LOG.timestamp, T_TERMINAL_INFO.mobile as tmobile,"
            + " T_USER.name as user_name "
        )

        from_table_clause = " FROM T_DELEGATION_LOG, T_ADMINISTRATOR, T_TERMINAL_INFO, T_USER "

        where_clause = (
            " WHERE T_DELEGATION_LOG.timestamp BETWEEN %s AND %s"
            + " AND T_DELEGATION_LOG.administrator_id = T_ADMINISTRATOR.id"
            + " AND T_DELEGATION_LOG.uid = T_USER.uid"
            + " AND T_DELEGATION_LOG.tid = T_TERMINAL_INFO.tid"
        )
        where_clause = where_clause % (start_time, end_time)

        fields = DotDict(
            administrator="T_ADMINISTRATOR.name LIKE '%%%%%s%%%%'",
            login="******",
            user_name="T_USER.name LIKE '%%%%%s%%%%'",
            mobile="T_USER.mobile LIKE '%%%%%s%%%%'",
            tmobile="T_TERMINAL_INFO.mobile LIKE '%%%%%s%%%%'",
        )
        for key in fields.iterkeys():
            v = self.get_argument(key, None)
            if v:
                if not check_sql_injection(v):
                    self.get()
                    return
                fields[key] = fields[key] % (v,)
            else:
                fields[key] = None
        terms = [where_clause] + [v for v in fields.itervalues() if v]
        where_clause = " AND ".join(terms)

        sql = select_clause + from_table_clause + where_clause
        sql += " ORDER BY T_DELEGATION_LOG.timestamp DESC"
        logs = self.db.query(sql)
        for i, log in enumerate(logs):
            log["id"] = i + 1
        self.render("delegation/log.html", logs=logs, interval=[start_time, end_time])
예제 #6
0
파일: smsoption.py 프로젝트: jcsy521/ydws
    def put(self):
        """Modify smsoptions for the given owner_mobile.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            owner_mobile = data['owner_mobile']
            logging.info("[UWEB] smsoption request: %s, uid: %s", 
                         data, self.current_user.uid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s",
                              e.args)
            self.write_ret(status)
            return 

        try:
            del data['owner_mobile']
            fields = DotDict(login="******",
                             powerlow="powerlow = %s",
                             powerdown="powerdown = %s",
                             illegalshake="illegalshake = %s",
                             illegalmove="illegalmove = %s",
                             sos="sos = %s",
                             heartbeat_lost="heartbeat_lost = %s",
                             charge="charge = %s",
                             region_enter="region_enter = %s",
                             region_out="region_out = %s",
                             stop="stop = %s",
                             speed_limit="speed_limit = %s")
            for key, value in data.iteritems():
                data[key] = fields[key] % data[key] 
            set_clause = ','.join([v for v in data.itervalues() if v is not None])
            if set_clause:
                self.db.execute("UPDATE T_SMS_OPTION SET " + set_clause +
                                "  WHERE uid = %s",
                                owner_mobile)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] uid:%s tid:%s update SMS Options failed.  Exception: %s", 
                              self.current_user.uid,self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #7
0
    def post(self):
        """Retrieve the administrators according to the given parameters.
        """
        # TODO: this is ugly!
        fields = DotDict(corporation="corporation LIKE '%%%%%s%%%%'",
                         name="name LIKE '%%%%%s%%%%'",
                         mobile="mobile LIKE '%%%%%s%%%%'",
                         phone="phone LIKE '%%%%%s%%%%'",
                         login="******",
                         valid="valid = %s",
                         source_id="source_id = %s")
        for key in fields.iterkeys():
            v = self.get_argument(key, None)
            if v:
                # if not check_sql_injection(v):
                #    self.get()
                #    return
                fields[key] = fields[key] % (v,)
            else:
                fields[key] = None

        where_clause = ' AND '.join([v for v in fields.itervalues()
                                     if v is not None])
        if where_clause:
            sql = ("SELECT id, corporation, name, mobile,"
                   "       phone, login, valid, type"
                   "  FROM T_ADMINISTRATOR"
                   "  WHERE ") + where_clause
            administrators = self.db.query(sql)
        else:
            administrators = []
        for i, administrator in enumerate(administrators):
            administrator['seq'] = i + 1
            for key in administrator:
                if administrator[key] is None:
                    administrator[key] = ''
        self.render("administrator/search.html",
                    sources=self.sources,
                    administrators=administrators)
예제 #8
0
파일: public.py 프로젝트: jcsy521/ydws
def update_corp(corp, cid, db, redis):
    """Update corp status.

    :arg corp: dict, e.g.

        {
          'c_name':'',
          'c_mobile':'',          
          'c_alert_mobile':'',
          'c_address':'',
          'c_linkman':'',
          'c_email':'',
        }

    :arg cid: string
    :arg db: database instance
    :arg redis: redis instance

    """
    set_clause_dct = DotDict()
    fields = DotDict(c_name="name = '%s'",
                     c_mobile="mobile = '%s'",
                     c_alert_mobile="alert_mobile = '%s'",
                     c_address="address = '%s'",
                     c_linkman="linkman = '%s'",
                     c_email="email = '%s'")

    for key, value in corp.iteritems():
        set_clause_dct.setdefault(key, fields[key] % value)

    set_clause = ','.join(
        [v for v in set_clause_dct.itervalues() if v is not None])

    if set_clause:
        db.execute("UPDATE T_CORP SET " + set_clause +
                   "  WHERE cid = %s",
                   cid)
예제 #9
0
파일: business.py 프로젝트: jcsy521/ydws
    def post(self):
        """Query businesses according to the given params.
        """
        corplist = self.db.query("SELECT id, cid, name FROM T_CORP")
        corps = self.get_argument('corps', None)
        begintime = int(self.get_argument('begintime',0))
        endtime = int(self.get_argument('endtime',0))
        interval=[begintime, endtime]
        if not corps:
            corps = self.db.query("SELECT cid FROM T_CORP")
            corps = [str(corp.cid) for corp in corps]
            sql = "SELECT id FROM T_GROUP WHERE corp_id IN %s" % (tuple(corps + DUMMY_IDS),)
            groups = self.db.query(sql)
            groups = [str(group.id) for group in groups] + [-1,]
        else:
            groups = self.db.query("SELECT id FROM T_GROUP WHERE corp_id = %s", corps) 
            groups = [str(group.id) for group in groups]

        fields = DotDict(umobile="tu.mobile LIKE '%%%%%s%%%%'",
                         tmobile="tt.mobile LIKE '%%%%%s%%%%'",
                         begintime="tt.begintime >= %s",
                         endtime="tt.begintime <= %s",
                         login="******")
        
        for key in fields.iterkeys():
            #BIG NOTE: if online is to be got, "tt.login != 0" is good
            if key == 'login' and self.get_argument(key, None) == '1':
                fields[key] = "tt.login != 0"
                continue

            v = self.get_argument(key, None)
            if v:
                if not check_sql_injection(v):
                    logging.error("Search business condition contain SQL inject. %s : %s", key, v)
                    self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.SELECT_CONDITION_ILLEGAL])
                    return
                else:
                    fields[key] = fields[key] % (v,)
            else:
                fields[key] = None

        where_clause = ' AND '.join([v for v in fields.itervalues()
                                     if v is not None])
        try:
            sql = ("SELECT tt.tid, tt.login, tu.name as uname, tu.mobile as umobile, tt.mobile as tmobile,"
                   "  tt.softversion, tt.begintime, tt.endtime, tt.move_val, tt.static_val,"
                   "  tt.service_status, tt.bt_name, tt.bt_mac, tt.biz_type,"
                   "  tc.cnum, tcorp.name as ecname, tcorp.mobile as cmobile"
                   "  FROM T_TERMINAL_INFO as tt LEFT JOIN T_CAR as tc ON tt.tid = tc.tid"
                   "                             LEFT JOIN T_USER as tu ON tt.owner_mobile = tu.mobile"
                   "                             LEFT JOIN T_GROUP as tg ON tt.group_id = tg.id"
                   "                             LEFT JOIN T_CORP as tcorp ON tg.corp_id = tcorp.cid"
                   "  WHERE tt.service_status=1 AND tt.group_id IN %s ") % (tuple(groups + DUMMY_IDS),)
            if where_clause:
                sql += ' AND ' + where_clause

            businesses = self.db.query(sql)

            for i, business in enumerate(businesses):
                business['seq'] = i + 1
                #business['sms_status'] = self.get_sms_status(business['tmobile'])
                business['corp_name'] = ''
                #NOTE: if login !=0(offline), set login as 1(online)
                business['login'] = business['login'] if business['login']==0 else 1
                #biz = QueryHelper.get_biz_by_mobile(business['tmobile'], self.db)
                #business['biz_type'] = biz['biz_type'] if biz else 1
                terminal = QueryHelper.get_terminal_info(business['tid'], self.db, self.redis)
                business['pbat'] = terminal['pbat'] if terminal.get('pbat', None) is not None else 0 
                business['alias'] = business['cnum'] if business['cnum'] else business['tmobile']  

                for key in business:
                    if business[key] is None:
                        business[key] = ''

            # keep data in redis
            m = hashlib.md5()
            m.update(self.request.body)
            hash_ = m.hexdigest()
            mem_key = self.get_memcache_key(hash_)
            self.redis.setvalue(mem_key, businesses,
                                time=self.MEMCACHE_EXPIRY)
            
            self.render('business/search.html',
                        status=ErrorCode.SUCCESS,
                        message='',
                        interval=interval, 
                        businesses=businesses,
                        corplist=corplist,
                        hash_=hash_)
        except Exception as e:
            logging.exception("Search business failed. Exception: %s.",
                              e.args)
            self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.SEARCH_BUSINESS_FAILURE])
예제 #10
0
    def post(self, administrator_id):
        """Edit the administrator.
        """
        is_self = (administrator_id == self.current_user.id)

        # update basic info
        fields = DotDict(corporation="corporation = %s",
                         name="name = %s",
                         mobile="mobile = %s",
                         phone="phone = %s",
                         email="email = %s",
                         valid="valid = %s",
                         source_id="source_id = %s"
                         )
        list_inject = ['corporation', 'name', 'mobile', 'phone']
        for key in list_inject:
            v = self.get_argument(key, '')
            # if not check_sql_injection(v):
            #   self.get(administrator_id)
            #   return
        if is_self:
            del fields['valid']
            del fields['source_id']

            self.bookkeep(dict(id=self.current_user.id,
                               session_id=self.current_user.session_id),
                          quote(safe_utf8(self.get_argument('name', u""))))

        data = [self.get_argument(key, '')
                for key in fields.iterkeys()] + [administrator_id]

        set_clause = ','.join([v for v in fields.itervalues()])

        self.db.execute("UPDATE T_ADMINISTRATOR"
                        " SET " + set_clause +
                        "  WHERE id = %s",
                        *data)

        if not is_self:
            # update privilege
            privileges = map(int, self.get_arguments('privileges'))
            if privileges:
                rs = self.db.query("SELECT privilege_group_id FROM T_PRIVILEGE"
                                   "  WHERE administrator_id = %s",
                                   administrator_id)
                ids = [r.privilege_group_id for r in rs]
                new_ids = list(set(privileges) - set(ids))
                old_ids = list(set(ids) - set(privileges))
                # clean up old ids
                self.db.execute("DELETE FROM T_PRIVILEGE"
                                "  WHERE administrator_id = %s"
                                "    AND privilege_group_id in %s",
                                administrator_id, tuple(old_ids + DUMMY_IDS))
                # insert new ids
                self.db.executemany("INSERT INTO T_PRIVILEGE"
                                    "  VALUES (%s, %s)",
                                    [(administrator_id, priv)
                                     for priv in new_ids])

            key = self.get_area_memcache_key(administrator_id)
            cities = [int(i)
                      for i in str_to_list(self.get_argument('cities', ''))]
            if len(cities) == 1 and int(cities[0]) == 0:
                self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                "  WHERE administrator_id = %s",
                                administrator_id)
                self.db.execute("INSERT INTO T_AREA_PRIVILEGE"
                                "  VALUES(NULL, %s, %s, %s)",
                                administrator_id, AREA.CATEGORY.PROVINCE,
                                AREA.PROVINCE.LIAONING)
                cities = self.db.query("SELECT city_id, city_name FROM T_HLR_CITY"
                                       "  WHERE province_id = %s",
                                       AREA.PROVINCE.LIAONING)
                self.redis.setvalue(key, cities)
            else:
                if cities:
                    areas = self.get_area(cities)
                    self.redis.setvalue(key, areas)

                    cities = self.db.query("SELECT region_code FROM T_HLR_CITY"
                                           "  WHERE city_id IN %s",
                                           tuple(cities + DUMMY_IDS))
                    cids = [c.region_code for c in cities]
                    rs = self.db.query("SELECT area_id FROM T_AREA_PRIVILEGE"
                                       "  WHERE category = %s"
                                       "    AND administrator_id = %s",
                                       AREA.CATEGORY.CITY, administrator_id)
                    ids = [r.area_id for r in rs]
                    new_ids = list(set(cids) - set(ids))
                    old_ids = list(set(ids) - set(cids))
                    # clean up old ids
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s"
                                    "    AND category = %s"
                                    "    AND area_id in %s",
                                    administrator_id, AREA.CATEGORY.CITY,
                                    tuple(old_ids + DUMMY_IDS))
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s"
                                    "    AND category = %s",
                                    administrator_id, AREA.CATEGORY.PROVINCE)
                    # insert new ids
                    self.db.executemany("INSERT INTO T_AREA_PRIVILEGE"
                                        "  VALUES (NULL, %s, %s, %s)",
                                        [(administrator_id, AREA.CATEGORY.CITY, id)
                                         for id in new_ids])
                else:
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s",
                                    administrator_id)
                    self.redis.delete(key)

        self.redirect("/administrator/list/%s" % administrator_id)
예제 #11
0
    def prepare_data(self, hash_):

        mem_key = self.get_memcache_key(hash_)
        
        data = self.redis.getvalue(mem_key)
        if data:
            return data

        # defaulty, we consider parents to be selected
        category = str(self.get_argument('category', XXT.USER_TYPE.PARENT))
        city = int(self.get_argument('cities', 0))
        terms = []

        users = []
        if int(city) == 0:
            cities = [city.city_id for city in self.cities]
        else:
            cities = [city,]

        select_clause = "SELECT T_XXT_USER.name AS pname,"\
                      + " T_XXT_USER.optype AS poptype,"\
                      + " T_XXT_USER.status AS jxq_status,"\
                      + " T_XXT_USER.plan_id AS pplan,"\
                      + " T_XXT_USER.timestamp AS ptimestamp,"\
                      + " T_XXT_TARGET.mobile AS tmobile, T_XXT_TARGET.lbmp_status,"\
                      + " T_XXT_TARGET.optype AS toptype,"\
                      + " T_XXT_TARGET.name AS tname,"\
                      + " T_XXT_TARGET.plan_id AS tplan,"\
                      + " T_XXT_TARGET.timestamp AS ttimestamp,"\
                      + " T_HLR_CITY.city_name AS city,"\
                      + " T_XXT_GROUP.name AS group_name,"
        USER_BIND_TARGET = " FROM T_XXT_USER LEFT JOIN T_XXT_TARGET"\
                           " ON (T_XXT_USER.mobile = T_XXT_TARGET.parent_mobile"\
                           " AND T_XXT_USER.service_id = T_XXT_TARGET.service_id),"
        TARGET_BIND_USER = "******"\
                           " ON (T_XXT_USER.mobile = T_XXT_TARGET.parent_mobile"\
                           " AND T_XXT_USER.service_id = T_XXT_TARGET.service_id),"
        from_table_clause = "T_HLR_CITY, T_XXT_GROUP"
        where_clause = " WHERE T_XXT_GROUP.xxt_id in %s "

        if int(self.type) == 1:
            groups = self.db.query("SELECT txg.xxt_id as id"
                                   "  FROM T_XXT_GROUP AS txg,"
                                   "       T_ADMINISTRATOR AS ta"
                                   "  WHERE ta.login = txg.phonenum"
                                   "    AND ta.id = %s",
                                   self.current_user.id)
        else:
            groups = self.db.query("SELECT DISTINCT xxt_id as id"
                                   "  FROM T_XXT_GROUP AS txg,"
                                   "       T_HLR_CITY AS thc"
                                   "  WHERE thc.city_id IN %s"
                                   "    AND txg.city_id = thc.region_code",
                                   tuple(cities + DUMMY_IDS))
        group_ids = [int(group.id) for group in groups]
        groups = tuple(group_ids + DUMMY_IDS) 

        terms.append(where_clause)
        if category == XXT.USER_TYPE.PARENT:
            fields = DotDict(name="T_XXT_USER.name LIKE '%%%%%s%%%%' ",
                             mobile=" T_XXT_USER.mobile LIKE '%%%%%s%%%%' ")
            for item in fields.iterkeys():
                v = self.get_argument(item, None)
                if v:
                    if not check_sql_injection(v):
                        return []
                    fields[item] = fields[item] % (v, )
                else:
                    fields[item] = None
            user_terms = [v for v in fields.itervalues() if v]
            terms += user_terms 
        else:
            fields = DotDict(name="T_XXT_TARGET.name LIKE '%%%%%s%%%%' ",
                             mobile=" T_XXT_TARGET.mobile LIKE '%%%%%s%%%%' ",
                             plan_id="T_XXT_TARGET.plan_id = %s ")
            for item in fields.iterkeys():
                v = self.get_argument(item, None)
                if v:
                    if not check_sql_injection(v):
                        return []
                    fields[item] = fields[item] % (v,)
                else:
                    fields[item] = None
            child_terms = [v for v in fields.itervalues() if v]
            terms += child_terms

        USER_BIND_GROUP = " T_XXT_USER.group_id = T_XXT_GROUP.xxt_id "
        TARGET_BIND_GROUP = " T_XXT_TARGET.group_id = T_XXT_GROUP.xxt_id "
        GROUP_BIND_CITY = " T_XXT_GROUP.city_id = T_HLR_CITY.region_code"
        terms.append(GROUP_BIND_CITY)
        terms.append(USER_BIND_GROUP)
        select_clause1 = select_clause + " T_XXT_USER.mobile AS pmobile"
        sql1 = ''.join((select_clause1, USER_BIND_TARGET, from_table_clause, ' AND '.join(terms)))
        terms.remove(USER_BIND_GROUP)
        terms.append(TARGET_BIND_GROUP)
        select_clause2 = select_clause + " T_XXT_TARGET.parent_mobile AS pmobile"
        sql2 = ''.join((select_clause2, TARGET_BIND_USER, from_table_clause, ' AND '.join(terms)))
        sql = sql1 + ' union ' + sql2
                                  
        users = self.db.query(sql, groups, groups)
        plans = self.db.query("SELECT xxt_id, name FROM T_XXT_PLAN")
        d_plan = dict()
        for plan in plans:
            d_plan[plan.xxt_id] = plan.name
        for i, user in enumerate(users):
            user['id'] = i + 1
            for key in user:
                if key in ('pplan', 'tplan'):
                    user[key] = d_plan[user[key]] if user[key] else ''
                else:
                    user[key] = user[key] if user[key] else ''

        self.redis.setvalue(mem_key, users, time=self.MEMCACHE_EXPIRY)
        return users 
예제 #12
0
파일: ecbusiness.py 프로젝트: jcsy521/ydws
    def prepare_data(self, hash_):
        """Prepare search results for post.
        """
        mem_key = self.get_memcache_key(hash_)
        data = self.redis.getvalue(mem_key)
        if data:
            if data[0]:
                return data

        corp = self.get_argument('corps', None)

        begintime = self.get_argument('begintime', 0)
        if not begintime:
            begintime = 0
        else:
            begintime = int(begintime)

        endtime = self.get_argument('endtime', 0)
        if not endtime:
            endtime = 0
        else:
            endtime = int(endtime)

        #begintime = int(self.get_argument('begintime',0))
        #endtime = int(self.get_argument('endtime',0))
        interval = [begintime, endtime]
        if not corp:
            corps = self.db.query("SELECT id, cid FROM T_CORP")
            corps = [str(c.cid) for c in corps]
        else:
            corps = [str(corp), ]

        fields = DotDict(ecmobile="mobile LIKE '%%%%%s%%%%'")
        #begintime="timestamp >= %s",
        # endtime="timestamp <= %s")

        for key in fields.iterkeys():
            v = self.get_argument(key, None)
            if v:
                # if not check_sql_injection(v):
                #    self.get()
                #    return
                fields[key] = fields[key] % (v,)
            else:
                fields[key] = None

        where_clause = ' AND '.join([v for v in fields.itervalues()
                                     if v is not None])

        sql = ("SELECT cid, name as ecname, mobile as ecmobile, address, email"
               "  FROM T_CORP"
               "  WHERE cid IN %s ") % (tuple(corps + DUMMY_IDS),)
        if where_clause:
            sql += " AND " + where_clause
        businesses = self.db.query(sql)
        for i, business in enumerate(businesses):
            business['seq'] = i + 1
            groups = self.db.query(
                "SELECT id FROM T_GROUP WHERE corp_id = %s", business.cid)
            groups = [g.id for g in groups]
            terminals = self.db.query("SELECT id FROM T_TERMINAL_INFO"
                                      "  WHERE group_id IN %s"
                                      "    AND service_status = %s",
                                      tuple(groups + DUMMY_IDS),
                                      UWEB.SERVICE_STATUS.ON)
            business['total_terminals'] = len(terminals)
            for key in business:
                if business[key] is None:
                    business[key] = ''

        # NOTE: here, in order to get the latest data, data is not kept in redis
        # self.redis.setvalue(mem_key,(businesses,interval),
        #                    time=self.MEMCACHE_EXPIRY)

        return businesses, interval