def attach_stream(self, stream, circuits):
        if stream.target_host not in self.state.addrmap.addr:
            print "No AddrMap entry for", stream.target_host,
            print "so I don't know where it exits; get Tor to attach stream."
            return None

        ip = str(self.state.addrmap.addr[stream.target_host].ip)
        stream_cc = txtorcon.util.NetLocation(ip).countrycode
        print "Stream to", ip, "exiting in", stream_cc

        if stream_cc is None:
            # returning None tells TorState to ask Tor to select a
            # circuit instead
            print "   unknown country, Tor will assign stream"
            return None

        for circ in circuits.values():
            if circ.state != 'BUILT' or circ.purpose != 'GENERAL':
                continue

            circuit_cc = circ.path[-1].location.countrycode
            if circuit_cc is None:
                print "warning: don't know where circuit", circ.id, "exits"

            if circuit_cc == stream_cc:
                print "  found suitable circuit:", circ
                return circ

        # if we get here, we haven't found a circuit that exits in
        # the country GeoIP claims our target server is in, so we
        # need to build one.
        print "Didn't find a circuit, building one"

        # we need to return a Deferred which will callback with our
        # circuit, however built_circuit only callbacks with the
        # message from Tor saying it heard about our request. So when
        # that happens, we push our real Deferred into the
        # waiting_circuits list which will get pop'd at some point
        # when the circuit_built() listener callback happens.

        d = defer.Deferred()
        self.request_circuit_build(stream_cc, d)
        return d
IStreamAttacher API
dataset/ETHPy150Open meejah/txtorcon/examples/attach_streams_by_country.py/MyAttacher.attach_stream