Example #1
0
async def wx(**data):
    """ 微信验证 """
    logger.warning("datawx=%s " % data)
    try:
        if len(data) == 0:
            return "hello, this is handle view"
        signature = data['signature']
        timestamp = data['timestamp']
        nonce = data['nonce']
        echostr = data['echostr']
        token = CONF['wechat']['token']

        # 计算签名
        list_temp = [token, timestamp, nonce]
        list_temp.sort()
        list_temp = ''.join(list_temp)
        sha1 = hashlib.sha1()
        sha1.update(list_temp.encode('utf-8'))
        hashcode = sha1.hexdigest()
        logger.info(
            f"wechat signature: hashcode:{hashcode}, signature:{signature} "
        )
        if hashcode == signature:
            return echostr
        else:
            return ""
    except Exception as Argument:
        return Argument
Example #2
0
async def init(loop):
    await orm.create_pool(
        loop=loop,
        host=CONF['db']['host'],
        port=CONF['db']['port'],
        user=CONF['db']['user'],
        password=CONF['db']['password'],
        db=CONF['db']['dbName']
    )

    app = web.Application(loop=loop, middlewares=[
        logger_factory, auth_factory, response_factory
    ])

    init_jinja2(app, filters=dict(datetime=datetime_filter))
    add_routes(app, 'handlers')
    add_static(app)
    try:
        srv = await loop.create_server(
            app.make_handler(),
            CONF['host'],
            CONF['port'])
    except Exception as e:
        logger.error(e)

    logger.info(f"server started at http://{CONF['host']}:{CONF['port']}")
    return srv
Example #3
0
 def __init__(self, xml_data):
     # 数据解析
     self.data = self._parse_xml(xml_data)
     logger.info('[wechat] receive msg_data :%s' % str(self.data))
     # 消息类型
     self.type = self.data.find('MsgType').text
     # 转换为消息对象
     self.msg_obj = self._to_msg()
Example #4
0
async def wechat_message_handle(data):
    """ 消息处理 """
    logger.info("[wechat] route, message info: {} ".format(data))
    try:
        msg_handle = MsgHandle(data)
        reply = msg_handle.run()
        return reply if reply else 'success'
    except Exception as e:
        logger.debug('[wechat] route: error. %s ' % str(e))
        return 'success'
Example #5
0
 def reply(msg_data):
     xml_form = """
         <xml>
         <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
         <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
         <CreateTime>{CreateTime}</CreateTime>
         <MsgType><![CDATA[text]]></MsgType>
         <Content><![CDATA[{Content}]]></Content>
         </xml>
     """
     logger.info('[wechat] reply msg_data: %s' % str(xml_form))
     return xml_form.format(**msg_data)
Example #6
0
def add_route(app, fn):
    """ 将处理函数注册到web服务程序路由中 """
    method = getattr(fn, '__method__', None)
    path = getattr(fn, '__route__', None)
    if path is None or method is None:
        raise ValueError('@get or @post not defined in {0}'.format(fn))
    if (not asyncio.iscoroutinefunction(fn)
            and not inspect.isgeneratorfunction(fn)):
        fn = asyncio.coroutine(fn)
    logger.info("add route {0} {1} =>? {2}({3})".format(
        method, path, fn.__name__,
        ', '.join(inspect.signature(fn).parameters.keys())))
    app.router.add_route(method, path, RequestHandler(app, fn))
Example #7
0
def log(s):
    logger.info('[Monitor] %s' % s)
Example #8
0
def add_static(app):
    """ 添加静态资源路径 """
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
    app.router.add_static('/static/', path)
    logger.info("add static {0} => {1}".format('/static/', path))
Example #9
0
    async def __call__(self, request):
        """ 分析请求, 整理参数 """
        kw = None
        if (self._has_var_kw_arg or self._has_named_kw_args
                or self._required_kw_args):
            # pdb.set_trace()
            if request.method == 'POST':
                # POST请求预处理,处理各种内容类型
                if not request.content_type:
                    return web.HTTPBadRequest(reason='Missing Content-type')
                ct = request.content_type.lower()
                if ct.startswith('application/json'):
                    params = await request.json()
                    if not isinstance(params, dict):
                        return web.HTTPBadRequest(
                            reason='Json body must be object')
                    kw = params

                elif (ct.startswith('application/x-www-form-urlencoded')
                      or ct.startswith('multipart/form-data')):
                    params = await request.post()
                    kw = dict(**params)

                else:
                    return web.HTTPBadRequest(
                        reason='Unsupported Content-Type: {0}'
                        ''.format(request.content_type),
                        content_type=request.content_type)

            if request.method == 'GET':
                qs = request.query_string
                if qs:
                    kw = {}
                    for k, v in parse.parse_qs(qs, True).items():
                        kw[k] = v[0]

        if kw is None:
            kw = dict(**request.match_info)
        else:
            if (not self._has_var_kw_arg) and self._named_kw_args:
                # 获取命名关键字
                copy = {}
                for name in self._named_kw_args:
                    if name in kw:
                        copy[name] = kw[name]
                kw = copy
            for k, v in request.match_info.items():
                if k in kw:
                    logger.warning('Duplicate arg name in named '
                                   'arg and kw args{0}'.format(k))
                kw[k] = v
        if self._has_request_arg:
            kw['request'] = request
        if self._required_kw_args:
            # 无默认值的关键字参数
            for name in self._required_kw_args:
                if not (name in kw):
                    return web.HTTPBadRequest(
                        reason='Missing argument:{0}'.format(name))
        if not kw:
            # stream request
            stream_data = await request.read()
            if stream_data:
                logger.info("stream request: {}".format(
                    stream_data.decode('utf-8')))
                kw['data'] = stream_data.decode('utf-8')

        logger.info('call with args:{0}'.format(str(kw)))
        try:
            r = await self._func(**kw)
            return r
        except APIError as e:
            return dict(error=e.error, data=e.data, message=e.message)