• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.InsensitiveDict类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

    def __init__(self, url, method='GET', postdata=None, headers=None,
                 agent="Twisted PageGetter", timeout=0, cookies=None,
                 followRedirect=1, proxy=None):
        self.protocol.followRedirect = followRedirect
        self.timeout = timeout
        self.agent = agent
        self.proxy = proxy

        if cookies is None:
            cookies = {}
        self.cookies = cookies
        if headers is not None:
            self.headers = InsensitiveDict(headers)
        else:
            self.headers = InsensitiveDict()
        if postdata is not None:
            self.headers.setdefault('Content-Length', len(postdata))
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("connection", "close")
        self.postdata = postdata
        self.method = method

        self.setURL(url)

        self.waiting = 1
        self.deferred = defer.Deferred()
        self.response_headers = None
开发者ID:GNOME,项目名称:postr,代码行数:27,代码来源:proxyclient.py


示例2: __init__

    def __init__(self, url, method='GET', postdata=None, headers=None,
                 agent="Twisted PageGetter", timeout=0, cookies=None,
                 followRedirect=True, redirectLimit=20,
                 afterFoundGet=False):
        self.followRedirect = followRedirect
        self.redirectLimit = redirectLimit
        self._redirectCount = 0
        self.timeout = timeout
        self.agent = agent
        self.afterFoundGet = afterFoundGet
        if cookies is None:
            cookies = {}
        self.cookies = cookies
        if headers is not None:
            self.headers = InsensitiveDict(headers)
        else:
            self.headers = InsensitiveDict()
        if postdata is not None:
            self.headers.setdefault('Content-Length', len(postdata))
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("connection", "close")
        self.postdata = postdata
        self.method = method

        self.setURL(url)

        self.waiting = 1
        self._disconnectedDeferred = defer.Deferred()
        self.deferred = defer.Deferred()
        # Make sure the first callback on the result Deferred pauses the
        # callback chain until the request connection is closed.
        self.deferred.addBoth(self._waitForDisconnect)
        self.response_headers = None
开发者ID:GunioRobot,项目名称:twisted,代码行数:33,代码来源:client.py


示例3: __init__

 def __init__(self, initial=None, case_mapping=None):
     if case_mapping is None:
         case_mapping = CaseMapping.by_name("rfc1459")
     elif isinstance(case_mapping, basestring):
         case_mapping = CaseMapping.by_name(case_mapping)
     self.case_mapping = case_mapping
     InsensitiveDict.__init__(self, initial, preserve=1)
开发者ID:kxz,项目名称:omnipresence,代码行数:7,代码来源:case_mapping.py


示例4: RestClientFactory

class RestClientFactory(protocol.ClientFactory):

    protocol = client.HTTPPageGetter
    noisy = False
    
    def __init__(self, host, port, path, data, timeout = 60):
        self.log = log.getChild('ClientFactory')
        self.timeout = timeout
        self.agent = "RestClient"
        self.headers = InsensitiveDict()
        self.headers.setdefault('Content-Length', len(data))
        self.headers.setdefault("connection", "close")
        self.method = 'POST'
        self.url = 'http://' + host + ':' + str(port) + path
        self.scheme = 'http'
        self.postdata = data
        self.host = host
        self.port = port
        self.path = path
        self.waiting = 1
        self.deferred = defer.Deferred()
        self.response_headers = None
        self.cookies = {}

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.url)

    def buildProtocol(self, addr):
        p = protocol.ClientFactory.buildProtocol(self, addr)
        if self.timeout:
            timeoutCall = reactor.callLater(self.timeout, p.timeout)
            self.deferred.addBoth(self._cancelTimeout, timeoutCall)
        return p

    def _cancelTimeout(self, result, timeoutCall):
        if timeoutCall.active():
            timeoutCall.cancel()
        return result

    def gotHeaders(self, headers):
        self.response_headers = headers
        
    def gotStatus(self, version, status):
        self.version, self.status = version, status

    def page(self, page):
        if self.waiting:
            self.waiting = 0
            self.deferred.callback(page)

    def noPage(self, reason):
        if self.waiting:
            self.waiting = 0
            self.deferred.errback(reason)

    def clientConnectionFailed(self, _, reason):
        if self.waiting:
            self.waiting = 0
            self.deferred.errback(reason)
开发者ID:Usr-X,项目名称:poker-network,代码行数:59,代码来源:pokerrestclient.py


示例5: HeaderAwareHTTPClientFactory

class HeaderAwareHTTPClientFactory(client.HTTPClientFactory):

    protocol = yourHTTPPageGetter
    noisy = False

    def __init__(self, url, method='GET', postdata=None, headers=None,
                 agent="Coherence PageGetter", timeout=0, cookies=None,
                 followRedirect=True, redirectLimit=20):
        self.followRedirect = followRedirect
        self.redirectLimit = redirectLimit
        self._redirectCount = 0
        self.timeout = timeout
        self.agent = agent

        if cookies is None:
            cookies = {}
        self.cookies = cookies
        if headers is not None:
            self.headers = InsensitiveDict(headers)
        else:
            self.headers = InsensitiveDict()
        if postdata is not None:
            self.headers.setdefault('Content-Length', len(postdata))
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("connection", "close")
        self.postdata = postdata
        self.method = method

        self.setURL(url)

        self.waiting = 1
        self.deferred = defer.Deferred()
        self._disconnectedDeferred = defer.Deferred()
        self.response_headers = None

    def buildProtocol(self, addr):
        p = protocol.ClientFactory.buildProtocol(self, addr)
        p.method = self.method
        p.followRedirect = self.followRedirect
        if self.timeout:
            timeoutCall = reactor.callLater(self.timeout, p.timeout)
            self.deferred.addBoth(self._cancelTimeout, timeoutCall)
            self._disconnectedDeferred = defer.Deferred()
        return p

    def page(self, page):
        if self.waiting:
            self.waiting = 0
            self.deferred.callback((page, self.response_headers))
开发者ID:pszafer,项目名称:dlna_upnp_invention,代码行数:49,代码来源:utils.py


示例6: __init__

    def __init__(self, factory, parent):
        self.factory     = factory
        self.nickname    = parent.nickname.encode('ascii')
        self.realname    = parent.realname.encode('ascii')
        self.username    = parent.ident.encode('ascii')
        self.ns_username = parent.username
        self.ns_password = parent.password
        self.password    = parent.server_password.encode('ascii')
        self.join_channels = parent.channel_map.keys()

        self.users        = InsensitiveDict()
        self.channels     = InsensitiveDict()
        self.cap_requests = set()

        self.parent = parent
开发者ID:edk0,项目名称:IAmARelayBotAMA,代码行数:15,代码来源:ircbot.py


示例7: __init__

 def __init__(self, factory, plugin):
     self.factory     = factory
     self.nickname    = plugin.nickname.encode('ascii')
     self.realname    = plugin.realname.encode('ascii')
     self.username    = plugin.username.encode('ascii')
     self.ns_password = plugin.password
     self.password    = plugin.server_password.encode('ascii')
     self.channel     = plugin.channel.encode('ascii')
     self.console     = plugin.console
     self.irc_message = plugin.irc_message
     self.users       = InsensitiveDict()
开发者ID:runfalk,项目名称:mark2,代码行数:11,代码来源:irc.py


示例8: __init__

    def __init__(
        self,
        url,
        method="GET",
        postdata=None,
        headers=None,
        agent="Twisted PageGetter",
        timeout=0,
        cookies=None,
        followRedirect=True,
        redirectLimit=20,
        afterFoundGet=False,
    ):
        self.followRedirect = followRedirect
        self.redirectLimit = redirectLimit
        self._redirectCount = 0
        self.timeout = timeout
        self.agent = agent
        self.afterFoundGet = afterFoundGet
        if cookies is None:
            cookies = {}
        self.cookies = cookies
        if headers is not None:
            self.headers = InsensitiveDict(headers)
        else:
            self.headers = InsensitiveDict()
        if postdata is not None:
            self.headers.setdefault("Content-Length", len(postdata))
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("connection", "close")
        self.postdata = postdata
        self.method = method

        self.setURL(url)

        self.waiting = 1
        self.deferred = defer.Deferred()
        self.response_headers = None
开发者ID:rolando-contribute,项目名称:cyclone,代码行数:38,代码来源:client.py


示例9: test01_proxy

 def test01_proxy(self):
       data = '{"type": "PacketPing"}'
       headers = InsensitiveDict()
       headers.setdefault('Content-Length', len(data))
       headers.setdefault("connection", "close")
       headers.setdefault("proxy-connection", "foo")
       host = '127.0.0.1'
       port = 19481
       path = '/POKER_REST'
       factory = pokerrestclient.PokerProxyClientFactory('POST', path, '1.1', headers, data, MockRequest(), 6, host + ':' + str(port) + path)
       reactor.connectTCP(host, port, factory)
       factory.deferred.addCallback(self.assertNotEquals, None)
       return factory.deferred
开发者ID:9cat,项目名称:Bitcoin-Poker-Room,代码行数:13,代码来源:test-pokerrestclient.py


示例10: __init__

 def __init__(self, host, port, path, data, timeout = 60):
     self.timeout = timeout
     self.agent = "RestClient"
     self.headers = InsensitiveDict()
     self.headers.setdefault('Content-Length', len(data))
     self.headers.setdefault("connection", "close")
     self.method = 'POST'
     self.url = 'http://' + host + ':' + str(port) + path
     self.postdata = data
     self.host = host
     self.port = port
     self.path = path
     self.waiting = 1
     self.deferred = defer.Deferred()
     self.response_headers = None
     self.cookies = {}
开发者ID:jefffederman,项目名称:pokersource,代码行数:16,代码来源:pokerrestclient.py


示例11: __init__

    def __init__(self, factory, plugin):
        self.factory     = factory
        self.nickname    = plugin.nickname.encode('ascii')
        self.realname    = plugin.realname.encode('ascii')
        self.username    = plugin.ident.encode('ascii')
        self.ns_username = plugin.username
        self.ns_password = plugin.password
        self.password    = plugin.server_password.encode('ascii')
        self.channel     = plugin.channel.encode('ascii')
        self.console     = plugin.console
        self.irc_message = plugin.irc_message
        self.irc_action  = plugin.irc_action
        self.irc_chat_status = plugin.irc_chat_status
        self.mangle_username = plugin.mangle_username

        self.users       = InsensitiveDict()
        self.cap_requests = set()
开发者ID:DMBuce,项目名称:mark2,代码行数:17,代码来源:irc.py


示例12: __init__

 def __init__(self, host, port, path, data, timeout=60):
     self.timeout = timeout
     self.agent = "RestClient"
     self.headers = InsensitiveDict()
     self.headers.setdefault("Content-Length", len(data))
     self.headers.setdefault("connection", "close")
     self.method = "POST"
     self.url = "http://" + host + ":" + str(port) + path
     self.scheme = "http"
     self.postdata = data
     self.host = host
     self.port = port
     self.path = path
     self.waiting = 1
     self.deferred = defer.Deferred()
     self.response_headers = None
     self.cookies = {}
     self._disconnectedDeferred = defer.Deferred()
开发者ID:rogeryan,项目名称:pokernetwork,代码行数:18,代码来源:pokerrestclient.py


示例13: __init__

    def __init__(self, headers):
        self.expires = None
        self.mtime = None
        self.length = 0
        self.start = 0
        self.size = 0
        self.mimeType = None

        headers = InsensitiveDict(headers)

        encoding = headers.get("Transfer-Encoding", None)
        if encoding == 'chunked':
            raise errors.FlumotionError("Chunked transfer not supported")

        expires = headers.get("Expires", None)
        if expires is not None:
            try:
                self.expires = http.stringToDatetime(expires)
            except:
                self.expires = 0

        lastmod = headers.get("Last-Modified", None)
        if lastmod is not None:
            self.mtime = http.stringToDatetime(lastmod)

        range = headers.get("Content-Range", None)
        length = headers.get("Content-Length", None)
        if range is not None:
            start, end, total = http.parseContentRange(range)
            self.start = start
            self.length = total
            if length is not None:
                self.size = int(length)
            else:
                self.size = end - start
        elif length is not None:
            self.length = int(length)
            self.size = int(length)
        else:
            raise errors.FlumotionError("Can't get length/size from headers",
                                        headers)

        ctype = headers.get("Content-Type", None)
        if ctype is not None:
            self.mimeType, _pdict = cgi.parse_header(ctype)
开发者ID:ApsOps,项目名称:flumotion-orig,代码行数:45,代码来源:http_client.py


示例14: __init__

    def __init__(self, dn, attributes={}):
        """

        Initialize the object.

        @param dn: Distinguished Name of the object, as a string.

        @param attributes: Attributes of the object. A dictionary of
        attribute types to list of attribute values.

        """
        self._attributes=InsensitiveDict()
        self.dn = distinguishedname.DistinguishedName(dn)

        for k,vs in attributes.items():
            if k not in self._attributes:
                self._attributes[k] = []
            self._attributes[k].extend(vs)

        for k,vs in self._attributes.items():
            self._attributes[k] = self.buildAttributeSet(k, vs)
开发者ID:AShabana,项目名称:ldaptor,代码行数:21,代码来源:entry.py


示例15: __init__

    def __init__(
        self, tagName, attributes=None, parentNode=None, filename=None,
        markpos=None, case_insensitive=1, namespace=None
    ):
        Node.__init__(self, parentNode)
        preserve_case = not case_insensitive
        tagName = tagName if preserve_case else tagName.lower()
        unescaped = unescape_dict(attributes or {})

        if case_insensitive:
            self.attributes = InsensitiveDict(unescaped, preserve=preserve_case)
        else:
            self.attributes = unescaped

        self.preserve_case = not case_insensitive
        self.case_insensitive = case_insensitive
        self.endTagName = self.nodeName = self.tagName = tagName
        self._filename = filename
        self._markpos = markpos
        self.namespace = namespace
        self.tag_is_blockelement = tagName in self.BLOCKELEMENTS
        self.tag_is_nice_format = tagName in self.NICEFORMATS
        self.tag_is_singleton = tagName.lower() in self.SINGLETONS
开发者ID:Fuzzwah,项目名称:riko,代码行数:23,代码来源:microdom.py


示例16: IRCBot

class IRCBot(irc.IRCClient):
    sasl_buffer = ""
    sasl_result = None
    sasl_login = None

    def __init__(self, factory, plugin):
        self.factory     = factory
        self.nickname    = plugin.nickname.encode('ascii')
        self.realname    = plugin.realname.encode('ascii')
        self.username    = plugin.ident.encode('ascii')
        self.ns_username = plugin.username
        self.ns_password = plugin.password
        self.password    = plugin.server_password.encode('ascii')
        self.channel     = plugin.channel.encode('ascii')
        self.console     = plugin.console
        self.irc_message = plugin.irc_message

        self.users       = InsensitiveDict()
        self.cap_requests = set()

    def register(self, nickname, hostname="foo", servername="bar"):
        self.sendLine("CAP LS")
        return irc.IRCClient.register(self, nickname, hostname, servername)

    def _parse_cap(self, cap):
        mod = ''
        while cap[0] in "-~=":
            mod, cap = mod + cap[0], cap[1:]
        if '/' in cap:
            vendor, cap = cap.split('/', 1)
        else:
            vendor = None
        return (cap, mod, vendor)

    def request_cap(self, *caps):
        self.cap_requests |= set(caps)
        self.sendLine("CAP REQ :{0}".format(' '.join(caps)))

    @defer.inlineCallbacks
    def end_cap(self):
        if self.sasl_result:
            yield self.sasl_result
        self.sendLine("CAP END")

    def irc_CAP(self, prefix, params):
        self.supports_cap = True
        identifier, subcommand, args = params
        args = args.split(' ')
        if subcommand == "LS":
            self.sasl_start(args)
            if not self.cap_requests:
                self.sendLine("CAP END")
        elif subcommand == "ACK":
            ack = []
            for cap in args:
                if not cap:
                    continue
                cap, mod, vendor = self._parse_cap(cap)
                if '-' in mod:
                    if cap in self.capabilities:
                        del self.capabilities[cap]
                    continue
                self.cap_requests.remove(cap)
                if cap == 'sasl':
                    self.sasl_next()
            if ack:
                self.sendLine("CAP ACK :{0}".format(' '.join(ack)))
            if not self.cap_requests:
                self.end_cap()
        elif subcommand == "NAK":
            # this implementation is probably not compliant but it will have to do for now
            for cap in args:
                self.cap_requests.remove(cap)
            if not self.cap_requests:
                self.end_cap()

    def signedOn(self):
        if ISSLTransport.providedBy(self.transport):
            cert = self.transport.getPeerCertificate()
            fp = cert.digest("sha1")
            verified = "verified" if self.factory.parent.server_fingerprint else "unverified"
            self.console("irc: connected securely. server fingerprint: {0} ({1})".format(fp, verified))
        else:
            self.console("irc: connected")
        
        if self.ns_username and self.ns_password and not self.sasl_login:
            self.msg('NickServ', 'IDENTIFY {0} {1}'.format(self.ns_username, self.ns_password))
        
        self.join(self.channel)

    def irc_JOIN(self, prefix, params):
        nick = prefix.split('!')[0]
        channel = params[-1]
        if nick == self.nickname:
            self.joined(channel)
        else:
            self.userJoined(prefix, channel)

    def joined(self, channel):
        self.console('irc: joined channel')
#.........这里部分代码省略.........
开发者ID:frostyfrog,项目名称:mark2,代码行数:101,代码来源:irc.py


示例17: HTTPClientFactory

class HTTPClientFactory(protocol.ClientFactory):
    """Download a given URL.

    @type deferred: Deferred
    @ivar deferred: A Deferred that will fire when the content has
          been retrieved. Once this is fired, the ivars `status', `version',
          and `message' will be set.

    @type status: str
    @ivar status: The status of the response.

    @type version: str
    @ivar version: The version of the response.

    @type message: str
    @ivar message: The text message returned with the status.

    @type response_headers: dict
    @ivar response_headers: The headers that were specified in the
          response from the server.

    @type method: str
    @ivar method: The HTTP method to use in the request.  This should be one of
        OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, or CONNECT (case
        matters).  Other values may be specified if the server being contacted
        supports them.

    @type redirectLimit: int
    @ivar redirectLimit: The maximum number of HTTP redirects that can occur
          before it is assumed that the redirection is endless.

    @type afterFoundGet: C{bool}
    @ivar afterFoundGet: Deviate from the HTTP 1.1 RFC by handling redirects
        the same way as most web browsers; if the request method is POST and a
        302 status is encountered, the redirect is followed with a GET method

    @type _redirectCount: int
    @ivar _redirectCount: The current number of HTTP redirects encountered.

    @ivar _disconnectedDeferred: A L{Deferred} which only fires after the last
        connection associated with the request (redirects may cause multiple
        connections to be required) has closed.  The result Deferred will only
        fire after this Deferred, so that callers can be assured that there are
        no more event sources in the reactor once they get the result.
    """

    protocol = HTTPPageGetter

    url = None
    scheme = None
    host = ''
    port = None
    path = None

    def __init__(self, url, method='GET', postdata=None, headers=None,
                 agent="Twisted PageGetter", timeout=0, cookies=None,
                 followRedirect=True, redirectLimit=20,
                 afterFoundGet=False):
        self.followRedirect = followRedirect
        self.redirectLimit = redirectLimit
        self._redirectCount = 0
        self.timeout = timeout
        self.agent = agent
        self.afterFoundGet = afterFoundGet
        if cookies is None:
            cookies = {}
        self.cookies = cookies
        if headers is not None:
            self.headers = InsensitiveDict(headers)
        else:
            self.headers = InsensitiveDict()
        if postdata is not None:
            self.headers.setdefault('Content-Length', len(postdata))
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("connection", "close")
        self.postdata = postdata
        self.method = method

        self.setURL(url)

        self.waiting = 1
        self._disconnectedDeferred = defer.Deferred()
        self.deferred = defer.Deferred()
        # Make sure the first callback on the result Deferred pauses the
        # callback chain until the request connection is closed.
        self.deferred.addBoth(self._waitForDisconnect)
        self.response_headers = None


    def _waitForDisconnect(self, passthrough):
        """
        Chain onto the _disconnectedDeferred, preserving C{passthrough}, so that
        the result is only available after the associated connection has been
        closed.
        """
        self._disconnectedDeferred.addCallback(lambda ignored: passthrough)
        return self._disconnectedDeferred


    def __repr__(self):
#.........这里部分代码省略.........
开发者ID:GunioRobot,项目名称:twisted,代码行数:101,代码来源:client.py


示例18: _render

    def _render(self, request, avatar):
        """Node-specific request processing.

        @param request: Web server request.
        @type request: Request

        @type avatar: Host

        @returns: nothing (not a C{Deferred} object!).
            But, due to C{inlineCallbacks}, yields the intermediate
            C{Deferred}s.

        @todo: Proper error handling.

        @todo: Properly handle the situation when the passthrough is
               restricted: generate the reply which contains the Error 404.

        @todo: This should be streamlined using super() as soon
               as C{twisted.web.resource.Resource} becomes a new-style class
        """
        assert not in_main_thread()
        # Kind-of-calling the parent, but the parent in this case should
        # return a Deferred as well,... let's not bother with it.
        # DeferredProcessingResource._render(self, request, avatar)

        logger.debug('')
        logger.debug('')
        logger.debug('Avatar %r;'
                         '\tincoming headers %r;'
                         '\tfrom %r',
                     avatar, request.requestHeaders, request.client)

        # We setup the default headers for response even before
        # we start analyzing the incoming message,
        # so that if analyzing fails for some reason, we have the headers
        # and can create a more-or-less proper error reply.
        _requestHeaders = InsensitiveDict(dict(request.requestHeaders
                                                      .getAllRawHeaders()))

        _responseHeaders = InsensitiveDict()
        self.initialize_headers(_responseHeaders)

        message = self.create_message_from_headers(headers=_requestHeaders,
                                                   auth_peer=avatar)

        message.body_receiver = RequestBodyReceiver(message=message,
                                                    request=request)

        # Make sure the body is received, before going further
        dummy_received_data = yield message.body_receiver.on_finish

        assert not in_main_thread()

        if message.direct:
            # If this is the message directed to ourselves,
            # process it and send the response
            logger.debug('')
            logger.debug('> Der Mitteilung Nahert: %r von %s',
                         message, message.src)

            # Process the incoming message
            try:
                self.tr_manager.handle_incoming_message(message)
            except TransactionProcessingException as e:
                # The incoming transaction cannot be processed.

                # TODO: handle error properly, send a error reply maybe
                logger.error('Error (%r) during incoming msg processing: %s',
                             e, e)

            logger.debug('Will send response to %r from %r %s',
                         message, message.src, hash(message.src))
            for k, v_list in _responseHeaders.iteritems():
                request.responseHeaders.setRawHeaders(k, v_list)
            logger.debug('Done with response headers')
        elif self._accept_passthrough_message(message):
            # Non-direct message, and passthrough allowed:
            # wait for the body, then put in the queue.

            logger.debug('Passthrough message %r: body already available',
                         message)
            self.tr_manager.post_message(message)

        else:
            # Passthrough is restricted for this message!
            raise NotImplementedError(u'Failed message {!r}:\n'
                                           u'from: {!r}\n'
                                           u'  to: {!r}'.format(message,
                                                                message.src,
                                                                message.dst))

        # How to check if we still need a message?
        still_need_checker = lambda: self.connection_alive

        # No matter if we are processing the message or passing it through,
        # we must send a response somehow.

        # If this is the message to us, we'd prefer a response to reply it;
        # but if this is a passthrough message, it will go to a different peer.
        prefer_msg_uuid = message.uuid if message.direct else None
#.........这里部分代码省略.........
开发者ID:shvar,项目名称:redfs,代码行数:101,代码来源:http_transport.py


示例19: __send_http_response

    def __send_http_response(self, inh, request, response_msg):
        """
        When we've know what message to send back to the HTTP client
        which has connected to the HTTP server, we issue this message back.

        @param inh: an inhabinant who will receive the response
        @type inh: AbstractInhabitant

        @param request: web server request.
        @type request: Request

        @param response_msg: response message to send.
        @type response_msg: AbstractMessage
        """
        if not self.connection_alive:
            logger.debug('Connection died inside %r while trying '
                             'to reply with %r',
                         self, response_msg)
            # That's very very bad! We should put the message back to queue.
            self.tr_manager.post_message(response_msg)
        else:
            logger.debug('Sending response %r to %r',
                         response_msg, request.requestHeaders)

            response_msg.in_transfer = True

            # Add the default server-specific headers,
            # then the message-specific headers.
            _headers = InsensitiveDict(dict(request.responseHeaders
                                                   .getAllRawHeaders()))
            _pragma = ','.join(ifilter(None, [response_msg.get_pragma(),
                                              self.extra_pragma()]))
            HTTPTransport.update_headers(_headers, {'Pragma': [_pragma]})
            HTTPTransport.update_headers(_headers, response_msg.get_headers())
            for k, v_list in _headers.iteritems():
                request.responseHeaders.setRawHeaders(k, v_list)

            logger.debug('New headers for %r are: %r',
                         response_msg, request.responseHeaders)


            @contract_epydoc
            def produce_body_in_main(body, msg):
                """
                @type body: col.Iterable
                @type msg: AbstractMessage
                """
                assert in_main_thread()

                try:
                    producer = LazyPullProducer(request, body)
                    producer.completed.addBoth(self._ready_to_finish.callback)
                except Exception:
                    logger.exception('Error during writing back the request:')
                    # We haven't succeeded to send the message to the client.
                    # Put it back to the queue.
                    callInThread(self.tr_manager.post_message, msg)


            assert not in_main_thread()  # get_body() may take long
            _body = response_msg.get_body()
            logger.debug('Writing body: %r', response_msg)

            callFromThread(produce_body_in_main, _body, response_msg)
开发者ID:shvar,项目名称:redfs,代码行数:64,代码来源:http_transport.py


示例20: IRCBot

class IRCBot(irc.IRCClient):
    sasl_buffer = ""
    sasl_result = None
    sasl_login = None

    cancel_hilight_re = re.compile(ur"(?:(?<=\u00a7[0-9a-flmnor])|(?<!\u00a7)\b).+?\b")

    def __init__(self, factory, parent):
        self.factory     = factory
        self.nickname    = parent.nickname.encode('ascii')
        self.realname    = parent.realname.encode('ascii')
        self.username    = parent.ident.encode('ascii')
        self.ns_username = parent.username
        self.ns_password = parent.password
        self.password    = parent.server_password.encode('ascii')
        self.join_channels = parent.channel_map.keys()

        self.users        = InsensitiveDict()
        self.channels     = InsensitiveDict()
        self.cap_requests = set()

        self.parent = parent

    def register(self, nickname, hostname="foo", servername="bar"):
        self.sendLine("CAP LS")
        return irc.IRCClient.register(self, nickname, hostname, servername)

    def sendLine(self, line):
        if isinstance(line, unicode):
            line = line.encode('utf8', 'replace')
        irc.IRCClient.sendLine(self, line)

    def _parse_cap(self, cap):
        mod = ''
        while cap[0] in "-~=":
            mod, cap = mod + cap[0], cap[1:]
        if '/' in cap:
            vendor, cap = cap.split('/', 1)
        else:
            vendor = None
        return (cap, mod, vendor)

    def request_cap(self, *caps):
        self.cap_requests |= set(caps)
        self.sendLine("CAP REQ :{0}".format(' '.join(caps)))

    @defer.inlineCallbacks
    def end_cap(self):
        if self.sasl_result:
            yield self.sasl_result
        self.sendLine("CAP END")

    def irc_CAP(self, prefix, params):
        self.supports_cap = True
        identifier, subcommand, args = params
        args = args.split(' ')
        if subcommand == "LS":
            self.sasl_start(args)
            if not self.cap_requests:
                self.sendLine("CAP END")
        elif subcommand == "ACK":
            ack = []
            for cap in args:
                if not cap:
                    continue
                cap, mod, vendor = self._parse_cap(cap)
                if '-' in mod:
                    if cap in self.capabilities:
                        del self.capabilities[cap]
                    continue
                self.cap_requests.remove(cap)
                if cap == 'sasl':
                    self.sasl_next()
            if ack:
                self.sendLine("CAP ACK :{0}".format(' '.join(ack)))
            if not self.cap_requests:
                self.end_cap()
        elif subcommand == "NAK":
            # this implementation is probably not compliant but it will have to do for now
            for cap in args:
                self.cap_requests.remove(cap)
            if not self.cap_requests:
                self.end_cap()

    def signedOn(self):
        if ISSLTransport.providedBy(self.transport):
            cert = self.transport.getPeerCertificate()
            fp = cert.digest("sha1")
            verified = "verified" if self.factory.parent.server_fingerprint else "unverified"
            print("irc: connected securely. server fingerprint: {0} ({1})".format(fp, verified))
        else:
            print("irc: connected")
        
        if self.ns_username and self.ns_password and not self.sasl_login:
            self.msg('NickServ', 'IDENTIFY {0} {1}'.format(self.ns_username, self.ns_password))
        
        for channel in self.join_channels:
            self.join(channel)

    def irc_JOIN(self, prefix, params):
#.........这里部分代码省略.........
开发者ID:edk0,项目名称:IAmARelayBotAMA,代码行数:101,代码来源:ircbot.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python versions.getVersionString函数代码示例发布时间:2022-05-27
下一篇:
Python util.untilConcludes函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap