python类Return()的实例源码

services.py 文件源码 项目:wxnotify 作者: mxgnene01 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_user_list():
    '''
    ????????? ???openid, ??
    '''
    access_token = yield find_access_token()
    if access_token is None:
        raise Return(False)

    client = AsyncHTTPClient()
    resp = yield client.fetch(tornado_options.get_user_list_url.format(access_token, ''))
    openids = json.loads(resp.body).get('data').get('openid')

    result = dict()
    for openid in openids:
        ret = yield get_user_detail(openid)
        tmp = dict(headimgurl = ret.get('headimgurl'), openid = ret.get('openid'), nickname = ret.get('nickname'))
        result[openid] = tmp

    raise Return(result)
services.py 文件源码 项目:wxnotify 作者: mxgnene01 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def check_signature(signature, timestamp, nonce, echostr):
    '''
    ??????
    '''

    # ?1???token?timestamp?nonce???????????
    mylist = sorted([tornado_options.token, timestamp, nonce])  # ?token, timestamp?nonce?????????????

    # ?2????????????????????sha1??
    mystr = ''.join(mylist)
    mystr_encoded = hashlib.sha1(mystr).hexdigest()  # ????????sha1??

    # ?3????????????????signature?????????????
    if mystr_encoded == signature:
        raise Return(echostr)
    else:
        raise Return(None)
services.py 文件源码 项目:wxnotify 作者: mxgnene01 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def unbind(db, openid):
    '''

    Parameters
    ----------
    openid??????openid

    Returns
    -------
    True ? False ??????????
    '''
    sql = "DELETE FROM dl_user_weixin WHERE openid = '%s'" % openid
    try:
        cursor = yield db.execute(sql)
    except Exception, e:
        BIZLOG.error('ERROR INFO IS : %s' % e.message)
        raise Return(False)

    if cursor.rowcount == 0:
        BIZLOG.error('UNBIND ERROR: [openid: %s]' % (openid, ))
        raise Return(False)
    else:
        BIZLOG.info('UNBIND SUCCESS: [openid: %s]' % (openid, ))
        raise Return(True)
mongo.py 文件源码 项目:fastweb 作者: BSlience 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def connect(self):
        """????"""

        try:
            self.recorder('INFO', '{obj} connect start'.format(obj=self))
            self.set_idle()
            self._client = motor_tornado.MotorClient(**self.setting)
            if self.db:
                self.select_db(self.db)
            self.isConnect = True
            self.recorder('INFO', '{obj} connect successful'.format(obj=self))
        except ConnectionFailure as e:
            self.recorder('ERROR', '{obj} connect failed [{msg}]'.format(obj=self, msg=e))
            self.error()
            raise MongoError
        raise Return(self)
mongo.py 文件源码 项目:fastweb 作者: BSlience 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def query(self, command, value=1, check=True, allowable_errors=None, **kwargs):
        """?????
           pymongo????????,??????
           TODO:????????????"""

        if not self._db:
            self.recorder('CRITICAL', 'please select db first!')

        shell_command = 'db.runCommand(\n{cmd}\n)'.format(cmd=dumps(command, indent=4, whole=4))
        self.recorder('INFO', '{obj} command start\n{cmd}'.format(obj=self, cmd=shell_command))
        try:
            with tool.timing('s', 10) as t:
                response = yield self._db.command(command=command, value=value, check=check,
                                                  allowable_errors=allowable_errors, **kwargs)
        except pymongo.errors.PyMongoError as e:
            self.recorder('ERROR', '{obj} command error [{msg}]'.format(obj=self, msg=e))
            raise MongoError
        self.recorder('INFO', '{obj} command successful\n{cmd} -- {time}'.format(obj=self, cmd=shell_command, time=t))

        self._response = self._parse_response(response)
        raise Return(self._response)
client.py 文件源码 项目:fastweb 作者: BSlience 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def communicate():
    # create client
    transport = TTornado.TTornadoStreamTransport('localhost', 9999)
    # open the transpo40.163rt, bail on error
    try:
        yield transport.open()
        print('Transport is opened')
    except TTransport.TTransportException as ex:
        logging.error(ex)
        raise gen.Return()

    protocol = TBinaryProtocol.TBinaryProtocolFactory()
    #pfactory = TMultiplexedProtocol.TMultiplexedProtocol(protocol, 'hello')
    client = HelloService.Client(transport, protocol)

    # ping
    yield client.sayHello()
    print("ping()")

    client._transport.close()
    raise gen.Return()
client.py 文件源码 项目:fastweb 作者: BSlience 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def communicate():
    # create client
    transport = TTornado.TTornadoStreamTransport('localhost', 7777)
    # open the transport, bail on error
    try:
        yield transport.open()
        print('Transport is opened')
    except TTransport.TTransportException as ex:
        logging.error(ex)
        raise gen.Return()

    protocol = TCompactProtocol.TCompactProtocolFactory()
    #pfactory = TMultiplexedProtocol.TMultiplexedProtocol(protocol, 'hello')
    client = HelloService.Client(transport, protocol)

    # ping
    yield client.sayHello()
    print("ping()")

    client._transport.close()
    raise gen.Return()
grants.py 文件源码 项目:auth-srv 作者: openpermissions 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def verify_access_service(self, client):
        """
        Verify the token's client / delegate has access to the service
        """
        try:
            service = yield Service.get(self.request.client_id)
        except couch.NotFound:
            raise Unauthorized("Unknown service '{}'"
                               .format(self.request.client_id))
        has_access = client.authorized(self.requested_access, service)

        if not has_access:
            raise Unauthorized("'{}' does not have '{}' to service '{}'"
                               .format(client.id, self.requested_access,
                                       self.request.client_id))

        raise Return(True)
grants.py 文件源码 项目:auth-srv 作者: openpermissions 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def generate_token(self):
        """Generate a delegate token"""
        self.validate_grant()
        self.validate_scope()

        # Assuming delegation always requires write access
        # should change it to a param
        client = yield Service.get(self.assertion['client']['id'])
        has_access = client.authorized('w', self.request.client)

        if not has_access:
            raise Unauthorized('Client "{}" may not delegate to service "{}"'.format(
                self.assertion['client']['id'],
                self.request.client_id
            ))

        token, expiry = generate_token(client,
                                       self.requested_scope,
                                       self.grant_type,
                                       delegate_id=self.request.client_id)

        raise Return((token, expiry))
scope.py 文件源码 项目:auth-srv 作者: openpermissions 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _check_access_resource_ids(self, func, resources):
        """
        Check resource identified by an ID exist and then call func for
        each resource
        """
        if not resources:
            raise Return()

        for resource_id in resources:
            try:
                doc = yield views.service_and_repository.first(key=resource_id)
            except couch.NotFound:
                raise InvalidScope('Scope contains an unknown resource ID')

            resource = RESOURCE_TYPES[doc['value']['type']](**doc['value'])
            try:
                yield resource.get_parent()
            except couch.NotFound:
                raise InvalidScope('Invalid resource - missing parent')
            func(resource, resources[resource_id])
utils.py 文件源码 项目:microProxy 作者: mike820324 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def create_iostream_pair(self):
        _lock = Event()
        server_streams = []

        def accept_callback(conn, addr):
            server_stream = MicroProxyIOStream(conn)
            server_streams.append(server_stream)
            # self.addCleanup(server_stream.close)
            _lock.set()

        listener, port = bind_unused_port()
        add_accept_handler(listener, accept_callback)
        client_stream = MicroProxyIOStream(socket.socket())
        yield [client_stream.connect(('127.0.0.1', port)),
               _lock.wait()]
        self.io_loop.remove_handler(listener)
        listener.close()

        raise Return((client_stream, server_streams[0]))
http1.py 文件源码 项目:microProxy 作者: mike820324 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def process_and_return_context(self):
        while not self.finished():
            self.req = None
            self.resp = None
            try:
                yield self.read_request()
                yield self.handle_http_proxy()
                self.send_request()
                yield self.read_response()
                self.send_response()
            except SrcStreamClosedError:
                if self.dest_stream:
                    self.dest_stream.close()
                self.context.done = True
                if self.req:
                    raise
            except DestStreamClosedError:
                self.src_stream.close()
                raise
            except SwitchToTunnelHttpProxy:
                break

        if self.switch_protocol:
            self.context.scheme = self.req.headers["Upgrade"]
        raise gen.Return(self.context)
http1.py 文件源码 项目:microProxy 作者: mike820324 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def handle_http_proxy(self):
        if self.is_tunnel_http_proxy():
            logger.debug("{0} proxy tunnel to {1}".format(self, self.req.path))
            scheme, host, port = parse_tunnel_proxy_path(self.req.path)
            yield self.connect_to_dest(scheme, (host, port))
            self.src_conn.send_response(HttpResponse(
                code="200",
                reason="OK", version="HTTP/1.1"))
            raise SwitchToTunnelHttpProxy
        elif self.is_normal_http_proxy():
            logger.debug("{0} proxy to {1}".format(self, self.req.path))
            scheme, host, port, path = parse_proxy_path(self.req.path)
            self.req.path = path
            yield self.connect_to_dest(scheme, (host, port))
            self.dest_conn.io_stream = self.dest_stream
        else:
            raise gen.Return(None)
socks.py 文件源码 项目:microProxy 作者: mike820324 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def process_and_return_context(self):
        self.socks_conn.initiate_connection()
        while True:
            try:
                data = yield self.context.src_stream.read_bytes(1024, partial=True)
            except iostream.StreamClosedError:
                raise SrcStreamClosedError(
                    detail="client closed while socks handshaking")

            _event = self.socks_conn.recv(data)
            if _event == "GreetingRequest":
                yield self.handle_greeting_request(_event)
            elif _event == "Request":
                dest_stream, host, port = yield self.handle_request_and_create_destination(_event)
                self.context.dest_stream = dest_stream
                self.context.host = host
                self.context.port = port
                break
            else:
                raise NotImplementedError("not handling with {0}".format(_event))

        raise gen.Return(self.context)
socks.py 文件源码 项目:microProxy 作者: mike820324 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def handle_request_and_create_destination(self, event):
        """Handle the socks request from source
        Create destination connection

        Returns:
            tuple: (dest_stream, host, port)
        """
        if event.cmd != REQ_COMMAND["CONNECT"]:
            logger.debug("Unsupport connect type")
            yield self.send_event_to_src_conn(Response(
                RESP_STATUS["COMMAND_NOT_SUPPORTED"],
                event.atyp, event.addr, event.port), raise_exception=False)
            raise ProtocolError("Unsupport bind type")

        try:
            dest_stream = yield self.create_dest_stream((str(event.addr), event.port))
        except gen.TimeoutError as e:
            yield self.handle_timeout_error(e, event)
        except iostream.StreamClosedError as e:
            yield self.handle_stream_closed_error(e, event)
        else:
            yield self.send_event_to_src_conn(Response(
                RESP_STATUS["SUCCESS"],
                event.atyp, event.addr, event.port))
            raise gen.Return((dest_stream, event.addr, event.port))
db_op.py 文件源码 项目:2016-NCTU_find_roommate-API-server 作者: Microsheep 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get(self, query, params, dry_output=False):
        """
        Use this method to fetch data from db.
            param query: (str) actual query to be executed
            param dry_output: (bool) switch output style
            return: If dry_output True - output tuple of tuples, otherwise list of dicts
        """
        #print(datetime.now())
        #print("DB_GET: "+query)
        #print("INPUT: "+str(params))
        with (yield self.pool.Connection()) as conn:
            with conn.cursor() as cursor:
                yield cursor.execute(query, params)
                yield conn.commit()
                data = rows = cursor.fetchall()
                cols = [x[0] for x in cursor.description]
        if not dry_output:
            data = []
            for row in rows:
                record = {}
                for prop, val in zip(cols, row):
                    record[prop] = val
                data.append(record)
        raise gen.Return(data)
green.py 文件源码 项目:gTornado 作者: alex8224 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def readline(self, max_bytes=-1):
        timer = None
        if self._readtimeout:
            timer = Timeout(self._readtimeout)
            timer.start()
        try:
            if max_bytes > 0:
                buff = yield self._iostream.read_until('\n', max_bytes=max_bytes)
            else:
                buff = yield self._iostream.read_until('\n')
            raise Return(buff)
        except TimeoutException:
            self.close()
            raise
        finally:
            if timer:
                timer.cancel()
init_db.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def init_community_nodes():
    node_list = [
        u'???', u'??', u'??', u'????', u'???', u'??',
        u'??', u'??', u'??', u'??', u'??', u'????', u'??']

    for i, node in enumerate(node_list):
        document = {
            'name': node,
            'sort': i,
            'category': NodeDocument.BUILTIN
        }

        existed = yield NodeDocument.find_one({"name": node})
        if not existed:
            yield NodeDocument.insert(document)

    raise gen.Return()
init_db.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_share_category():
    collection = Connection.get_database(pymongo=True).share_category

    category_list = [
        u'??', u'??', u'??', u'??', u'??', u'??', u'??', u'??']

    for i, category in enumerate(category_list):
        document = {
            'name': category,
            'sort': i
        }

        existed = collection.find_one({"name": category})
        if not existed:
            collection.insert(document)

    raise gen.Return()
document.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_chat_message_list(user_id, skip=0, limit=None):
        '''????????????'''

        user_dbref = DBRef(UserDocument.meta['collection'], ObjectId(user_id))
        query = {
            '$or': [{'sender': user_dbref}, {'recipient': user_dbref}]
        }

        cursor = ChatMessageDocument.find(query).sort(
            [('send_time', pymongo.DESCENDING)]
        ).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        chat_message_list = yield ChatMessageDocument.to_list(cursor)
        chat_message_list = yield ChatMessageDocument.translate_dbref_in_document_list(
            chat_message_list)

        raise gen.Return(chat_message_list)


问题


面经


文章

微信
公众号

扫码关注公众号