Esempio n. 1
0
def main():
    R = RedisClass()
    server_list = R.get_socket_sercerIP()
    # print("start_client......", client_id)
    print(server_list)
    # client_ioloop = ioloop.IOLoop.instance()
    c1 = {}
    # for i in range(len(server_list)):
    i = 0
    a = SocketClientModel(client_id, server_list[i]['label'],
                          server_list[i]['host'], server_list[i]['port'])
    a.start()
    # c1 = SocketClientModel(client_id)
    #     yield c1["c"+str(i)].sock_while()
    #     pass

    # yield c1.chick(TotalConsoleDist)
    # yield c1.sock_while()
    # client_ioloop.add_handler(ioloop.IOLoop.READ)
    # client_ioloop.start()
    # client_ioloop.run_sync(start)
    # if c1.stream.closed():
    #     yield c1.chick(TotalConsoleDist)
    # else:
    #     break
    # run_client()
    print("exit")
Esempio n. 2
0
def updataMasterCopy():
    R = RedisClass()
    uaidList = R.RH.smembers(config.redis_master_uaid_set)
    M = MasterModel()
    for uaid in uaidList:
        datas2 = yield M.getMaterFollow(uaid)
        yield R.getRedisMaterFollow(datas2)
    return
Esempio n. 3
0
 def setNewMarginCommcand(self, uaid, followid, type):
     from handlers.myredis.redis_class import RedisClass
     CommcandDist = {}
     CommcandDist["fx_type"] = type
     CommcandDist["sendid"] = int(uaid)
     CommcandDist["followid"] = int(followid)
     R = RedisClass()
     yield R.add_Console_list(CommcandDist)
     return
Esempio n. 4
0
    def get(self):
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        Master_flag = self.get_argument('f6')
        Master_key = self.get_argument('f10')
        OrderTicket = self.get_arguments('S0')
        OrderQsid = self.get_arguments('S1')

        # 验证
        R = RedisClass()
        uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
        followid = yield R.get_Mater_uaid(Master_key)
        followid = 0 if followid == None else followid
        logger.debug("uaid:%s" % uaid)
        if uaid > 0 and int(followid) > 0:
            #验证通过
            S = SeperateModel()
            fid = yield S.CheckFollowID(uaid, followid)
            if get_class == "set":
                yield S.delSeperateList(fid)
                order_Tuple_add = []
                for i in range(len(OrderTicket)):
                    #增加订单,元组列表
                    tupleList = (fid, int(OrderTicket[i]), int(OrderQsid[i]))
                    order_Tuple_add.append(tupleList)
                if len(order_Tuple_add) > 0:
                    # 批量增加订单
                    add_flag = yield S.AddSeperateList(order_Tuple_add)
                    if add_flag == True:
                        url_text = "1,"
                    else:
                        url_text = "-4,"
                else:
                    url_text = "0,"
            elif get_class == "get":
                # 获得缓存的分仓数组
                order_dist = yield S.getSeperateOrder(fid)
                if len(order_dist) > 0:
                    url_text = "2,"
                    for order_3 in order_dist:
                        url_text = url_text + str(
                            order_3['orderid']) + "," + str(
                                order_3['qsid']) + ","
                        # upnew_flag = upnew_flag + 1
                else:
                    url_text = "0,"
        else:
            # MD5不相符
            url_text = '-1,'
        logger.debug(url_text)
        self.write(url_text + config.StringEnd)
        self.finish()
Esempio n. 5
0
    def get(self):
        F = ErrorForm(self.request.arguments)
        if F.validate() and F.cla.data == "SendError":
            #交易失败发送提示
            ukid = F.ukid.data
            AccountNumber = F.f2.data
            md5_from = F.f5.data
            key_ma = F.f10.data
            ErrorNumber = F.f8.data
            Language = F.f7.data
            strtext = F.f9.data
            R = RedisClass()
            uaid = yield R.chick_MD5_uaid(str(AccountNumber), md5_from, ukid)
            followid = yield R.get_Mater_uaid(key_ma)
            if int(uaid) > 0 and followid != None:
                M = MasterModel()
                Master_data = yield M.getMasterEmail(followid)
                E = OrderError()
                err_text = E.getErrorText(ErrorNumber, Language)
                sendH = SendmailModel()
                tomail = []
                tomail.append(Master_data['email'])
                if Language == 0:
                    mail_text = ""#跟单账号提示:<BR>
                    mail_text = mail_text + err_text + "<BR>"
                    mail_text = mail_text + strtext + "<BR>"
                    mail_text = mail_text + "请人工检查跟单账号MT4的网络与交易平台是否正常运行.<BR>"
                    mail_text = mail_text + "-----来自[提示发送系统]<BR>"
                    mail_title = "跟单账号" + str(AccountNumber) + "的提示"
                else:
                    mail_text = "Documentary account message:<BR>"
                    mail_text = mail_text + err_text + "<BR>"
                    mail_text = mail_text + strtext + "<BR>"
                    mail_text = mail_text + "Please manually check if the MT4 network and Broker of the documentary account are running normally.<BR>"
                    mail_text = mail_text + "-----From [Prompt Sending System]<BR>"
                    mail_title = "Documentary account " + str(AccountNumber) + " message"
                send_flag = yield sendH.email_send(tomail, mail_text, mail_title)
                if send_flag == True:
                    url_text = "1,1,"
                else:
                    url_text = "0,0,"
            else:
                url_text = "0,0,"
        else:
            # 表单错误
            from models.public.confrom_model import get_ErrorForm
            echo = get_ErrorForm(F)
            logger.error("[SendOrderErrorHandler]:" + echo)
            url_text = "0,0,"

        self.write(url_text + config.StringEnd)
        self.finish()
Esempio n. 6
0
def main():
    R = RedisClass()
    server_list = R.get_socket_sercerIP()
    # print("start_client......", client_id)
    # print(server_list)
    # i = 1
    a = {}
    for i in range(len(server_list)):
        print("start_client......%s" % server_list[i])
        a[server_list[i]['label']] = socketClient(client_id,
                                                  server_list[i]['label'],
                                                  server_list[i]['host'],
                                                  server_list[i]['port'])
        a[server_list[i]['label']].chat({})
Esempio n. 7
0
def updataRedisMasterAll():
    # 写入Master账户ID与订单号集合
    R = RedisClass()
    #清除所有旧数据
    yield R.delete_redis(config.redis_order_set)
    yield R.delete_redis(config.redis_order_dic)
    #获取数据
    order_arr = getMaster()
    #写入
    for order in order_arr:
        R.RH.sadd(config.redis_master_uaid_set, str(order['uaid']))
        R.RH.hset(config.redis_master_uaid_dic, order['key_ma'], str(order['uaid']))
        R.RH.sadd(config.redis_order_set + str(order['uaid']), order['tid'])
        R.RH.hmset(config.redis_order_dic + str(order['tid']), order)
    return
Esempio n. 8
0
 def initClientIP(self, sockname):
     # 获得需要通知的服务器列表
     R = RedisClass()
     G = global_Models()
     sss_list_new = []
     sss_list_old = G.get("socket_server_set")
     if sss_list_old == None:
         sss_list_old = []
     for sss_name in R.RH.smembers("socket_server_set"):
         sss = R.RH.hgetall(sss_name)
         flag = 0
         for sss_name_old in sss_list_old:
             if sss['host'] == sss_name_old['host'] and int(
                     sss['port']) == int(sss_name_old['port']):
                 flag = 1
                 sss_list_new.append(sss_name_old)
         if flag == 0:
             # 不存在则增加
             if sss and (sss['host'], int(sss['port'])) != sockname:
                 # 不是自身服务器
                 sss['time_vol'] = 0
                 sss['flag'] = 0  # 0,无状态;1,接收端,2,发送端
                 sss['me'] = 0  # 0,其他服务器;1,自己本身
             else:
                 sss['time_vol'] = 0
                 sss['flag'] = 0  # 0,无状态;1,接收端,2,发送端
                 sss['me'] = 1  # 0,其他服务器;1,自己本身
             sss_list_new.append(sss)
     G.set_map("socket_server_set", sss_list_new)
     return
Esempio n. 9
0
def setRedisProduct(datas):
    R = RedisClass()
    # print(datas)
    for Pdata in datas:
        # print(Pdata)
        R.RH.set(redis_qq_pid + str(Pdata['pid']), Pdata['qq'])
        R.RH.set(redis_version_pid + str(Pdata['pid']), Pdata['version'])
Esempio n. 10
0
    def get(self):
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        umail = self.get_argument('f11', "")
        par = r'^[\.a-zA-Z0-9_\-]{1,30}@[a-zA-Z0-9_\-]+\.([a-zA-Z0-9_\-]{1,5})$'
        par2 = r'.*\.(com|cn|net|org|gov|edu|top)$'
        if re.match(par, umail) and re.match(par2, umail):
            #邮箱验证成功
            R = RedisClass()
            uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
            # print(uaid)
            if uaid > 0:
                sendH = SendmailModel()
                # mail_key = str(random.randint(100000, 999999))
                mail_key = "".join(random.sample('123567890', 6))
                mail_text = """验证码:
                
                """
                mail_text = mail_text + mail_key
                mail_text = mail_text + """
                
                主策略账号注册或登陆使用,请不要将验证码转发或给其他人查看!!!!!
                -----来自[跟单交易多账户管理系统]"""
                tomail = []
                tomail.append(umail)
                send_flag = yield sendH.email_send(tomail, mail_text,
                                                   "主策略账号登陆验证码")
                if send_flag == True:
                    md5_str = mail_key + AccountNumber + str(
                        config.TineMd5Info)
                    str_md5 = hashlib.md5(
                        md5_str.encode(encoding='UTF-8')).hexdigest()
                    R.RH.set(config.redis_session_uaid_set + str(uaid),
                             mail_key,
                             ex=config.SessionsOutTime)
                    url_text = "1," + str_md5 + ","
                else:
                    url_text = "0,-1,"
            else:
                url_text = "0,-2,"
        else:
            url_text = "0,-3,"

        self.write(url_text + config.StringEnd)
        self.finish()
Esempio n. 11
0
    def post(self):
        type = self.get_argument("type", "")
        echo_dist = {}
        if type == "sign_out":
            # 退出
            self.session.delete()
            # self.session['web_uid'] = None
            # self.session['web_uaid'] = None
            # self.session['web_key_ma'] = None
            # self.session['web_account'] = None
            # self.session['web_email'] = None
            # self.session['web_uname'] = None
            echo_dist['reponse_status'] = 5
            echo_dist['echo'] = self.locale.translate("退出成功")

        else:
            #登陆
            F = LoginForm(self.request.arguments)
            if F.validate():#and F.cla.data == "SendError"
                R = RedisClass()
                mail_key = R.RH.get(config.redis_session_uaid_set + str(F.umail.data))
                R.RH.delete(config.redis_session_uaid_set + str(F.umail.data))
                # 验证码检查
                if mail_key == F.pword.data:
                    M = MasterModel()
                    m_data = yield M.checkMaterMail(F.umail.data)
                    # print(m_data)
                    if len(m_data) == 0:
                        echo_dist['reponse_status'] = 0
                        echo_dist['echo'] = self.locale.translate("策略邮箱未注册")
                    else:
                        self.session['web_uid'] = m_data[0]['uid']
                        uaid_list = ""
                        key_ma_list = ""
                        ma_list = ""
                        for data in m_data:
                            uaid_list = uaid_list + str(data['uaid']) + ","
                            key_ma_list = key_ma_list + data['key_ma'] + ","
                            ma_list = ma_list + data['account'] + ","
                        self.session['web_uaid'] = uaid_list
                        # self.session['web_key_ma'] = key_ma_list
                        # self.session['web_account'] = ma_list
                        self.session['web_email'] = F.umail.data
                        self.session['web_uname'] = m_data[0]['uname']
                        from models.public.headers_model import LogsModel
                        LogsModel.addMysqlLog("login", "loging", str(m_data[0]['uid']), self.get_user_ip())
                        echo_dist['echo'] = self.locale.translate("登陆成功")
                        echo_dist['reponse_status'] = 5
            else:
                # 表单错误
                from models.public.confrom_model import get_ErrorForm
                echo_dist['echo'] = get_ErrorForm(F)
                echo_dist['reponse_status'] = 1
        self.write(json.dumps(echo_dist))
        self.finish()
Esempio n. 12
0
    def get(self):
        echo_dist = {}
        page_main = {}
        page_main['lang'] = self.get_lang()
        page_main['title_website'] = config.WEBSITE_NAME
        if self.session['web_uid'] == None:
            yield self.redirect("/index")
            return
        else:
            F = AccountsForm(self.request.arguments)
            # print(F.fx_type.data)
            if F.validate():
                page_main['prc_type'] = F.fx_type.data
                cookie_dist = self.getCookie()
                page_main.update(cookie_dist)
                if F.fx_type.data == "list_pricing":
                    # 列出所有的价格列表
                    page_main['title_type'] = self.locale.translate("我要续费")
                    A = AccountsModel()
                    page_main['data'] = yield A.getProductInfoList(config.PID)
                    yield self.render("user/index_pricing_list.html", page_main=page_main, session=self.session)
                    return
                elif F.fx_type.data == "buy_price_one":
                    # 购买订单
                    page_main['title_type'] = self.locale.translate("我要续费")
                    page_main['fx_id'] = F.fx_id.data
                    A = AccountsModel()
                    page_main['data'] = yield A.getProductInfo(F.fx_id.data)
                    yield self.render("user/index_buy2.html", page_main=page_main, session=self.session)
                    return
                elif F.fx_type.data == "list_account_order":
                    page_main['th_num'] = 9
                    page_main['title_type'] = self.locale.translate("购买记录")
                    page_main['fx_id'] = 9 if F.fx_id.data == None else F.fx_id.data
                    R = RedisClass()
                    endtime = R.RH.get(config.redis_ua_pid_endtime + cookie_dist["current_strategy"])
                    if endtime == None :
                        endtime = 0
                    import time
                    page_main['endtime'] = time.strftime("%Y-%m-%d", time.localtime(int(
                        float(endtime))))
                    yield self.render("user/index_account_order_list.html", page_main=page_main, session=self.session)
                    return
                else:
                    self.redirect("/index")
                    return

            else:
                # 表单错误
                from models.public.confrom_model import get_ErrorForm
                echo_dist['echo'] = get_ErrorForm(F)
                logger.debug(echo_dist['echo'])
                echo_dist['reponse_status'] = 1
                self.redirect("/index")
                return
Esempio n. 13
0
    def get(self):
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        # Master_flag = self.get_argument('f6')
        key_ma = self.get_argument('f10', "")
        R = RedisClass()
        uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
        etext = ""
        if uaid > 0:
            #验证通过
            # M = MasterModel()
            followid = R.get_Mater_uaid(key_ma)
            # followid = yield M.getMaterUaid(R, key_ma)
            if followid != None:
                Mflag = yield R.chick_MaterAuthorize(followid, uaid)
                if Mflag == True:
                    order_arr = yield R.get_orders_redis(followid)
                    etext2 = yield self.format_ordertext(order_arr)
                    etext = etext + "1,0,0,0,0,0,0,0,0," + etext2
                else:
                    etext = etext + "-2,0,0,0,0,0,0,0,0,"
            else:
                etext = etext + "-1,0,0,0,0,0,0,0,0,"

        else:
            etext = etext + "0,0,0,0,0,0,0,0,0,"
        self.write(etext + config.StringEnd)
        self.finish()
Esempio n. 14
0
    def get(self):
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        umail = self.get_argument('f11', "")
        Ckey = self.get_argument('f12', "")
        pid = self.get_argument('s0', "0")

        par = r'^[\.a-zA-Z0-9_\-]{1,30}@[a-zA-Z0-9_\-]+\.([a-zA-Z0-9_\-]{1,5})$'
        echotext = ""
        if re.match(par, umail):
            #邮箱验证成功
            R = RedisClass()
            uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
            if uaid > 0:
                mail_key = R.RH.get(config.redis_session_uaid_set + str(uaid))
                if mail_key == Ckey:
                    #验证成功
                    M = MasterModel()
                    #检查email账号注册并登陆
                    key_ma = yield M.getVcmial(umail, uaid)
                    if key_ma != None:
                        # 提取跟单的账号列表
                        yield R.insert_master_uaid(key_ma, uaid)
                        datas = yield M.getMaterFollow(uaid)
                        echotext2 = yield R.getRedisMaterFollow(datas)
                        maxnum = yield M.getMaterCopyNum(config.PID, uaid)
                        echotext = echotext + str(maxnum) + "_" + str(
                            config.ERROR_TIME) + "," + key_ma + "," + echotext2
                    else:
                        echotext = "-2,0,"
                else:
                    echotext = "-3,0,"
            else:
                echotext = "-4,0,"
        else:
            echotext = "-5,0,"
        self.write(echotext + config.StringEnd)
        self.finish()
Esempio n. 15
0
 def __init__(self, logger, client_id, io_loop=None):
     self.client_id = client_id
     self.host = config.server_list[client_id]['url']
     self.port = config.server_list[client_id]['port']
     self.flag = False
     self.time_vol = 0
     self.MD5info = "WZ12KfOkMIbwXiRm84gGIUHGEPie4klyX"
     self.R = RedisClass()
     self.io_loop = io_loop
     self.sock_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
     self.stream = iostream.IOStream(self.sock_fd)
     self.stream.set_close_callback(self.on_receive)
     self.logger = logger
Esempio n. 16
0
    def post(self):
        F = SendEmailForm(self.request.arguments)
        echo_dist = {}
        if F.validate():  #and F.cla.data == "SendError"
            #邮箱验证成功
            R = RedisClass()
            sendH = SendmailModel()
            M = MasterModel()
            m_data = yield M.checkMaterMail(F.umail.data)
            logger.debug(m_data)
            if len(m_data) == 0:
                # 策略邮箱不存在
                echo_dist['reponse_status'] = 4
            else:
                # mail_key = str(random.randint(100000, 999999))
                mail_key = "".join(random.sample('123567890', 6))
                mail_text = self.locale.translate("主策略账号登陆验证码")
                mail_text = mail_text + """:
                
                """
                mail_text = mail_text + mail_key
                mail_text = mail_text + """
                
                """
                mail_text = mail_text + self.locale.translate(
                    "请不要将验证码转发或给其他人查看")
                mail_text = mail_text + """!!!!!
                
                -----"""
                mail_text = mail_text + self.locale.translate(
                    "来自[跟单交易多账户管理系统]")
                tomail = []
                tomail.append(F.umail.data)
                send_flag = yield sendH.email_send(
                    tomail, mail_text, self.locale.translate("主策略账号登陆验证码"))
                if send_flag == True:
                    R.RH.set(config.redis_session_uaid_set + str(F.umail.data),
                             mail_key,
                             ex=config.SessionsOutTime)
                    echo_dist['reponse_status'] = 5  #  发送成功
                else:
                    echo_dist['reponse_status'] = 2  # 发送失败
        else:
            # 表单错误
            from models.public.confrom_model import get_ErrorForm
            echo_dist['echo'] = get_ErrorForm(F)
            echo_dist['reponse_status'] = 0  # 输入错误

        self.write(json.dumps(echo_dist))
        self.finish()
Esempio n. 17
0
 def set_Header(self, user_request, userid, temp_uid):
     R = RedisClass()
     if userid == None:
         R.RH.hset(
             config.redis_user_headers_dic, temp_uid,
             user_request.headers['Accept-Language'] + " " +
             user_request.headers['User-Agent'] + " " +
             user_request.remote_ip)
     else:
         R.RH.hset(
             config.redis_user_headers_dic, userid,
             user_request.headers['Accept-Language'] + " " +
             user_request.headers['User-Agent'] + " " +
             user_request.remote_ip)
     return
Esempio n. 18
0
    def post(self):
        echo_dist = {}
        if self.session['web_uid'] == None:
            echo_dist['reponse_status'] = -1
        else:
            #
            F = AccountsForm(self.request.arguments)
            if F.validate():  #and F.cla.data == "SendError"
                from models.user.strategy_model import StrategyModel
                S = StrategyModel()
                echo_dist['reponse_status'] = 5
                cookie_dist = self.getCookie(1)
                page_papa = {}
                page_papa['start'] = F.start.data
                page_papa['length'] = F.length.data
                page_papa['search'] = self.get_argument('search[value]', '0')
                page_papa['fx_type'] = F.fx_type.data
                page_papa['fx_id'] = F.fx_id.data
                if F.fx_type.data == "edit_authorization":
                    # 修改授权
                    R = RedisClass()
                    flag = yield S.edit_authorization(
                        self.session['web_uid'], self.get_user_ip(),
                        cookie_dist["current_strategy"], F.fx_id.data)
                    if flag < 0:
                        echo_dist['reponse_status'] = flag
                    else:
                        logger.debug("edit_authorization:%s,%s,%s" %
                                     (cookie_dist["current_strategy"],
                                      str(F.fx_id.data), str(flag)))
                        # R.RH.hset(config.redis_master_uaid_Hash + str(self.get_secure_cookie("current_strategy"),
                        #                                               encoding="utf-8"), str(F.fx_id.data), str(flag))
                        yield R.set_MaterFollow(
                            cookie_dist["current_strategy"], str(F.fx_id.data),
                            str(flag))
                        echo_dist['echo'] = flag
                elif F.fx_type.data == "list_master":
                    echo_dist['data'] = yield S.getStrategyListPage(
                        self.session['web_uid'], page_papa, 1)
                    if len(echo_dist.get('data')) > 0:
                        if 'allnum' in echo_dist['data'][-1]:
                            allnum = echo_dist['data'].pop()
                            logger.debug(allnum)
                            echo_dist["recordsTotal"] = allnum['allnum']
                            echo_dist["recordsFiltered"] = allnum['allnum']
                            # s_data.pop()
                    else:
                        echo_dist['echo'] = self.locale.translate("无数据")
                        echo_dist['reponse_status'] = 5

                elif F.fx_type.data == "click_delete":
                    echo_dist['reponse_status'] = yield S.edit_master_delete(
                        self.session['web_uid'], self.get_user_ip(),
                        F.fx_id.data)
                    if echo_dist['reponse_status'] != 5:
                        echo_dist['echo'] = self.locale.translate("操作失败")
                elif F.fx_type.data == "delete_follow_flag":
                    echo_dist['reponse_status'] = yield S.edit_follow_delete(
                        cookie_dist["current_strategy"],
                        self.session['web_uid'], self.get_user_ip(),
                        F.fx_id.data)
                    if echo_dist['reponse_status'] != 5:
                        echo_dist['echo'] = self.locale.translate("操作失败")
            else:
                # 表单错误
                from models.public.confrom_model import get_ErrorForm
                echo_dist['echo'] = get_ErrorForm(F)
                echo_dist['reponse_status'] = 1
        # from models.public.headers_model import DateEncoder
        # yield self.write(json.dumps(echo_dist, cls=DateEncoder))
        self.write(json.dumps(echo_dist))
        self.finish()
Esempio n. 19
0
 def __init__(self):
     RedisClass.__init__(self)
     self.msg_disc = {
         'uaid': 0
     }
Esempio n. 20
0
 def __del__(self):
     RedisClass.__del__(self)
Esempio n. 21
0
    def get(self):
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        copy_account = self.get_argument('f11', "")
        edit_flag = self.get_argument('f12', "")
        md5_from2 = self.get_argument('f13', "")
        MasterKey = self.get_argument('f14', "")
        pid = self.get_argument('s0', 0)
        echotext = ""
        if get_class == "edit":
            # 修改授权
            # 二次较检
            md5_str = AccountNumber + copy_account + str(config.TineMd5Info)
            str_md5 = hashlib.md5(md5_str.encode(encoding='UTF-8')).hexdigest()
            if str_md5 == md5_from2:
                # 信息验证成功,进行相关操作
                R = RedisClass()
                followid = yield R.chick_MD5_uaid(AccountNumber, md5_from,
                                                  ukid)
                if followid > 0:
                    m_flag = yield R.chick_MaterAuthorize(
                        followid, copy_account)
                    if edit_flag == "1" and m_flag == True:
                        echotext = "0,0,"
                    elif edit_flag == "0" and m_flag == False:
                        echotext = "0,0,"
                    else:
                        #需要修改授权
                        M = MasterModel()
                        flag = R.RH.hget(
                            config.redis_master_uaid_Hash + str(followid),
                            str(copy_account))

                        if flag == 1 or flag == "1":
                            mflag = yield M.setMaterAuthorize(
                                followid, copy_account, 0)
                            if mflag == True:
                                R.RH.hset(
                                    config.redis_master_uaid_Hash +
                                    str(followid), str(copy_account), "0")
                                echotext = "1,0,"
                            else:
                                echotext = "-3,0,"
                        else:
                            # 判断超过授权数量
                            copy_max_num = yield M.get_copy_num(
                                R.RH.hgetall(config.redis_master_uaid_Hash +
                                             str(followid)))
                            master_max_num = yield M.getMaterCopyNum(
                                pid, followid)
                            if copy_max_num >= master_max_num:
                                # 授权数量超过
                                echotext = "-6,0,"
                            else:
                                mflag = yield M.setMaterAuthorize(
                                    followid, copy_account, 1)
                                if mflag == True:
                                    R.RH.hset(
                                        config.redis_master_uaid_Hash +
                                        str(followid), str(copy_account), "1")
                                    echotext = "1,1,"
                                else:
                                    echotext = "-3,0,"
                else:
                    echotext = "-4,0,"
            else:
                echotext = "-5,0,"
        elif get_class == "apply":
            # 申请授权
            # 二次较检
            md5_str = AccountNumber + MasterKey + str(config.TineMd5Info)
            str_md5 = hashlib.md5(md5_str.encode(encoding='UTF-8')).hexdigest()
            if str_md5 == md5_from2:
                #信息验证成功
                R = RedisClass()
                uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
                if uaid > 0:
                    M = MasterModel()
                    followid = yield R.get_Mater_uaid(MasterKey)
                    if followid == None:
                        mflag = False
                    else:
                        mflag = yield R.chick_MaterAuthorize(followid, uaid)
                    if mflag == True:
                        #已经授权
                        echotext = "2," + str(
                            config.ERROR_TIME) + ",9947" + str(followid) + ","
                    else:
                        if followid != None:
                            # 有MasterKey的策略,进行申请操作
                            yield R.insert_master_uaid(MasterKey, followid)
                            #检查数据库
                            # print(followid,uaid)
                            yield M.checkMaterFollow(followid, uaid)
                            # 更新Redis
                            yield R.set_MaterFollow(followid, uaid, 0)
                            echotext = "1,0,"
                        else:
                            #无效MasterKey,找不到相关策略
                            echotext = "-3,0,"
                else:
                    echotext = "-4,0,"
            else:
                echotext = "-5,0,"

        self.write(echotext + config.StringEnd)
        self.finish()
Esempio n. 22
0
    def post(self):
        echo_dist = {}
        F = LoginForm(self.request.arguments)
        if F.validate():
            S = SwissquoteModel()
            if F.fx_type.data == "signout":
                # 退出
                self.session.delete()
                # self.session['swissquote_uid'] = None
                echo_dist['reponse_status'] = 5
                echo_dist['echo'] = self.locale.translate("退出成功")

            elif F.fx_type.data == "sendmail":
                from models.user.sendmail_model import SendmailModel
                import random
                sendH = SendmailModel()
                mail_key = "".join(random.sample('123567890', 6))
                mail_text = self.locale.translate("返佣管理系统登陆验证码")
                mail_text = mail_text + """:
    
                                """
                mail_text = mail_text + mail_key
                mail_text = mail_text + """
    
                                """
                mail_text = mail_text + self.locale.translate(
                    "请不要将验证码转发或给其他人查看")
                mail_text = mail_text + """!!!!!
    
                                -----"""
                mail_text = mail_text + self.locale.translate("来自[返佣管理系统]")
                tomail = []
                tomail.append(F.umail.data)
                send_flag = yield sendH.email_send(
                    tomail, mail_text, self.locale.translate("返佣管理系统登陆验证码"))
                if send_flag == True:
                    R = RedisClass()
                    R.RH.set(config.redis_session_uaid_set + str(F.umail.data),
                             mail_key,
                             ex=config.SessionsOutTime)
                    echo_dist['reponse_status'] = 5  # 发送成功
                else:
                    echo_dist['reponse_status'] = 2  # 发送失败

            else:
                #登陆
                R = RedisClass()
                mail_key = R.RH.get(config.redis_session_uaid_set +
                                    str(F.umail.data))
                R.RH.delete(config.redis_session_uaid_set + str(F.umail.data))
                # 验证码检查
                if mail_key == F.pword.data:
                    m_data = yield S.CheckMailAccount(F.umail.data)
                    # print(m_data)
                    if m_data == None:
                        #策略邮箱未注册
                        uid = yield S.AddMailAccount(F.umail.data)
                        if uid == None:
                            echo_dist['reponse_status'] = 0
                            echo_dist['echo'] = self.locale.translate("邮箱注册失败")
                        else:
                            self.session['swissquote_uid'] = uid
                            echo_dist['reponse_status'] = 5
                            echo_dist['echo'] = self.locale.translate(
                                "新注册并登陆成功")
                    else:
                        # 已经有账号
                        self.session['swissquote_uid'] = m_data['uid']
                        echo_dist['echo'] = self.locale.translate("登陆成功")
                        echo_dist['reponse_status'] = 5

                    from models.public.headers_model import LogsModel
                    LogsModel.addMysqlLog("login",
                                          "loging", str(m_data['uid']),
                                          self.get_user_ip())
                else:
                    echo_dist['reponse_status'] = 0
                    echo_dist['echo'] = self.locale.translate("登录失败")

        else:
            # 表单错误
            from models.public.confrom_model import get_ErrorForm
            echo_dist['echo'] = get_ErrorForm(F)
            echo_dist['reponse_status'] = 1
        self.write(json.dumps(echo_dist))
        self.finish()
Esempio n. 23
0
 def __init__(self):
     self.R = RedisClass()
Esempio n. 24
0
class UserModel():
    def __init__(self):
        self.R = RedisClass()

    @gen.coroutine
    def GetAccount(self, users):
        # 查交易账号存在与否,并返回有效连接MD5—KEY
        with (yield pool.Connection()) as conn:
            with conn.cursor() as cursor:
                # users['ptname']db.cursor(MySQLdb.cursors.DictCursor)
                sql = "SELECT uaid,pid,account FROM usercode WHERE ptname='%s' AND account=%s AND accountserver='%s' AND vipid=1" % (
                    users['ptname'], users['account'], users['accountserver'])
                # print(sql)
                yield cursor.execute(sql)
                datas = cursor.fetchone()
                # print(datas)
                if datas != None:
                    # 账号存在
                    # print(datas)
                    # 验证产品,生成回复
                    account_arr = yield self.GetAcountPinfo(
                        conn, users, datas['uaid'])
                    if account_arr != None:
                        # 查询策略的参数等

                        M = MasterModel()
                        if users['Master_flag'] == "1":
                            Mater_parameter = yield M.getMaterInfo(
                                datas['uaid'], users['pid'])
                            account_arr['max_num'] = Mater_parameter[
                                'mater_max_num']
                            account_arr['endtime'] = Mater_parameter['endtime']
                        else:
                            account_arr['max_num'] = 0
                            account_arr['endtime'] = None
                        # print(account_arr)
                        echotext = yield self.getOdata(account_arr,
                                                       users['account'],
                                                       datas['uaid'],
                                                       users['ukid'],
                                                       users['get_class'])
                    else:
                        echotext = "-9,0,0,0,0,0"
                else:
                    #账号不存在,新增账号
                    # 先验证平台与服务器
                    pt_id = yield self.GetPlatfrom(conn, users['ptname'])
                    # print(pt_id)
                    if pt_id != 0:
                        # 验证服务器
                        pfuid = yield self.GetAccountsServer(
                            conn, users['accountserver'], pt_id)
                        if pfuid != 0:
                            # 新增交易账户users_account
                            up_date = datetime.datetime.now().strftime(
                                '%Y-%m-%d %H:%M:%S')
                            user_url = users['accountserver'] + users['ptname']
                            try:
                                sql3 = "INSERT INTO users_account(uid,pt_id,pfuid,account,allname,balance,credit,quity," \
                                       "profit,margin,xs,ea,moni,gangan,huobi,huibimodel,stopoutlevel,stopoutmode,minlot,maxlot,user_url," \
                                       "ibpt1,adminstate,agent_time,user_update,onlinetime,start_balance) VALUES " \
                                       "(%s,%s,%s,%s,'%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,'%s','%s',%s,%s,%s,%s,'%s',%s,%s,'%s','%s','%s',%s)"\
                                        % (1, pt_id, pfuid, users['account'], users['allname'], users['balance'],
                                          users['credit'], users['quity'], users['profit'], users['margin'],
                                          users['xs'], users['ea'], users['moni'], users['gangan'], users['huobi'],
                                          users['huibimodel'], users['stopoutlevel'], users['stopoutmode'], users['minlot'], users['maxlot'],
                                          user_url, 1, 0, up_date, up_date, up_date, users['balance'])
                                # print(sql3)
                                yield cursor.execute(sql3)
                                yield conn.commit()
                                uaid = cursor.lastrowid
                            except Exception as err:
                                yield conn.rollback()
                                logger.error(
                                    "[user_model:GetAccount:INSERT]: %s" % err)
                                return None
                            # 验证产品,生成回复
                            account_arr = yield self.GetAcountPinfo(
                                conn, users, uaid)
                            if account_arr != None:
                                echotext = yield self.getOdata(
                                    account_arr, users['account'], uaid,
                                    users['ukid'], users['get_class'])
                                if users['Master_flag'] == "1":
                                    # 加载策略到Redis
                                    O = OrderModel()
                                    # 得到账户的持仓订单
                                    datas2 = yield O.get_PositionOrder(uaid)
                                    # 进行更新redis持仓
                                    yield self.R.set_Master_order(uaid, datas2)
                                    M = MasterModel()
                                    datas3 = yield M.getMaterFollow(uaid)
                                    yield self.R.getRedisMaterFollow(datas3)
                            else:
                                echotext = "-6,0,0,0,0,0,"
                        else:
                            echotext = "-7,0,0,0,0,0,"
                    else:
                        echotext = "-8,0,0,0,0,0,"
        # print(echotext)
        # yield pool.close()
        return echotext

    @gen.coroutine
    def GetPlatfrom(self, conn, ptname):
        # 查询平台
        sql = "SELECT pt_id FROM platfrom WHERE ptname='%s'"
        with conn.cursor() as cursor:
            yield cursor.execute(sql % ptname)
            datas = cursor.fetchone()
            if datas != None:
                return datas['pt_id']
            else:
                try:
                    yield cursor.execute(
                        "INSERT INTO platfrom(ptname) VALUES('%s')" % ptname)
                    newid = conn.insert_id()
                    yield conn.commit()
                    return newid
                except Exception as err:
                    yield conn.rollback()
                    logger.error("[user_model:GetPlatfrom:INSERT]: %s" % err)
                    return 0

    @gen.coroutine
    def GetAccountsServer(self, conn, accountserver, pt_id):
        # 查询交易服务器
        sql = "SELECT pfuid FROM plat_server WHERE accountserver='%s' and pt_id=%s"
        with conn.cursor() as cursor:
            yield cursor.execute(sql % (accountserver, pt_id))
            datas = cursor.fetchone()
            if datas != None:
                return datas['pfuid']
            else:
                try:
                    yield cursor.execute(
                        "INSERT INTO plat_server(accountserver,pt_id) VALUES('%s', %s)"
                        % (accountserver, pt_id))
                    newid = conn.insert_id()
                    yield conn.commit()
                    return newid
                except Exception as err:
                    yield conn.rollback()
                    logger.error("[user_model:GetAccountsServer:INSERT]: %s" %
                                 err)
                    return 0

    @gen.coroutine
    def GetAcountPinfo(self, conn, users, uaid):
        # 查询账户与产品
        up_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql = "SELECT acount_pinfo.pid,acount_pinfo.apflag,acount_pinfo.qq,acount_pinfo.version,acount_pinfo.pflag FROM acount_pinfo WHERE pid=%s AND uaid=%s"
        with conn.cursor() as cursor:
            yield cursor.execute(sql % (users['pid'], uaid))
            datas = cursor.fetchone()
            # print("1:")
            if datas != None:
                try:
                    # 保存account_product,更新在线时间
                    # print(users['minlot'], users['maxlot'])
                    yield cursor.callproc(
                        'updata_ua_onlinedate',
                        (uaid, users['minlot'], users['maxlot'], users['pid'],
                         users['balance'], users['credit'], users['quity'],
                         users['profit'], users['margin'], "@flag"))
                    yield cursor.execute("select @flag")
                    # row = cursor.fetchone()
                    # print("updata_ua_onlinedate:", row)
                except Exception as err:
                    logger.error("[user_model:GetAcountPinfo:update]: %s" %
                                 err)
                return datas
                # 预留远程参数设置
            else:
                # 新增产品到交易账号上
                # sql4 = "SELECT qq,version,probation FROM product WHERE pid=%s"
                # yield cursor.execute(sql4 % users['pid'])
                # datas2 = cursor.fetchone()
                # endtime = (datetime.datetime.now() + datetime.timedelta(days=datas2['probation'])).strftime(
                #     "%Y-%m-%d %H:%M:%S")
                sql3 = "INSERT INTO account_product(pid,uaid,apflag,starttime,onlinetime,lasttime) VALUES(%s,%s,%s,'%s','%s','%s')"
                try:
                    yield cursor.execute(
                        sql3 %
                        (users['pid'], uaid, 1, up_date, up_date, up_date))
                    yield conn.commit()
                    yield cursor.execute(sql % (users['pid'], uaid))
                    datas2 = cursor.fetchone()
                    return datas2
                except Exception as err:
                    yield conn.rollback()
                    logger.error("[user_model:GetAcountPinfo:INSERT]: %s" %
                                 err)
                    return None

    @gen.coroutine
    def getOdata(self, datas, account, uaid, ukid, get_class):
        echotext = ""
        endtime = 0
        if datas != None:
            # 保存account_product,更新在线时间
            echotext0 = str(datas['apflag']) + ","
            # print(datas['endtime'])
            if datas.get('endtime') == None:
                endtime = 0
            else:
                endtime = time.mktime(
                    time.strptime(
                        datas['endtime'].strftime('%Y-%m-%d %H:%M:%S'),
                        "%Y-%m-%d %H:%M:%S"))
            time_md5 = endtime - config.TineMd5Info
            echotext = echotext + str(time_md5) + ","
            # 策略参数
            if datas.get('followParameter') == None:
                datas['followParameter'] = "0"
            echotext = echotext + datas['followParameter'] + ","
            # # 开仓时间段
            # if datas['zd_opentime'] == "" or datas['zd_opentime'] == None:
            #     echotext = echotext + "0,"
            # else:
            #     echotext = echotext + datas['zd_opentime'] + ","
            # 平仓时间段
            if datas.get('zd_closetime') == "" or datas.get(
                    'zd_closetime') == None:
                echotext = echotext + "0,"
            else:
                echotext = echotext + datas.get('zd_closetime') + ","
            echotext = echotext + datas['qq'] + ","
            echotext = echotext + datas['version'] + ","
        else:
            echotext0 = "-10,0,0,0,0,0,"
        md5_time = str(int(time.time()))
        if ukid == "0":
            acount_md5 = str(account) + md5_time
            acount_md5 = hashlib.md5(
                acount_md5.encode(encoding='UTF-8')).hexdigest()
        else:
            acount_md5 = ukid
        self.R.RH.hset(config.redis_acount_md5_dic, acount_md5, uaid)  #dic
        # print("redis_acount_md5_dic",R.RH.hget(config.redis_acount_md5_dic, acount_md5))
        self.R.RH.sadd(config.redis_uaid_set, uaid)  #Set集合
        self.R.RH.set(config.redis_ua_pid_endtime + str(uaid), endtime)  #到期时间
        text_md5 = str(time_md5) + str(account) + str(datas.get('pid'))
        text_md5 = hashlib.md5(text_md5.encode(encoding='UTF-8')).hexdigest()
        # 加密字符
        echotext = echotext0 + text_md5 + "," + echotext + str(
            acount_md5) + ","
        text_md5_2 = hashlib.md5(echotext.encode(encoding='UTF-8')).hexdigest()
        if datas.get('max_num') == None:
            datas['max_num'] = -1
        echotext = echotext + text_md5_2 + "," + md5_time + "," + str(
            datas.get('max_num')) + ","
        if get_class == "login":
            echotext = echotext + self.R.RH.get("server_ip") + "," + str(
                config.SOCKET_PORT) + ","
        # logger.info("getOdata:%s" % echotext)
        return echotext

    @gen.coroutine
    def get1data(self, datas2):
        echotext = ""
        if datas2 != None:
            echotext = echotext + str(datas2['@maxtime']) + "," + str(
                datas2['@maxloss']) + ","
            echotext = echotext + str(datas2['@maxnum']) + "," + str(
                datas2['@fixed']) + ","
            echotext = echotext + str(datas2['@percent']) + "," + str(
                datas2['@rate_min']) + ","
            echotext = echotext + str(datas2['@rate_max']) + "," + str(
                datas2['@reflex']) + ","
            echotext = echotext + str(datas2['@rate']) + "," + str(
                datas2['@allowed_sign']) + "," + str(
                    datas2['@tpsl_flag']) + ","
            echotext = echotext + str(datas2['@parameter_time']) + "," + str(
                datas2['comment']) + ","
        else:
            echotext = "0,0,0,0,0,0,0,0,0,0,0,"
        # logger.info("get1data:%s" % echotext)
        return echotext

    @gen.coroutine
    def CheckAccount(self, users):
        if self.R.RH.hexists(config.redis_acount_md5_dic, users['ukid']):
            datas = {}
            uaid = self.R.RH.hget(config.redis_acount_md5_dic, users['ukid'])
            datas2 = yield self.updataAccount(users, uaid)
            # pp = redis_ua_pid_endtime + str(uaid)
            # print(R.RH.get(redis_ua_pid_endtime + str(uaid)))
            # endtime = int(float(R.RH.get(config.redis_ua_pid_endtime + str(uaid))))
            from models.user.master_model import MasterModel
            M = MasterModel()
            if users['Master_flag'] != "1":
                # 非策略账号
                master_id = yield self.R.get_Mater_uaid(users['MasterKey'])
                comment = yield self.R.get_Mater_Comment(users['MasterKey'])
                if master_id == None:
                    return "-11,0,0,0,0,0,"
                # follow_parameter = yield R.getMaterParameter(master_id, users['pid'])
                follow_parameter = yield M.getMaterInfo(
                    master_id, users['pid'])
                # 加入策略参数
                datas['followParameter'] = str(
                    int(follow_parameter['position_maxnum'])
                ) + "." + follow_parameter['spsl'] + "." + follow_parameter[
                    'reverse'] + "."
                datas['endtime'] = follow_parameter['endtime']
                datas2['comment'] = comment
            else:
                Mater_parameter = yield M.getMaterInfo(uaid, users['pid'])
                datas['max_num'] = Mater_parameter['mater_max_num']
                datas['endtime'] = Mater_parameter['endtime']
                datas2['comment'] = "fx"

            # datas['endtime'] = datetime.datetime.fromtimestamp(endtime)
            datas['pid'] = users['pid']
            datas['apflag'] = 1
            datas['zd_opentime'] = ""
            datas['zd_closetime'] = ""
            datas['qq'] = self.R.RH.get(config.redis_qq_pid +
                                        str(users['pid']))
            datas['version'] = self.R.RH.get(config.redis_version_pid +
                                             str(users['pid']))
            echotext = yield self.getOdata(datas, users['account'], uaid,
                                           users['ukid'], users['get_class'])
            echotext2 = yield self.get1data(datas2)
            # logger.info("CheckAccount:" + echotext + echotext2)
            return echotext + echotext2
        else:
            # 账户未登陆或已经失效
            return "-12,0,0,0,0,0,"

    @gen.coroutine
    def ExitAccount(self, users):
        if self.R.RH.hexists(config.redis_acount_md5_dic, users['ukid']):
            uaid = self.R.RH.hget(config.redis_acount_md5_dic, users['ukid'])
            self.updataAccount(users, uaid)
            self.R.RH.hdel(config.redis_acount_md5_dic, users['ukid'])
            self.R.RH.delete(config.redis_ua_pid_endtime + str(uaid))
            return "1,1,"
        else:
            # 账户未登陆或已经失效
            return "-13,0,0,0,0,0,"

    @gen.coroutine
    def updataAccount(self, users, uaid):
        with (yield pool.Connection()) as conn:
            with conn.cursor() as cursor:
                try:
                    yield cursor.callproc(
                        'updata_follow_parameter',
                        (users['uid'], users['ip'], int(uaid),
                         int(users['maxtime']), int(users['maxloss']),
                         int(users['maxnum']), float(users['fixed']),
                         float(users['percent']), float(users['rate_min']),
                         float(users['rate_max']), int(users['reflex']),
                         float(users['rate']), int(users['allowed_sign']),
                         int(users['parameter_time']), users['MasterKey'],
                         int(users['pid']), float(users['balance']),
                         float(users['credit']), float(users['quity']),
                         float(users['profit']), float(users['margin']),
                         int(users['tpsl_flag']), "@maxtime", "@maxloss",
                         "@maxnum", "@fixed", "@percent", "@rate_min",
                         "@rate_max", "@reflex", "@rate", "@allowed_sign",
                         "@parameter_time", "@tpsl_flag", "@flag"))
                    yield cursor.execute(
                        "SELECT @maxtime,@maxloss,@maxnum,@fixed,@percent,@rate_min,@rate_max,@reflex,@rate,@allowed_sign,@parameter_time,@tpsl_flag,@flag"
                    )
                    row = cursor.fetchone()
                    # print("AA:", row)
                except Exception as err:
                    row = None
                    logger.error("[user_model:updataAccount:update]: %s" % err)
        return row
Esempio n. 25
0
import config
import time
from tornado import ioloop, gen, iostream
# import datetime
# import tormysql
# import pymysql
# from tornado import gen

from handlers.myredis.redis_class import RedisClass

from models.public.headers_model import global_Models
import config
from models.my_socket.my_socket_model import MySocketModel
# def main():
#     # from models.user.order_model import OrderModel
#     # O = OrderModel()
#     # order_num = yield O.get_PositionOrderNum(4490)
#     # S = MySocketModel()
#     # pp = yield S.get_chick_orders2(4495, "089bb6b18604cda2fd8611e085a289c8")
#     print("11")
# if __name__ == '__main__':
#     main()yy = R.RH.hget(config.redis_acount_md5_dic, "449a5dc904bef5315828a0d3ee7dd857")
#getCopyText:{"type":"copyorder","ukid":"449a5dc904bef5315828a0d3ee7dd857","f2":"861649","f5":"e94fe0343a3e495b740419d83343bd2d","f10":""}

R = RedisClass()
yy = R.chick_MD5_uaid("861649", "e94fe0343a3e495b740419d83343bd2d",
                      "449a5dc904bef5315828a0d3ee7dd857")
print(yy)
Esempio n. 26
0
import logging
import os
from tornado import ioloop, gen
from tornado.tcpclient import TCPClient
from handlers.log.mylog import logInit_socket_client
from socket_client.models.socket_client_model import SocketClientModel
import config
import time
from handlers.myredis.redis_class import RedisClass
import socket
from tornado import ioloop, gen, iostream
import json
from models.public.headers_model import DistMD5

client_id = 999
R = RedisClass()
server_list = R.get_socket_sercerIP()
log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")
logInit_socket_client(log_path)
logger = logging.getLogger('Socket')
print("start_client......", client_id)

class SocketClientModel(object):
    # stream = {}
    clients = set()
    def __init__(self, client_id, label, host, port, io_loop):
        SocketClientModel.clients.add(self)
        self.label = label
        self.client_id = client_id
        self.host = host
        self.port = port
Esempio n. 27
0
client_id = 0
if __name__ == '__main__':
    client_label = "b"
    port = 9001
    print("TCPServer start ......")
    from models.public.headers_model import global_Models
    G = global_Models()
    G.set_map("ServerTime", 0)
    # ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    # ssl_ctx.load_cert_chain(os.path.join("/home/ssl/", "fullchain.pem"),
    #                         os.path.join("/home/ssl/", "privkey.pem"))
    # TCPServer(ssl_options=ssl_ctx)
    import socket
    from handlers.myredis.redis_class import RedisClass
    R = RedisClass()
    R.register_socketIP(get_host_ip(), port, client_label)
    # R.register_socketIP(socket.gethostbyname(socket.gethostname()), port, client_label)
    # R.register_socketIP("127.0.0.1", port, client_label)

    log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")
    logInit_socket(log_path)
    # server = CopyServer(ssl_options=ssl_ctx)
    server = CopyServer()
    server.listen(port)
    # server.bind(9000)# Forks multiple sub-processes
    # server.start(0)  # Forks multiple sub-processes
    ioloop.IOLoop.current().start()
    # 3.
    # `add_sockets`: advanced
    # multi - process::
Esempio n. 28
0
    def get(self):
        #self.render("user/login.html", next=self.get_argument("next"))
        get_class = self.get_argument('class')
        ukid = self.get_argument('ukid')
        AccountNumber = self.get_argument('f2')
        md5_from = self.get_argument('f5')
        Master_flag = self.get_argument('f6')
        OrderTicket = self.get_arguments('H0')
        OpenT = self.get_arguments('H1')
        OrderComment = self.get_arguments('H2')
        # print(type(OrderComment))
        # for ii in OrderComment:
        #     print(ii)
        account = self.get_arguments('H3')
        OrderProfit = self.get_arguments('H4')
        proxy_from_orderid = self.get_arguments('H5')
        # 验证
        R = RedisClass()
        uaid = yield R.chick_MD5_uaid(AccountNumber, md5_from, ukid)
        # print("uaid:", uaid)
        if uaid > 0:
            #验证通过
            O = ProxyOrderModel()
            url_text = "2,"
            upnew_flag = 0
            #把OrderTicket转成元组
            TicketTuple = yield O.FormatTuple(OrderTicket)
            accountTuple = yield O.FormatTuple(account)
            Order_datas = yield O.CheckOrderList(uaid, TicketTuple)
            order_Tuple_add = []
            order_Tuple_edit = []
            GradePrice = yield O.findProxyGradePrice(accountTuple)
            # print(GradePrice)
            for i in range(len(OrderTicket)):
                edit_flag = 0
                for Order_data in Order_datas:
                    if str(OrderTicket[i]) == str(Order_data['orderid']):
                        #存在订单
                        if OpenT[i] != str(Order_data['stime']):
                            edit_flag = 1
                        if account[i] != str(Order_data['account']):
                            edit_flag = 1
                        if OrderProfit[i] != str(Order_data['profit']):
                            edit_flag = 1
                        if proxy_from_orderid[i] != str(Order_data['proxy_from_orderid']):
                            edit_flag = 1

                        # print(OrderComment[i])
                        # print(Order_data['comment'])
                        if OrderComment[i] != str(Order_data['comment']):
                            edit_flag = 1
                        if Order_data['proxy_profit'] > 0 or str(Order_data['proxy_profit']) != "0.00":
                            edit_flag = 2
                        if edit_flag == 1:
                            # 修改订单,元组列表
                            tupleList2 = (int(OpenT[i]), int(proxy_from_orderid[i]), OrderComment[i], int(account[i]),
                                          float(OrderProfit[i]), float(OrderProfit[i]) / config.PROXY_PRICE * GradePrice[i], 1, uaid, int(OrderTicket[i]))
                            order_Tuple_edit.append(tupleList2)
                        else:
                            #无须修改的
                            url_text = url_text + OrderTicket[i] + ",1,"
                        edit_flag = 2
                        break

                if edit_flag == 0:
                    #增加订单,元组列表
                    tupleList = (int(OrderTicket[i]), int(proxy_from_orderid[i]), int(account[i]), int(OpenT[i]),
                                 float(OrderProfit[i]), float(OrderProfit[i]) / config.PROXY_PRICE * GradePrice[i], OrderComment[i], uaid, 1)
                    order_Tuple_add.append(tupleList)
            if len(order_Tuple_add) > 0:
                # 批量增加订单
                add_flag = yield O.AddOrderList(order_Tuple_add)
                if add_flag == True:
                    orderid_str = ""
                    add_edit_flag = 0
                    for order_1 in order_Tuple_add:
                        url_text = url_text + str(order_1[0]) + ",1,"
                        # print("==%s" % type(order_1[18]))
                else:
                    for order_2 in order_Tuple_add:
                        url_text = url_text + str(order_2[0]) + ",0,"
            if len(order_Tuple_edit) > 0:
                    # 修改订单
                    up_flag = yield O.UpOrderList(order_Tuple_edit)
                    if up_flag == True:
                        for order_3 in order_Tuple_edit:
                            url_text = url_text + str(order_3[8]) + ",1,"
                            upnew_flag = upnew_flag + 1
                    else:
                        for order_4 in order_Tuple_edit:
                            url_text = url_text + str(order_4[8]) + ",0,"

        else:
            if uaid == -1:
                # MD5不相符
                url_text = '-1,-1,0,0,0,0,0,0,0,'
            else:
                #不存在或是没有登陆
                url_text = '-1,-2,0,0,0,0,0,0,0,'
        # print(url_text)
        self.write(url_text + config.StringEnd)
        self.finish()
        # #整理数据
        # if users['ea'] =="true" or users['ea'] == 1:
        #     users['ea'] == 1
        # else:
        #     users['ea'] == 0
        # if users['moni'] == "true":
        #     users['moni'] == 1
        # else:
        #     users['moni'] == 0
        # #
        # md5_str = users['account'] + users['version']
        # str_md5 = hashlib.md5(md5_str.encode(encoding='UTF-8')).hexdigest()
        # # 验证
        # #datas = ""
        # y = UserModel()
        # if users['md5_from'] == str_md5:
        #     if get_class == "check":
        #         datas = yield y.GetAccount(users)#tornado.gen.Task
        #       # 执行Task函数,内部还是返回future对象。Task函数上第一个参数是要执行的函数,第二个是参数
        #
        #         self.write(datas)
        # else:
        #     self.write('-1,0,0,0,0,0,0,0,0,')
        # self.finish()
    #登录成功附加别的属性
    # def success_login(self, user):
    #     user.last_login = datetime.now()
    #     user.loginnum += 1
    #     self.db.add(user)
    #     self.db.commit()
    #     self.session.set('username', user.user_name)
Esempio n. 29
0
# coding = utf-8
import logging
import os
from tornado import ioloop, gen
from tornado.tcpclient import TCPClient
from handlers.log.mylog import logInit_socket_robot_client
from socket_client.models.socket_client_model import SocketClientModel
import config
import time
from handlers.myredis.redis_class import RedisClass

client_id = 1
R = RedisClass()
log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")
logInit_socket_robot_client(log_path)
logger = logging.getLogger('robot_client')


def main():

    R.ResetTotalConsole()
    print("start_client......", client_id)


def chick_redisConsole():
    # print("2")
    try:
        # print(config.server_list[client_id]['url'], config.server_list[client_id]['port'])
        # R = RedisClass()
        # TotalConsoleDist = R.pop_TotalConsole(client_id)
        TotalConsoleDist = R.pop_Console_list(client_id)
Esempio n. 30
0
    ip = get_host_ip()
    iplist = ip.split(".")
    client_label = iplist[3]
    print(str(ip))
    port = 9000
    print("TCPServer start ......")
    from models.public.headers_model import global_Models
    G = global_Models()
    G.set_map("ServerTime", 0)
    # ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    # ssl_ctx.load_cert_chain(os.path.join("/home/ssl/", "fullchain.pem"),
    #                         os.path.join("/home/ssl/", "privkey.pem"))
    # TCPServer(ssl_options=ssl_ctx)

    from handlers.myredis.redis_class import RedisClass
    R = RedisClass()
    R.register_socketIP(ip, port, client_label)
    # R.register_socketIP(socket.gethostbyname(socket.gethostname()), port, client_label)
    # R.register_socketIP("127.0.0.1", port, client_label)
    del R
    log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")
    logInit_socket(log_path)
    # server = CopyServer(ssl_options=ssl_ctx)
    server = CopyServer()
    server.listen(port)
    # server.bind(9000)# Forks multiple sub-processes
    # server.start(0)  # Forks multiple sub-processes
    ioloop.IOLoop.current().start()
    # 3.
    # `add_sockets`: advanced
    # multi - process::