示例#1
0
    def get(self):
        userid = self.getCurrUserId()
        num = self.get_argument("num", 0)
        count = self.get_argument("count", -1)
        userType = self.get_argument("userType",None)
        mylog.getlog().info(getLogText( "get comment:userid", userid, " num", num," count",count,"userType",userType))
        service = self.getDbService()
        if userid:
            commentIds = service.getUserComments(userid,userType, int(num), int(count))
            commentDatas = [service.getCommentById(commentIds[i]) for i in xrange(len(commentIds))] if commentIds else []

            # print commentIds
            # print commentDatas
            for item in commentDatas:
                if "fromUserId" in item:
                    print 'eeeeeeeeeeeeeee item["fromUserId"]',item["fromUserId"]

                    user = yield User.get(item["fromUserId"],userType)
                    print "user,",user
                    if user:
                        item["nickBarData"] = user.to_user_base_data()

            self.write(DataProtocol.getSuccessJson(commentDatas,"json"))
        else:
            self.write(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
示例#2
0
    def getLocalTruckBill(self, location, num):
        drivers = yield User.objects({"id":{"$ne":ObjectId(self.getCurrUserId())}, "trunks":{"$not":{"$size":0}}, \
                                      "homeLocation":re.compile(r"^"+location)}).limit(num).to_list(num)

        mylog.getlog().info(getLogText("-----recommend local:", len(drivers)))
        returnBills = []
        if drivers:
            for driver in drivers:
                currTruck = driver.getCurrTruck()
                if currTruck:
                    bill = Bill()
                    bill.trunkType = currTruck["type"]
                    bill.trunkLength = currTruck["length"]
                    bill.trunkLoad = currTruck["load"]
                    driver.currType = UserType.DRIVER
                    driverData = driver.to_user_base_data()
                    # print "driver:", driver.ids
                    driverLocs = yield Location.objects({
                        "userId":
                        str(driver.id)
                    }).sort([("timestamp", -1)]).limit(1).to_list(1)
                    # driverLoc = yield Location.get_collection().find_one({"userId":str(driver.id)})
                    if driverLocs:
                        driverData.update(
                            {"location": driverLocs[0].to_client()})
                    returnBills.append(
                        createRecommendBill(driverData, bill.to_client(),
                                            RecomendBillType.LOCAL))

        raise Return(returnBills)
示例#3
0
def getAddrNearBill(user, excludeBills, bills, returnLimit):
    '''
    根据用户当前有效的单据查找from,to都在同一个城市的对应单据
    :param user:
    :param excludeBills: 之前已经找到的单据,后面查找时候就要排除掉
    :param bills:
    :return:
    '''
    if bills:
        conditions = []
        for bill in bills:
            #获取单子上面的城市名
            fromCity, toCity = getCity(bill.fromAddr), getCity(bill.toAddr)
            cond = {
                "fromAddr": re.compile(r"^" + fromCity),
                "toAddr": re.compile(r"^" + toCity)
            }
            cond.update(getLoadMatchCondition(user, bill))
            conditions.append(cond)
        findType = matchBillType(oppsiteUserType(user.currType))
        query = getQueryFromBase(str(user.id), findType, excludeBills,
                                 {"$or": conditions})
        returnBills = yield Bill.objects(query).limit(returnLimit)\
                                        .to_list(returnLimit)

        mylog.getlog().info(getLogText("----get addr near", len(returnBills)))
        raise Return(returnBills)
    else:
        raise Return([])
示例#4
0
def getRecordMatchBill(user, excludeBills, recordBills, returnLimit):
    '''
    根据用户以往的发送记录,计算出频率排在前面的几个城市,推送
    :param user:
    :param excludeBills:
    :param recordBills:
    :return:
    '''
    if recordBills:
        recordFrom = [bill.fromAddr for bill in recordBills]
        recordTo = [bill.toAddr for bill in recordBills]
        fromFreq = addrsAnalysis(recordFrom)
        toFreq = addrsAnalysis(recordTo)
        #取出频率至多前三位的城市
        fromCities, toCities = fromFreq["city"].keys(
        )[0:3], toFreq["city"].keys()[0:3]

        query = {"fromAddr": {"$in": fromCities}, "toAddr": {"$in": toCities}}
        query.update(getLoadMatchCondition(user))

        findType = matchBillType(oppsiteUserType(user.currType))
        bills = yield Bill.objects(getQueryFromBase(str(user.id), findType, excludeBills, query))\
                            .limit(returnLimit).to_list(returnLimit)

        mylog.getlog().info(getLogText("----get addr record", len(bills)))
        raise Return(bills)
    else:
        raise Return([])
示例#5
0
def getAddrNearBill(user, excludeBills, bills, returnLimit):
    '''
    根据用户当前有效的单据查找from,to都在同一个城市的对应单据
    :param user:
    :param excludeBills: 之前已经找到的单据,后面查找时候就要排除掉
    :param bills:
    :return:
    '''
    if bills:
        conditions = []
        for bill in bills:
            #获取单子上面的城市名
            fromCity, toCity = getCity(bill.fromAddr), getCity(bill.toAddr)
            cond = {"fromAddr": re.compile(r"^"+fromCity), "toAddr":re.compile(r"^"+toCity)}
            cond.update(getLoadMatchCondition(user, bill))
            conditions.append(cond)
        findType = matchBillType(oppsiteUserType(user.currType))
        query = getQueryFromBase(str(user.id), findType, excludeBills, {"$or":conditions})
        returnBills = yield Bill.objects(query).limit(returnLimit)\
                                        .to_list(returnLimit)

        mylog.getlog().info(getLogText("----get addr near", len(returnBills)))
        raise Return(returnBills)
    else:
        raise Return([])
示例#6
0
def getRecordMatchBill(user, excludeBills, recordBills, returnLimit):
    '''
    根据用户以往的发送记录,计算出频率排在前面的几个城市,推送
    :param user:
    :param excludeBills:
    :param recordBills:
    :return:
    '''
    if recordBills:
        recordFrom = [bill.fromAddr for bill in recordBills]
        recordTo = [bill.toAddr for bill in recordBills]
        fromFreq = addrsAnalysis(recordFrom)
        toFreq = addrsAnalysis(recordTo)
        #取出频率至多前三位的城市
        fromCities, toCities = fromFreq["city"].keys()[0:3], toFreq["city"].keys()[0:3]

        query = {"fromAddr":{"$in":fromCities}, "toAddr":{"$in":toCities}}
        query.update(getLoadMatchCondition(user))

        findType = matchBillType(oppsiteUserType(user.currType))
        bills = yield Bill.objects(getQueryFromBase(str(user.id), findType, excludeBills, query))\
                            .limit(returnLimit).to_list(returnLimit)

        mylog.getlog().info(getLogText("----get addr record", len(bills)))
        raise Return(bills)
    else:
        raise Return([])
示例#7
0
    def getDbService(self):
        service = DbService().connect()

        if not service:
            self.write(DataProtocol.getJson(DataProtocol.DB_ERROR))
            mylog.getlog().info(getLogText(DataProtocol.DB_ERROR,"db connect error"))
        return service
示例#8
0
    def getDbService(self):
        service = DbService().connect()

        if not service:
            self.write(DataProtocol.getJson(DataProtocol.DB_ERROR))
            mylog.getlog().info(
                getLogText(DataProtocol.DB_ERROR, "db connect error"))
        return service
示例#9
0
def _quit_if_ioloop_is_empty():
    ioloop = tornado.ioloop.IOLoop.instance()
    reset()

    if len(ioloop._handlers) <= len(ioloop._timeouts):
        mylog.getlog().info("No more request in progress(%d timeouts). really quiting", len(ioloop._timeouts))
        tornado.ioloop.IOLoop.instance().stop()
    else:
        mylog.getlog().info("%d more handlers pending", len(ioloop._handlers))
示例#10
0
 def billDone(self, bill):
     bill.state = BillState.DONE
     yield bill.save()
     if bill.id in self.getAttr("Bills"):
         self.getAttr("Bills").remove(bill.id)
         self.getAttr("BillsRecord").append(bill.id)
         yield self.save()
     else:
         mylog.getlog().error("attend to done a bill that is not belonged to self")
示例#11
0
 def removeBill(self, bill):
     mylog.getlog().info(getLogText("--bill match control remove bill: "))
     cityKey = makeAddrKey(bill.fromAddr, bill.toAddr)
     billId = str(bill.id)
     if billId and cityKey in self.billMatchMap:
         for item in self.billMatchMap[cityKey][bill.billType]:
             if billId == item["id"]:
                 self.billMatchMap[cityKey][bill.billType].remove(item)
                 break
示例#12
0
 def from_db(cls, dbDoc):
     if not dbDoc:
         return None
     obj = cls()
     try:
         obj.update_from_db(dbDoc)
         return obj
     except Exception, e:
         mylog.getlog().error("DOCUMENT FROM DB ERROR: "+e.message)
         return None
示例#13
0
 def from_db(cls, dbDoc):
     if not dbDoc:
         return None
     obj = cls()
     try:
         obj.update_from_db(dbDoc)
         return obj
     except Exception, e:
         mylog.getlog().error("DOCUMENT FROM DB ERROR: " + e.message)
         return None
示例#14
0
 def billDone(self, bill):
     bill.state = BillState.DONE
     yield bill.save()
     if bill.id in self.getAttr("Bills"):
         self.getAttr("Bills").remove(bill.id)
         self.getAttr("BillsRecord").append(bill.id)
         yield self.save()
     else:
         mylog.getlog().error(
             "attend to done a bill that is not belonged to self")
示例#15
0
文件: admin.py 项目: buerlab/trunkweb
    def get(self):
        service = self.getDbService()
        userid = self.getCurrentUser()
        user = service.getAdmin(userid)
        mylog.getlog().info(getLogText("GetAdminHandler user", user))

        if user:
            self.write(DataProtocol.getSuccessJson(user, "json"))
        else:
            self.write(DataProtocol.getJson(DataProtocol.DB_ERROR))
示例#16
0
    def save(self, force_insert=False):

        self.validate()

        if force_insert:
            self.id = ""
        try:
            dbdoc = self.to_mongo()
        except Exception, e:
            mylog.getlog().error("save error when validate"+e.message)
            raise Return(None)
示例#17
0
 def check(self, *args, **kwargs):
     userid = self.getCurrUserId()
     mylog.getlog().info(getLogText("get connect userid:", userid))
     mark = self.getMark()
     customType = self.getCustomType()
     print "authPage"
     print userid,mark
     if userid and mark and checkMark(userid, mark,customType):
         return func(self, *args, **kwargs)
     self.redirect("/login.html")
     return None
示例#18
0
    def save(self, force_insert=False):

        self.validate()

        if force_insert:
            self.id = ""
        try:
            dbdoc = self.to_mongo()
        except Exception, e:
            mylog.getlog().error("save error when validate" + e.message)
            raise Return(None)
示例#19
0
 def check(self, *args, **kwargs):
     userid = self.getCurrUserId()
     mylog.getlog().info(getLogText("get connect userid:", userid))
     mark = self.getMark()
     customType = self.getCustomType()
     print "authPage"
     print userid, mark
     if userid and mark and checkMark(userid, mark, customType):
         return func(self, *args, **kwargs)
     self.redirect("/login.html")
     return None
示例#20
0
文件: admin.py 项目: buerlab/trunkweb
 def check(self, *args, **kwargs):
     username = self.getCurrentUser()
     mylog.getlog().info(getLogText("get connect username:"******"authPage"
     print username, mark
     if username and mark and checkMark(username, mark):
         return func(self, *args, **kwargs)
     self.clear_cookie("mark")
     self.clear_cookie("username")
     self.redirect("/login.html")
     return None
示例#21
0
文件: admin.py 项目: buerlab/trunkweb
 def post(self):
     service = self.getDbService()
     id = self.get_argument("id", None)
     if (not id is None):
         mylog.getlog().info(getLogText("id", id))
         username = self.getCurrentUsername()
         service.doneToAddMessage(id, username)
         self.write(DataProtocol.getSuccessJson("ok", "json"))
     else:
         self.write(
             DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR,
                                  "id is invaill"))
示例#22
0
 def get(self):
     mylog.getlog().info(getLogText("find bills"))
     service = self.getDbService()
     userid = self.getCurrUserId()
     if service:
         user = service.getUserBaseData(userid)
         query = {}
         if user.has_key("userType"):
             query["billType"] = "goods" if user["userType"] == "driver" else "trunk"
             mylog.getlog().info(getLogText("find:", query["billType"]))
         bills = service.findBills(query)
         self.write(DataProtocol.getSuccessJson(bills))
示例#23
0
 def readyToJPush(self, bill):
     mylog.getlog().info("----process bill id: %s" % bill.id)
     if bill.sender:
         sender = yield User.get(bill.sender, matchUserType(bill.billType))
         if sender and sender.level == UserLevel.NORMAL and sender.getAttr(
                 "JPushId"):
             mylog.getlog().info(
                 getLogText("--process bill send msg ",
                            sender.getAttr("JPushId"), sender.id,
                            sender.currType))
             self.pushQueue.sendMsg(sender.getAttr("JPushId"), sender.id,
                                    sender.currType)
示例#24
0
 def get(self):
     mylog.getlog().info(getLogText("find bills"))
     service = self.getDbService()
     userid = self.getCurrUserId()
     if service:
         user = service.getUserBaseData(userid)
         query = {}
         if user.has_key("userType"):
             query["billType"] = "goods" if user[
                 "userType"] == "driver" else "trunk"
             mylog.getlog().info(getLogText("find:", query["billType"]))
         bills = service.findBills(query)
         self.write(DataProtocol.getSuccessJson(bills))
示例#25
0
 def initFromDB(self):
     self.billMatchMap = {}
     cursor = Bill.get_collection().find({"state": BillState.WAIT})
     count = yield cursor.count()
     mylog.getlog().info(
         getLogText("BILL MATCH INIT FROM DB, GET BILL COUNT: ",
                    str(count)))
     if count > 0:
         while (yield cursor.fetch_next):
             billDoc = cursor.next_object()
             bill = Bill.from_db(billDoc)
             matchCity(self.billMatchMap, bill)
     print self.billMatchMap
示例#26
0
 def onCall(self, **kwargs):
     mylog.getlog().info(getLogText("get record bills"))
     user = yield self.getUser()
     fromId = self.get_argument("fromId", None)
     fromObjId = ObjectId(fromId) if fromId else None
     record = user.getAttr("BillsRecord")
     record.reverse()
     fromIndex = 0
     try:
         if fromObjId:
             fromIndex = record.index(fromObjId)+1
     except Exception, e:
         pass
示例#27
0
 def onCall(self, **kwargs):
     mylog.getlog().info(getLogText("get record bills"))
     user = yield self.getUser()
     fromId = self.get_argument("fromId", None)
     fromObjId = ObjectId(fromId) if fromId else None
     record = user.getAttr("BillsRecord")
     record.reverse()
     fromIndex = 0
     try:
         if fromObjId:
             fromIndex = record.index(fromObjId) + 1
     except Exception, e:
         pass
示例#28
0
    def onCall(self, **kwargs):
        mylog.getlog().info(getLogText("--send bill, get argument: ", kwargs))
        if kwargs:
            bill = Bill.from_db(kwargs)
            if bill:
                now = time.time()
                bill.sendTime, bill.addTime = bill.sendTime or now, now
                bill.state = BillState.WAIT
                userId = self.getCurrUserId()
                print "userid"
                if userId:
                    user = (yield self.getUser()) if not bill.sender else (
                        yield User.get(bill.sender, matchUserType(
                            bill.billType)))
                    if user and user.currType == matchUserType(bill.billType):
                        # saveBill = yield user.sendBill(bill)
                        bill.sender = bill.sender or user.id
                        bill.senderName = bill.senderName or user.nickName
                        bill.phoneNum = bill.phoneNum or user.phoneNum
                        saveResult = yield bill.save()

                        if saveResult:
                            user.getAttr("Bills").append(bill.id)
                            yield user.save()

                            mylog.getlog().info(
                                getLogText("--send bill success~~~"))
                            #告诉matchcontroller有新单发送,更新matchmap
                            BillMatchController().sendBill(bill)

                            self.finish(
                                DataProtocol.getSuccessJson(bill.to_client()))
                        else:
                            self.finish(
                                DataProtocol.getJson(DataProtocol.DB_ERROR))
                    else:
                        self.finish(
                            DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR,
                                                 "创建订单失败"))
                else:
                    yield bill.save()
                    #告诉matchcontroller有新单发送,更新matchmap
                    BillMatchController().sendBill(bill)
                    self.finish(DataProtocol.getSuccessJson(bill.to_client()))
            else:
                self.finish(
                    DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR,
                                         "创建订单失败"))
        else:
            self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
        return
示例#29
0
def matchCity(result, bill):
    billType = bill.billType
    if not billType in (BillType.GOODS, BillType.TRUNK):
        return
    cityKey = makeAddrKey(bill.fromAddr, bill.toAddr)
    if cityKey:
        if not cityKey in result:
            result[cityKey] = {BillType.TRUNK: [], BillType.GOODS: []}
        result[cityKey][billType].append({
            "id": str(bill.id),
            "matcher": BillMatcher(bill)
        })
    else:
        mylog.getlog().error("ADD BILL ERROR, ADDR IS INVALID")
示例#30
0
    def getMatchMap(self):
        mylog.getlog().info(getLogText("get match map "))
        #如果结果里面司机或者货主list里面有一个是空得,应该filter掉
        result = {}
        for k, v in self.billMatchMap.iteritems():
            branch = {}
            for k2, v2 in v.iteritems():
                if not v2:
                    branch = {}
                    break
                branch[k2] = [item["id"] for item in v2]
            if branch:
                result[k] = branch

        return result
示例#31
0
    def check(self, *args, **kwargs):
        userid = self.getCurrUserId()

        mark = self.getMark()
        customType = self.getCustomType()
        mylog.getlog().info(getLogText("get connect userid:", userid, "mark:", mark, "ip:", self.request.remote_ip))

        #来自特殊的admin userid 则特殊处理  留个后门
        if userid == "53e9cd5915a5e45c43813d1c":
            return func(self, *args, **kwargs)
        elif userid and mark and checkMark(userid, mark,customType):
            return func(self, *args, **kwargs)
        self.write(DataProtocol.getJson(DataProtocol.AUTH_ERROR,"登录失败"))
        self.finish()
        return None
示例#32
0
文件: admin.py 项目: buerlab/trunkweb
    def post(self):
        username = self.get_argument("username", None)
        psw = self.get_argument("password", None)
        realname = self.get_argument("realname", None)
        bankName = self.get_argument("bankName", None)
        phoneNum = self.get_argument("phoneNum", None)
        bankNum = self.get_argument("bankNum", None)

        mylog.getlog().info(
            getLogText("RegisterHandler", username, psw, realname, phoneNum,
                       bankName, bankNum))
        if username and psw:
            service = self.getDbService()

            # self.set_secure_cookie("mark", getmark(user))

            #开放注册的flag
            if False:
                self.write(
                    DataProtocol.getJson(DataProtocol.USER_EXISTED_ERROR,
                                         "不允许注册了,请与管理员联系"))
                return
            else:
                if not service.hasAdmin(username):
                    # print "register new admin:", username
                    service.addAdmin(username, encryptPassword(psw), realname,
                                     phoneNum, bankName, bankNum)

                    #注册后顺便登录
                    user = service.confirmAdmin(username, encryptPassword(psw))
                    if user:
                        self.set_secure_cookie("userid", str(user["_id"]))
                        self.set_secure_cookie("username",
                                               str(user["username"]))
                        self.set_secure_cookie("mark", getMark(user["_id"]))

                    # print str(username)
                    # print getMark(username)
                    self.write(DataProtocol.getSuccessJson(user, "json"))

                else:
                    self.write(
                        DataProtocol.getJson(DataProtocol.USER_EXISTED_ERROR,
                                             "管理员已经存在"))
        else:
            self.write(
                DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR,
                                     "missing username or password"))
示例#33
0
class GetRecordBillHandler(BaseHandler):

    returnOnce = 5
    returnLimit = 50

    optionalParams = {"fromId": unicode}

    @auth
    @coroutineDebug
    @coroutine
    def onCall(self, **kwargs):
        mylog.getlog().info(getLogText("get record bills"))
        user = yield self.getUser()
        fromId = self.get_argument("fromId", None)
        fromObjId = ObjectId(fromId) if fromId else None
        record = user.getAttr("BillsRecord")
        record.reverse()
        fromIndex = 0
        try:
            if fromObjId:
                fromIndex = record.index(fromObjId) + 1
        except Exception, e:
            pass
        mylog.getlog().info(getLogText("from index: ", fromIndex))
        slice = record[fromIndex:fromIndex +
                       self.returnOnce] if fromIndex < len(record) else []
        bills = [(yield Bill.get(id)) for id in slice]
        billsToReturn = [bill.to_client() for bill in bills if bill]
        self.finish(DataProtocol.getSuccessJson(billsToReturn))
示例#34
0
    def check(self, *args, **kwargs):
        userid = self.getCurrUserId()

        mark = self.getMark()
        customType = self.getCustomType()
        mylog.getlog().info(
            getLogText("get connect userid:", userid, "mark:", mark, "ip:",
                       self.request.remote_ip))

        #来自特殊的admin userid 则特殊处理  留个后门
        if userid == "53e9cd5915a5e45c43813d1c":
            return func(self, *args, **kwargs)
        elif userid and mark and checkMark(userid, mark, customType):
            return func(self, *args, **kwargs)
        self.write(DataProtocol.getJson(DataProtocol.AUTH_ERROR, "登录失败"))
        self.finish()
        return None
示例#35
0
    def onCall(self, **kwargs):
        mylog.getlog().info(getLogText("--send bill, get argument: ", kwargs))
        if kwargs:
            bill = Bill.from_db(kwargs)
            if bill:
                now = time.time()
                bill.sendTime, bill.addTime = bill.sendTime or now, now
                bill.state = BillState.WAIT
                userId = self.getCurrUserId()
                print "userid"
                if userId:
                    user = (yield self.getUser()) if not bill.sender else (yield User.get(bill.sender, matchUserType(bill.billType)))
                    if user and user.currType == matchUserType(bill.billType):
                        # saveBill = yield user.sendBill(bill)
                        bill.sender = bill.sender or user.id
                        bill.senderName = bill.senderName or user.nickName
                        bill.phoneNum = bill.phoneNum or user.phoneNum
                        saveResult = yield bill.save()

                        if saveResult:
                            user.getAttr("Bills").append(bill.id)
                            yield user.save()

                            mylog.getlog().info(getLogText("--send bill success~~~"))
                            #告诉matchcontroller有新单发送,更新matchmap
                            BillMatchController().sendBill(bill)

                            self.finish(DataProtocol.getSuccessJson(bill.to_client()))
                        else:
                            self.finish(DataProtocol.getJson(DataProtocol.DB_ERROR))
                    else:
                        self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR, "创建订单失败"))
                else:
                    yield bill.save()
                    #告诉matchcontroller有新单发送,更新matchmap
                    BillMatchController().sendBill(bill)
                    self.finish(DataProtocol.getSuccessJson(bill.to_client()))
            else:
                self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR, "创建订单失败"))
        else:
            self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
        return
示例#36
0
文件: admin.py 项目: buerlab/trunkweb
    def post(self):
        sendTo = self.get_argument("sendTo", None)
        phonenum = self.get_argument("phonenum", None)
        nickname = self.get_argument("nickname", "你好")
        _from = self.get_argument("from", None)
        _to = self.get_argument("to", None)
        usertype = self.get_argument("usertype", "driver")
        comment = self.get_argument("comment", None)
        print phonenum, nickname, _from, _to

        if usertype is None or sendTo is None or phonenum is None or nickname is None or _from is None or _to is None:
            self.write(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
            return

        regcodeObject = YunPianMsgMatch()
        regcodeStr = regcodeObject.send(sendTo, phonenum, usertype, nickname,
                                        _from, _to, comment)

        mylog.getlog().info(regcodeStr)
        self.write(DataProtocol.getSuccessJson())
示例#37
0
    def onCall(self, **kwargs):
        mylog.getlog().info(getLogText("get recomend bills"))
        usertype = self.getUserType()
        user = yield self.getUser()
        if not user:
            self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
            raise Return(None)

        self.findtype = matchBillType(oppsiteUserType(usertype))

        self.config = yield Config.shared()
        self.userBills = yield user.getBills()
        for id in user.getAttr("BillsRecord")[0:10]:
            bill = yield Bill.get(id)
            self.recordBills.append(bill)

        bills = yield getBillsToRecomend(user, self.config)

        if "format" in kwargs and kwargs["format"] == "ids":
            #slice
            sortBills, returnBillIds = bills[0:self.returnBillsNum], []
            returnBills = yield getRecomendBills(sortBills)
            if len(bills) > self.returnBillsNum:
                returnBillIds = [
                    str(b.id) for b in bills[self.returnBillsNum:len(bills)]
                ]

            returnData = {"bills": returnBills, "ids": returnBillIds}
        else:
            returnData = yield getRecomendBills(bills)

            # if we want to find trucks then return some local drivers.
            if self.findtype == BillType.TRUNK:
                gap = self.config.recommendBillsReturnOnce - len(returnData)
                if gap > 0:
                    localBills = yield self.getLocalTruckBill(
                        getCity(user.homeLocation), gap)
                    returnData.extend(localBills)

        mylog.getlog().info(getLogText("recommend bills return:", len(bills)))
        self.finish(DataProtocol.getSuccessJson(returnData))
示例#38
0
文件: admin.py 项目: buerlab/trunkweb
    def post(self):
        img = self.request.files["file"][0]["body"]
        filename = self.request.files['file'][0]["filename"]
        mylog.getlog().info(getLogText("filename", filename))

        image = Image.open(StringIO.StringIO(buf=img))
        size = image.size
        type = image.format
        mylog.getlog().info(getLogText("size", size))
        mylog.getlog().info(getLogText("type", type))

        filepath = "/secret/driverLicensePic/" + filename + "_" + str(
            int(time.time())) + "." + type.lower()
        image.save(static_path + filepath)
        userid = filename.split("_")[1]
        mylog.getlog().info(getLogText(userid))
        service = self.getDbService()
        service.updateUser(userid,
                           **dict({"driverLicensePicFilePath": filepath}))
        mylog.getlog().info(getLogText("ok"))
        self.write(DataProtocol.getSuccessJson("ok", "json"))
示例#39
0
def getAddrMatchBill(bills):
    '''
    根据用户当前有效的单据查找from,to都匹配的对应单据
    :param user:
    :param excludeBills: 之前已经找到的单据,后面查找时候就要排除掉
    :param bills:
    :return:
    '''
    if bills:
        returnBills = []
        #
        # try:
        #     conditions = []
        #     for bill in bills:
        #         cond = {"fromAddr":bill.fromAddr, "toAddr":bill.toAddr}
        #         #载重与货物重量匹配的条件
        #         cond.update(self.getLoadMatchCondition(user, bill))
        #         conditions.append(cond)
        #     limitLength = self.config.recommendBillsReturnOnce
        #     returnBills = yield Bill.objects(self.getQueryFromBase(user, excludeBills, {"$or":conditions}))\
        #                         .limit(limitLength).to_list(limitLength)
        # except Exception, e:
        #     print "QUERY ERROR :", e.message


        # 遍历用户正在等待中的单子
        for bill in bills:
            matchBills = BillMatchController().getMatchBills(bill)
            for bId in matchBills:
                if bId:
                    matchBill = yield Bill.get(bId)
                    #如果是车单,用户当前车辆的载重小于货重,或者 货单, 货重大于车单的载重就排除
                    if matchBill:
                        returnBills.append(matchBill)

        mylog.getlog().info(getLogText("----get addr match", len(returnBills)))
        raise Return(returnBills)
    else:
        raise Return([])
示例#40
0
文件: admin.py 项目: buerlab/trunkweb
    def get(self):
        filename = self.get_argument("filename", None)
        keyword = self.get_argument("keyword", None)
        if filename is None:
            self.write(
                DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR,
                                     "args is invalid"))
            return

        filePath = self.cur_file_dir() + "/log/" + filename
        print "GetLogHandler", filename, keyword, filePath
        if os.path.isfile(filePath):
            try:
                fp = open(filePath, "r")
                ret = fp.readlines()
                self.write(DataProtocol.getSuccessJson(ret, "json"))
                fp.close()
            except:
                self.write(DataProtocol.getJson(DataProtocol.FILE_ERROR))
                mylog.getlog().exception(getLogText("GetLogHandler exception"))
        else:
            self.write(DataProtocol.getJson(DataProtocol.FILE_ERROR, "文件不存在"))
示例#41
0
    def onCall(self, **kwargs):
        mylog.getlog().info(getLogText("get recomend bills"))
        usertype = self.getUserType()
        user = yield self.getUser()
        if not user:
            self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
            raise Return(None)

        self.findtype = matchBillType(oppsiteUserType(usertype))

        self.config = yield Config.shared()
        self.userBills = yield user.getBills()
        for id in user.getAttr("BillsRecord")[0:10]:
            bill = yield Bill.get(id)
            self.recordBills.append(bill)

        bills = yield getBillsToRecomend(user, self.config)

        if "format" in kwargs and kwargs["format"] == "ids":
            #slice
            sortBills, returnBillIds = bills[0:self.returnBillsNum], []
            returnBills = yield getRecomendBills(sortBills)
            if len(bills)>self.returnBillsNum:
                returnBillIds = [str(b.id) for b in bills[self.returnBillsNum:len(bills)]]

            returnData = {"bills":returnBills, "ids":returnBillIds}
        else:
            returnData = yield getRecomendBills(bills)


            # if we want to find trucks then return some local drivers.
            if self.findtype == BillType.TRUNK:
                gap = self.config.recommendBillsReturnOnce - len(returnData)
                if gap > 0:
                    localBills = yield self.getLocalTruckBill(getCity(user.homeLocation), gap)
                    returnData.extend(localBills)

        mylog.getlog().info(getLogText("recommend bills return:", len(bills)))
        self.finish(DataProtocol.getSuccessJson(returnData))
示例#42
0
def getAddrMatchBill(bills):
    '''
    根据用户当前有效的单据查找from,to都匹配的对应单据
    :param user:
    :param excludeBills: 之前已经找到的单据,后面查找时候就要排除掉
    :param bills:
    :return:
    '''
    if bills:
        returnBills = []
        #
        # try:
        #     conditions = []
        #     for bill in bills:
        #         cond = {"fromAddr":bill.fromAddr, "toAddr":bill.toAddr}
        #         #载重与货物重量匹配的条件
        #         cond.update(self.getLoadMatchCondition(user, bill))
        #         conditions.append(cond)
        #     limitLength = self.config.recommendBillsReturnOnce
        #     returnBills = yield Bill.objects(self.getQueryFromBase(user, excludeBills, {"$or":conditions}))\
        #                         .limit(limitLength).to_list(limitLength)
        # except Exception, e:
        #     print "QUERY ERROR :", e.message

        # 遍历用户正在等待中的单子
        for bill in bills:
            matchBills = BillMatchController().getMatchBills(bill)
            for bId in matchBills:
                if bId:
                    matchBill = yield Bill.get(bId)
                    #如果是车单,用户当前车辆的载重小于货重,或者 货单, 货重大于车单的载重就排除
                    if matchBill:
                        returnBills.append(matchBill)

        mylog.getlog().info(getLogText("----get addr match", len(returnBills)))
        raise Return(returnBills)
    else:
        raise Return([])
示例#43
0
    def getLocalTruckBill(self, location, num):
        drivers = yield User.objects({"id":{"$ne":ObjectId(self.getCurrUserId())}, "trunks":{"$not":{"$size":0}}, \
                                      "homeLocation":re.compile(r"^"+location)}).limit(num).to_list(num)

        mylog.getlog().info(getLogText("-----recommend local:", len(drivers)))
        returnBills = []
        if drivers:
            for driver in drivers:
                currTruck = driver.getCurrTruck()
                if currTruck:
                    bill = Bill()
                    bill.trunkType = currTruck["type"]
                    bill.trunkLength = currTruck["length"]
                    bill.trunkLoad = currTruck["load"]
                    driver.currType = UserType.DRIVER
                    driverData = driver.to_user_base_data()
                    # print "driver:", driver.ids
                    driverLocs = yield Location.objects({"userId":str(driver.id)}).sort([("timestamp", -1)]).limit(1).to_list(1)
                    # driverLoc = yield Location.get_collection().find_one({"userId":str(driver.id)})
                    if driverLocs:
                        driverData.update({"location":driverLocs[0].to_client()})
                    returnBills.append(createRecommendBill(driverData, bill.to_client(), RecomendBillType.LOCAL))

        raise Return(returnBills)
示例#44
0
    def sendBill(self, bill):
        mylog.getlog().info("----bill match controller send bill")
        matchCity(self.billMatchMap, bill)
        matchBillIds = self.getMatchBills(bill)
        if len(matchBillIds) > 0:
            mylog.getlog().info("----%d match" % len(matchBillIds))
            self.readyToJPush(bill)

            for billId in matchBillIds:
                iterBill = yield Bill.get(billId)
                if iterBill:
                    self.readyToJPush(iterBill)
                    if bill.phoneNum and iterBill.phoneNum and bill.phoneNum != iterBill.phoneNum:
                        mylog.getlog().info(
                            "----send bill and ready to text msg")
                        self.readyToTextMsg(bill, iterBill)
                        self.readyToTextMsg(iterBill, bill)
示例#45
0
def dbserviceLog(*arg):
    prefix = tuple(["DbServiceLog:"])
    arg = prefix + arg
    mylog.getlog().info(getLogText(arg))
示例#46
0
 def get(cls, str_id):
     try:
         query = cls.query_dict_to_db({"id":str_id})
     except Exception, e:
         mylog.getlog().error("DOCEMENT GET ERROR")
         raise Return(None)
示例#47
0
# @coroutineDebug
# @coroutine
# def initAppConf():
#     conf = yield Config.objects().one()
#     if not conf:
#         conf = Config()
#         conf.currUse = True
#         yield conf.save()
#
#     AppConf.conf = conf

writePid()

if __name__ == "__main__":
    mylog.getlog().info("application start ,http://115.29.8.74:9288")
    connection = connect("mongodb://"+options.dbuser+":"+options.dbpsw+"@"+options.dbaddr+"/"+options.dbname)

    server = HTTPServer(application, xheaders=True)
    server.listen(app_server_port)

    #初始化billmatchmap,建立一个单子匹配的map
    BillMatchController().initFromDB()
    initBillAnalysis()

    msJobs = tornado.ioloop.PeriodicCallback(jobsUpdate, 100)
    msJobs.start()

    # minJobs = tornado.ioloop.PeriodicCallback(jobsEveryMin, 10*1000)
    # minJobs.start()
示例#48
0
 def post(self):
     service = self.getDbService()
     mylog.getlog().info(getLogText(service))
     self.write("you make it")
示例#49
0
    :param user:
    :param excludeBills:
    :param location:
    :return:
    '''
    try:
        query = {"fromAddr":re.compile(r"^"+location)}
        query.update(getLoadMatchCondition(user))

        findType = matchBillType(oppsiteUserType(user.currType))
        bills = yield Bill.objects(getQueryFromBase(str(user.id), findType, excludeBills, query))\
                                    .limit(returnLimit).to_list(returnLimit)
    except Exception, e:
        print "lOCAL EROOR:", e.message

    mylog.getlog().info(getLogText("----get location%s match"%location, len(bills)))
    raise Return(bills)

def calWeight(config, user, userBills, recordBills, bill):
    weight = 0
    weight += evalBillMatchWeight(config, userBills, bill)
    weight += evalLocationWeight(config, user, bill)
    weight += evalBillRecordWeight(config, recordBills, bill)
    weight += evalTimeWeight(config, bill)
    weight += evalStarWeight(config, user, bill)
    weight += evalTrunkVerifiedWeight(config, user)
    weight += evalTrunkPicVerifiedWeight(config, user)
    weight += evalDriverLiscenseVerifiedWeight(config, user)
    weight += evalIDVerifiedWeight(config, user)
    return weight
示例#50
0
 def getAttr(self, attrName):
     try:
         return self[self.currType+str(attrName)]
     except Exception, e:
         mylog.getlog().info("user get attr error:"+e.message)
         raise ValueError("get attr error!!!")
示例#51
0
                kwargs[k] = self.formatValue(v[-1])

            # print "kwargs",kwargs
            if self.validateParams(kwargs):
                try:
                    JPushService.initPush(self.getUserType())
                    ret = self.onCall(**kwargs)
                    if isinstance(ret, Future):
                        yield ret
                except (TypeError, KeyError) as e:
                    self.finish(DataProtocol.getJson(DataProtocol.DATAPROTOCOL_ERROR))
                except Exception, e:
                    pass
            else:
                self.finish(DataProtocol.getJson(DataProtocol.ARGUMENT_ERROR))
        except Exception, e:
            mylog.getlog().error(e)
            mylog.getlog().exception(getLogText("BaseHandler dispatch exception"))
            self.finish("exception caught!!")

    @coroutine
    def get(self, *args, **kwargs):
        yield self.dispatch()

    @coroutine
    def post(self, *args, **kwargs):
        yield self.dispatch()

    def onCall(self, *args, **kwargs):
        self.finish("Under construction.")