当前位置: 首页>>代码示例>>Python>>正文


Python utils.safeunicode函数代码示例

本文整理汇总了Python中toughlib.utils.safeunicode函数的典型用法代码示例。如果您正苦于以下问题:Python safeunicode函数的具体用法?Python safeunicode怎么用?Python safeunicode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了safeunicode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: event_smtp_account_open

    def event_smtp_account_open(self, userinfo):

        open_notify = u"""尊敬的 %customer% 您好:
        欢迎使用产品 %product%, 您的账号已经开通,账号名是 %username%, 服务截止 %expire%。"""

        ctx = open_notify.replace('%customer%', userinfo.get('realname'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        ctx = ctx.replace('%username%', userinfo.get('account_number'))
        ctx = ctx.replace('%expire%', userinfo.get('expire_date'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        topic = ctx[:ctx.find('\n')]
        smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
        from_addr = self.get_param_value("smtp_from")
        smtp_port = int(self.get_param_value("smtp_port", 25))
        smtp_sender = self.get_param_value("smtp_sender", None)
        smtp_user = self.get_param_value("smtp_user", None)
        smtp_pwd = self.get_param_value("smtp_pwd", None)
        return sendmail(
                server=smtp_server,
                port=smtp_port,
                user=smtp_user,
                password=smtp_pwd,
                from_addr=from_addr, mailto=userinfo.email,
                topic=utils.safeunicode(topic),
                content=utils.safeunicode(ctx),
                tls=False)
开发者ID:YMXZ,项目名称:ToughRADIUS,代码行数:26,代码来源:account_open_notify.py

示例2: parse_form_request

 def parse_form_request(self):
     try:
         print self.get_params()
         return apiutils.parse_form_request(self.settings.config.system.secret, self.get_params())
     except Exception as err:
         logger.error(u"api authorize parse error, %s" % utils.safeunicode(traceback.format_exc()))
         raise ValueError(u"Error: %s" % utils.safeunicode(err.message))
开发者ID:WyattShao,项目名称:ToughRADIUS,代码行数:7,代码来源:apibase.py

示例3: get

    def get(self, *args, **kwargs):
        logger.info(utils.safeunicode(self.request.query))
        wlan_params = {
            "wlanuserip": self.get_argument("userip", self.request.remote_ip),
            "ispcode": self.get_argument("ispcode", "default"),
            "wlanusername": self.get_argument("username","test"),
            "wlanacip": self.settings.config.acagent.nasaddr,
            "ssid": self.get_argument("ssid","default"),
            "wlanusermac": self.get_argument("wlanusermac","00-00-00-00-00"),
            "wlanapmac": self.get_argument("wlanapmac","00-00-00-00-00"),
            "wlanuserfirsturl": self.get_argument("wlanuserfirsturl","/portal/index"),
            "callback": self.get_argument("callback",""),
            "vendortype" : self.get_argument("vendortype",""),
        }
        logger.info(utils.safeunicode(wlan_params))
        if wlan_params['vendortype'] == 'routeros':
            logger.info("Forward to RouterOS Portal Login")
            self.forward_ros(wlan_params)
            return

        elif wlan_params['vendortype'] == 'ikuai':
            logger.info("Forward to RouterOS ikuai Login")
            self.forward_ikuai(wlan_params)
            return

        logger.info("callback_cache_%s" % utils.safeunicode(wlan_params['wlanuserip']))
        self.application.mcache.set(
            "callback_cache_%s" % utils.safestr(wlan_params['wlanuserip']),wlan_params['callback'],300)

        url = self.settings.config.acagent.portal_login.format(**wlan_params)
        logger.info("portal forward to : %s" % url)
        self.redirect(url, permanent=False)
开发者ID:sdgdsffdsfff,项目名称:toughwlan,代码行数:32,代码来源:forward.py

示例4: c_make_sign

def c_make_sign(params={}):
    """
        >>> c_make_sign({"k1":"v1", "k2":"v2"})
        '33C9065427EECA3490C5642C99165145'
    """
    _params = [utils.safeunicode(k) for k in params if k is not None]
    _params.sort()
    _params2 = [utils.safeunicode(k)+'='+params[k]+'&' for k in _params if k is not None]
    strs = ''.join(_params2).strip('&')
    mds = md5(strs.encode('utf-8')).hexdigest()
    return mds.lower()
开发者ID:fozzmarc,项目名称:toughlib,代码行数:11,代码来源:apiutils.py

示例5: get

    def get(self):
        token = self.get_argument("token",None)
        if not token or  token not in md5(self.settings.config.system.secret.encode('utf-8')).hexdigest():
            return self.render_json(code=1,msg=u"token invalid")

        mailto = self.get_argument('mailto')
        topic = self.get_argument('topic')
        ctx = self.get_argument('content')
        logger.info("sendmail: %s %s %s"% (mailto, utils.safeunicode(topic), utils.safeunicode(ctx)))
        self.send_mail(mailto, topic, ctx).addCallbacks(logger.info,logger.error)
        self.mongodb.add_mail_alert(mailto,ctx)
        self.render_json(code=0,msg="mail send done")
开发者ID:lxyjyy,项目名称:ToughNMS,代码行数:12,代码来源:sendmail.py

示例6: process

    def process(self, msgid, message):
        self.syslog.info("accept auth message @ %s : %r" % (self.listen, utils.safeunicode(message)))
        @self.cache.cache(expire=600)   
        def get_account_by_username(username):
            return self.db.query(models.TrAccount).filter_by(account_number=username).first()

        @self.cache.cache(expire=600)   
        def get_product_by_id(product_id):
            return self.db.query(models.TrProduct).filter_by(id=product_id).first()

        try:
            req_msg = apiutils.parse_request(self.secret, message)
            if req_msg.get("action") == 'ping':
                return self.agent.reply(msgid, apiutils.make_message(self.secret,code=0))
            if 'username' not in req_msg:
                raise ValueError('username is empty')
        except Exception as err:
            resp = apiutils.make_message(self.secret, code=1, msg=utils.safestr(err.message))
            self.agent.reply(msgid, resp)
            return
            
        try:
            username = req_msg['username']
            account = get_account_by_username(username)
            if not account:
                apiutils.make_message(self.secret, code=1, msg=u'user  {0} not exists'.format(utils.safeunicode(username)))
                self.agent.reply(msgid, resp)
                return
                
            passwd = self.app.aes.decrypt(account.password)
            product = get_product_by_id(account.product_id)

            result = dict(
                code=0,
                msg='success',
                username=username,
                passwd=passwd,
                input_rate=product.input_max_limit,
                output_rate=product.output_max_limit,
                attrs={
                    "Session-Timeout"      : 86400,
                    "Acct-Interim-Interval": 300
                }
            )

            resp = apiutils.make_message(self.secret, **result)
            self.agent.reply(msgid, resp)
            self.syslog.info("send auth response %r" % (utils.safeunicode(resp)))
        except Exception as err:
            self.syslog.error(u"api authorize error %s" % utils.safeunicode(err.message))
            resp = apiutils.make_message(self.secret, code=1, msg=utils.safestr(err.message))
            return self.agent.reply(msgid, resp)
开发者ID:davislidaqing,项目名称:ToughRADIUS,代码行数:52,代码来源:authorize.py

示例7: render_json

 def render_json(self, **template_vars):
     if not template_vars.has_key("code"):
         template_vars["code"] = 0
     resp = json.dumps(template_vars, ensure_ascii=False)
     if self.settings.debug:
         logger.debug("[api debug] :: %s response body: %s" % (self.request.path, utils.safeunicode(resp)))
     self.write(resp)
开发者ID:lxyjyy,项目名称:ToughRADIUS,代码行数:7,代码来源:base.py

示例8: post

    def post(self):
        try:
            req_msg = self.parse_form_request()
            if  not any([req_msg.get('ip_addr'),req_msg.get("dns_name")]):
                raise ValueError("ip_addr, dns_name required one")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        bas = self.db.query(models.TrwBas)
        if req_msg.get('ip_addr'):
            bas = bas.filter_by(ip_addr=req_msg['ip_addr']).first()
        elif req_msg.get('dns_name'):
            bas = bas.filter_by(dns_name=req_msg['dns_name']).first()

        if not bas:
            self.render_result(code=1, msg="nas not exists")
            return

        attrs = ['bas_name','time_type','vendor_id','portal_vendor','bas_secret','coa_port','ac_port']

        for attr in attrs:
            if attr in req_msg:
                setattr(bas, attr, req_msg[attr])

        self.db.commit()

        self.render_result(code=0, msg="success")
开发者ID:gvsurenderreddy,项目名称:toughwlan,代码行数:28,代码来源:api_nas.py

示例9: process

    def process(self):
        conn = self.db()
        try:
            nas_list = conn.query(models.TrwBas)
            for nas in nas_list:
                if not nas.dns_name:
                    continue
                results, _, _ = yield client.lookupAddress(nas.dns_name)
                if not results:
                    logger.error("domain {0} resolver empty".format(nas.dns_name))

                if results[0].type == dns.A:
                    ipaddr = ".".join(str(i) for i in struct.unpack("BBBB", results[0].payload.address))
                    if ipaddr:
                        nas.ip_addr = ipaddr
                        conn.commit()
                        logger.info("domain {0} resolver {1}  success".format(nas.dns_name,ipaddr))
                else:
                    logger.info("domain {0} no ip address,{1}".format(nas.dns_name, repr(results)))

        except Exception as err:
            logger.error('ddns process error %s' % utils.safeunicode(err.message))
        finally:
            conn.close()

        reactor.callLater(60, self.process, )
开发者ID:gvsurenderreddy,项目名称:toughwlan,代码行数:26,代码来源:ddns_task.py

示例10: processAcct

    def processAcct(self, datagram, host, port):
        try:
            bas = self.find_nas(host)
            if not bas:
                raise PacketError('[Radiusd] :: Dropping packet from unknown host %s' % host)

            secret, vendor_id = bas['bas_secret'], bas['vendor_id']
            req = self.createAcctPacket(packet=datagram, 
                dict=self.dict, secret=six.b(str(secret)),vendor_id=vendor_id)

            logger.info("[Radiusd] :: Received radius request: %s" % (repr(req)))
            if self.config.system.debug:
                logger.debug(req.format_str())

            if req.code != packet.AccountingRequest:
                raise PacketError('non-AccountingRequest packet on authentication socket')

            if not req.VerifyAcctRequest():
                raise PacketError('VerifyAcctRequest error')

            reply = req.CreateReply()
            status_type = req.get_acct_status_type()
            if status_type in self.acct_class:
                acct_func = self.acct_class[status_type](self,req.get_ticket()).acctounting
                reactor.callLater(0.1,acct_func)
            return reply
        except Exception as err:
            errstr = 'RadiusError:Dropping invalid acct packet from {0} {1},{2}'.format(
                host, port, utils.safeunicode(err))
            logger.error(errstr)
            import traceback
            traceback.print_exc()
开发者ID:niebaopeng,项目名称:ToughRADIUS,代码行数:32,代码来源:radiusd.py

示例11: error

def error(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_ERROR in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_ERROR,message,**kwargs)
    else:
        default_log.error(message)
开发者ID:xvxieweilai,项目名称:toughlib,代码行数:7,代码来源:logger.py

示例12: debug

def debug(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_DEBUG in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_DEBUG,message,**kwargs)
    else:
        default_log.debug(message)
开发者ID:xvxieweilai,项目名称:toughlib,代码行数:7,代码来源:logger.py

示例13: info

def info(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_INFO in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_INFO,message,**kwargs)
    else:
        default_log.info(message)
开发者ID:xvxieweilai,项目名称:toughlib,代码行数:7,代码来源:logger.py

示例14: log_trace

 def log_trace(self,host,port,req,reply=None):
     if not self.is_trace_on():
         return
     if not self.user_exists(req.get_user_name()):
         return
     try:
         if reply is None:
             msg = message.format_packet_log(req)
             logger.info(u"Radius请求来自 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
         else:
             msg = message.format_packet_log(reply)
             logger.info(u"Radius响应至 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
     except Exception as err:
         logger.exception(err)
开发者ID:dhh123,项目名称:ToughRADIUS,代码行数:16,代码来源:radiusd.py

示例15: post

    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'isp_code' not in req_msg:
                raise ValueError("isp_code required")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        isp = self.db.query(models.TrwIsp).filter_by(isp_code=req_msg['isp_code']).first()
        if not isp:
            self.render_result(code=1, msg="isp not exists")
            return


        attrs = ['isp_name','isp_desc','isp_email','isp_phone','isp_idcard']

        for attr in attrs:
            if attr in req_msg:
                setattr(isp, attr, req_msg[attr])

        if 'status' in req_msg and req_msg['status'] in ('0','1'):
            isp.status = int(req_msg['status'])

        isp.isp_name = req_msg.get("isp_name","")
        isp.isp_desc = req_msg.get("isp_desc","")
        isp.isp_email = req_msg.get("isp_email","")
        isp.isp_phone = req_msg.get("isp_phone","")
        isp.isp_idcard = req_msg.get("isp_idcard","")
        self.db.commit()

        self.render_result(code=0, msg="success")
开发者ID:gvsurenderreddy,项目名称:toughwlan,代码行数:32,代码来源:api_isp.py


注:本文中的toughlib.utils.safeunicode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。