twisted.internet.defer.returnValue

Here are the examples of the python api twisted.internet.defer.returnValue taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

View license
    @inlineCallbacks
    def _srp_auth(self, username, password):
        try:
            auth = yield self._bonafide_auth(username, password)
        except SRPAuthError:
            raise UnauthorizedLogin("User typed wrong password/username combination.")
        returnValue(auth)

Example 2

View license
    @inlineCallbacks
    def _bonafide_auth(self, user, password):
        srp_provider = Api(self._leap_provider.api_uri)
        credentials = Credentials(user, password)
        srp_auth = Session(credentials, srp_provider, self._leap_provider.local_ca_crt)
        yield srp_auth.authenticate()
        returnValue(Authentication(user, srp_auth.token, srp_auth.uuid, 'session_id', {'is_admin': False}))

Example 3

View license
    @inlineCallbacks
    def get_or_create_user(self, invite_code=None):
        try:
            yield self.authenticate()
        except UnauthorizedLogin:
            yield self.register(invite_code)
        user = (self._username, self._password)
        returnValue(user)

Example 4

Project: rollingpin
Source File: frontends.py
View license
    @inlineCallbacks
    def read_character(self):
        while True:
            character = yield self.character_waiter
            if character:
                returnValue(character)

Example 5

Project: rollingpin
Source File: frontends.py
View license
    @inlineCallbacks
    def raw_input(self, prompt):
        self.restore_terminal_settings()

        try:
            sys.stdout.write(prompt)
            sys.stdout.flush()

            line = yield self.character_waiter
            returnValue(line.rstrip("\n"))
        finally:
            self.disable_echo()

Example 6

Project: rollingpin
Source File: autoscaler.py
View license
@inlineCallbacks
def parallel_map(iterable, fn, *args, **kwargs):
    deferreds = []
    parallelism_limiter = DeferredSemaphore(MAX_PARALLELISM)
    for item in iterable:
        d = parallelism_limiter.run(fn, item, *args, **kwargs)
        deferreds.append(d)
    results = yield gatherResults(deferreds)
    returnValue(results)

Example 7

Project: rollingpin
Source File: mock.py
View license
    @inlineCallbacks
    def connect_to(self, host):
        yield sleep(random.random() * 2)

        connection = MockTransportConnection()
        returnValue(connection)

Example 8

Project: rollingpin
Source File: ssh.py
View license
    @inlineCallbacks
    def connect_to(self, host):
        factory = _ConnectionFactory(self.config, self.key)

        port = self.config["transport"]["port"]
        timeout = self.config["transport"]["timeout"]

        try:
            connector = reactor.connectTCP(
                host, port, factory, timeout=timeout)
            connection = yield factory.connection_ready
        except (ConnectError, DNSLookupError) as e:
            raise ConnectionError(str(e))

        command_binary = self.config["transport"]["command"]
        transport_connection = SshTransportConnection(
            command_binary, connector, connection)
        returnValue(transport_connection)

Example 9

Project: rollingpin
Source File: ssh.py
View license
    @inlineCallbacks
    def execute(self, log, command):
        args = " ".join(pipes.quote(part) for part in command)
        command = "sudo %s %s" % (self.command_binary, args)

        channel = _CommandChannel(
            log, command, conn=self.connection)
        self.connection.openChannel(channel)
        result = yield channel.finished
        returnValue(result)

Example 10

Project: gazouilleur
Source File: microblog.py
View license
    @inlineCallbacks
    def get_stats(self, **kwargs):
        timestamp = timestamp_hour(datetime.today())
        try:
            last = yield find_stats({'user': self.user.lower()}, limit=1, filter=sortdesc('timestamp'))
            last = last[0]
        except:
            last = {}
        if last and last['timestamp'] == timestamp:
            res = None
        else:
            res = self._send_query(self.conn.users.show, {'screen_name': self.user}, return_result=True)
        check_twitter_results(res)
        returnValue((res, last, timestamp))

Example 11

Project: umongo
Source File: app.py
View license
@app.route('/users/<nick_or_id>', methods=['GET'])
@locale_from_request
@inlineCallbacks
def get_user(request, nick_or_id):
    user = yield User.find_one(_nick_or_id_lookup(nick_or_id))
    if not user:
        raise Error(404, 'Not found')
    returnValue(jsonify(request, dump_user_no_pass(user)))

Example 12

Project: umongo
Source File: app.py
View license
@app.route('/users/<nick_or_id>', methods=['DELETE'])
@locale_from_request
@inlineCallbacks
def delete_user(request, nick_or_id):
    user = yield User.find_one(_nick_or_id_lookup(nick_or_id))
    if not user:
        raise Error(404, 'Not Found')
    try:
        yield user.delete()
    except ValidationError as ve:
        raise Error(400, jsonify(message=ve.args[0]))
    returnValue('Ok')

Example 13

Project: umongo
Source File: app.py
View license
@app.route('/users', methods=['GET'])
@locale_from_request
@inlineCallbacks
def list_users(request):
    page = int(request.args.get('page', 1))
    users = yield User.find(limit=10, skip=(page - 1) * 10)
    returnValue(jsonify(request, {
        '_total': (yield User.count()),
        '_page': page,
        '_per_page': 10,
        '_items': [dump_user_no_pass(u) for u in users]
    }))

Example 14

Project: umongo
Source File: app.py
View license
@app.route('/users', methods=['POST'])
@locale_from_request
@inlineCallbacks
def create_user(request):
    payload = get_json(request)
    if payload is None:
        raise Error(400, 'Request body must be json with Content-type: application/json')
    try:
        user = User(**payload)
        yield user.commit()
    except ValidationError as ve:
        raise Error(400, jsonify(request, message=ve.args[0]))
    returnValue(jsonify(request, dump_user_no_pass(user)))

Example 15

Project: umongo
Source File: txmongo.py
View license
    @inlineCallbacks
    def fetch(self, no_data=False):
        if not self._document:
            if self.pk is None:
                raise ReferenceError('Cannot retrieve a None Reference')
            self._document = yield self.document_cls.find_one(self.pk)
            if not self._document:
                raise ValidationError(self.error_messages['not_found'].format(
                    document=self.document_cls.__name__))
        returnValue(self._document)

Example 16

Project: scrapyd
Source File: poller.py
View license
    @inlineCallbacks
    def poll(self):
        if self.dq.pending:
            return
        for p, q in self.queues.iteritems():
            c = yield maybeDeferred(q.count)
            if c:
                msg = yield maybeDeferred(q.pop)
                returnValue(self.dq.put(self._message(msg, p)))

Example 17

Project: SickRage
Source File: twisted_test.py
View license
    def test_success(self):
        @inlineCallbacks
        def fn():
            if False:
                # inlineCallbacks doesn't work with regular functions;
                # must have a yield even if it's unreachable.
                yield
            returnValue(42)
        f = gen.convert_yielded(fn())
        self.assertEqual(f.result(), 42)

Example 18

Project: tahoe-lafs
Source File: test_runner.py
View license
    @inlineCallbacks
    def find_import_location(self):
        res = yield self.run_bintahoe(["--version-and-path"])
        out, err, rc_or_sig = res
        self.assertEqual(rc_or_sig, 0, res)
        lines = out.splitlines()
        tahoe_pieces = lines[0].split()
        self.assertEqual(tahoe_pieces[0], "%s:" % (__appname__,), (tahoe_pieces, res))
        returnValue(tahoe_pieces[-1].strip("()"))

Example 19

Project: tahoe-lafs
Source File: i2p_provider.py
View license
@inlineCallbacks
def _connect_to_i2p(reactor, cli_config, txi2p):
    # we assume i2p is already running
    ports_to_try = ["tcp:127.0.0.1:7656"]
    if cli_config["i2p-sam-port"]:
        ports_to_try = [cli_config["i2p-sam-port"]]
    for port in ports_to_try:
        accessible = yield _try_to_connect(reactor, port, cli_config.stdout,
                                           txi2p)
        if accessible:
            returnValue(port) ; break # helps editor
    else:
        raise ValueError("unable to reach any default I2P SAM port")

Example 20

Project: tahoe-lafs
Source File: tor_provider.py
View license
@inlineCallbacks
def _connect_to_tor(reactor, cli_config, txtorcon):
    # we assume tor is already running
    ports_to_try = ["unix:/var/run/tor/control",
                    "tcp:127.0.0.1:9051",
                    "tcp:127.0.0.1:9151", # TorBrowserBundle
                    ]
    if cli_config["tor-control-port"]:
        ports_to_try = [cli_config["tor-control-port"]]
    for port in ports_to_try:
        tor_state = yield _try_to_connect(reactor, port, cli_config.stdout,
                                          txtorcon)
        if tor_state:
            tor_control_proto = tor_state.protocol
            returnValue((port, tor_control_proto)) ; break # helps editor
    else:
        raise ValueError("unable to reach any default Tor control port")

Example 21

Project: tahoe-lafs
Source File: tor_provider.py
View license
    @inlineCallbacks
    def _make_control_endpoint(self, reactor):
        # this will only be called when tahoe.cfg has "[tor] launch = true"
        (endpoint_desc, _) = yield self._get_launched_tor(reactor)
        tor_control_endpoint = clientFromString(reactor, endpoint_desc)
        returnValue(tor_control_endpoint)

Example 22

Project: tornado-zh
Source File: twisted_test.py
View license
    def test_success(self):
        @inlineCallbacks
        def fn():
            if False:
                # inlineCallbacks doesn't work with regular functions;
                # must have a yield even if it's unreachable.
                yield
            returnValue(42)
        f = gen.convert_yielded(fn())
        self.assertEqual(f.result(), 42)

Example 23

Project: autologin
Source File: http_api.py
View license
    @inlineCallbacks
    def _login(self, runner, login_url, username, password, extra_js=None):
        async_items = scrape_items(runner,
                                   LoginSpider,
                                   url=login_url,
                                   username=username,
                                   password=password,
                                   extra_js=extra_js)
        while (yield async_items.fetch_next):
            returnValue(async_items.next_item())

Example 24

Project: autologin
Source File: spiders.py
View license
    @inlineCallbacks
    def solve_captcha(self, page_form):
        from decaptcha.exceptions import DecaptchaError
        form_screenshot = b64decode(page_form['screenshot'])
        self.debug_screenshot('captcha', form_screenshot)
        try:
            captcha_value = yield self.solver.solve(form_screenshot)
        except DecaptchaError as e:
            self.logger.error('captcha not solved', exc=e)
            returnValue(None)
        else:
            self.logger.debug('captcha solved: "%s"' % captcha_value)
            self.attempted_captchas.append(form_screenshot)
            returnValue(captcha_value)

Example 25

Project: tornado
Source File: twisted_test.py
View license
    def test_success(self):
        @inlineCallbacks
        def fn():
            if False:
                # inlineCallbacks doesn't work with regular functions;
                # must have a yield even if it's unreachable.
                yield
            returnValue(42)
        f = gen.convert_yielded(fn())
        self.assertEqual(f.result(), 42)

Example 26

Project: txAMQP
Source File: testlib.py
View license
    @inlineCallbacks
    def queue_declare(self, channel=None, *args, **keys):
        channel = channel or self.channel
        reply = yield channel.queue_declare(*args, **keys)
        self.queues.append((channel, reply.queue))
        returnValue(reply)

Example 27

Project: txAMQP
Source File: testlib.py
View license
    @inlineCallbacks
    def exchange_declare(self, channel=None, ticket=0, exchange='',
                         type='', passive=False, durable=False,
                         auto_delete=False, internal=False, nowait=False,
                         arguments={}):
        channel = channel or self.channel
        reply = yield channel.exchange_declare(ticket, exchange, type, passive, durable, auto_delete, internal, nowait, arguments)
        self.exchanges.append((channel,exchange))
        returnValue(reply)

Example 28

Project: foolscap
Source File: tor.py
View license
    @inlineCallbacks
    def hint_to_endpoint(self, hint, reactor):
        # Return (endpoint, hostname), where "hostname" is what we pass to the
        # HTTP "Host:" header so a dumb HTTP server can be used to redirect us.
        mo = HINT_RE.search(hint)
        if not mo:
            raise InvalidHintError("unrecognized TCP/Tor hint")
        host, portnum = mo.group(1), int(mo.group(2))
        if is_non_public_numeric_address(host):
            raise InvalidHintError("ignoring non-Tor-able ipaddr %s" % host)
        socks_endpoint = yield self._maybe_connect(reactor)
        # txsocksx doesn't like unicode: it concatenates some binary protocol
        # bytes with the hostname when talking to the SOCKS server, so the
        # py2 automatic unicode promotion blows up
        host = host.encode("ascii")
        ep = txtorcon.TorClientEndpoint(host, portnum,
                                        socks_endpoint=socks_endpoint)
        returnValue( (ep, host) )

Example 29

Project: magic-wormhole
Source File: transit.py
View license
    @inlineCallbacks
    def get_connection_hints(self):
        hints = []
        direct_hints = yield self._get_direct_hints()
        for dh in direct_hints:
            hints.append({u"type": u"direct-tcp-v1",
                          u"hostname": dh.hostname,
                          u"port": dh.port, # integer
                          })
        for relay in self._transit_relays:
            rhint = {u"type": u"relay-v1", u"hints": []}
            for rh in relay.hints:
                rhint[u"hints"].append({u"type": u"direct-tcp-v1",
                                        u"hostname": rh.hostname,
                                        u"port": rh.port})
            hints.append(rhint)
        returnValue(hints)

Example 30

Project: magic-wormhole
Source File: transit.py
View license
    @inlineCallbacks
    def connect(self):
        with self._timing.add("transit connect"):
            yield self._get_transit_key()
            # we want to have the transit key before starting any outbound
            # connections, so those connections will know what to say when
            # they connect
            winner = yield self._connect()
        returnValue(winner)

Example 31

Project: magic-wormhole
Source File: wormhole.py
View license
    @inlineCallbacks
    def go(self):
        with self._timing.add("allocate"):
            self._send_command("allocate")
            nameplate_id = yield self._allocated_d
        code = codes.make_code(nameplate_id, self._code_length)
        assert isinstance(code, type("")), type(code)
        returnValue(code)

Example 32

Project: magic-wormhole
Source File: wormhole.py
View license
    @inlineCallbacks
    def _list(self):
        self._lister_d = defer.Deferred()
        self._send_command("list")
        nameplates = yield self._lister_d
        self._lister_d = None
        returnValue(nameplates)

Example 33

Project: magic-wormhole
Source File: wormhole.py
View license
    @inlineCallbacks
    def _API_close(self, res, mood="happy"):
        if self.DEBUG: print("close")
        if self._close_called: raise InternalError
        self._close_called = True
        self._maybe_close(WormholeClosedError(), mood)
        if self.DEBUG: print("waiting for disconnect")
        yield self._disconnect_waiter
        returnValue(res)

Example 34

Project: txamqp
Source File: testlib.py
View license
    @inlineCallbacks
    def queue_declare(self, channel=None, *args, **keys):
        channel = channel or self.channel
        reply = yield channel.queue_declare(*args, **keys)
        self.queues.append((channel, reply.queue))
        returnValue(reply)

Example 35

Project: txamqp
Source File: testlib.py
View license
    @inlineCallbacks
    def exchange_declare(self, channel=None, ticket=0, exchange='',
                         type='', passive=False, durable=False,
                         auto_delete=False, internal=False, nowait=False,
                         arguments={}):
        channel = channel or self.channel
        reply = yield channel.exchange_declare(ticket, exchange, type, passive, durable, auto_delete, internal, nowait, arguments)
        self.exchanges.append((channel,exchange))
        returnValue(reply)

Example 36

View license
    @inlineCallbacks
    def serviceCatalog(self):
        if self._serviceCatalog is None:
            yield self.login()

        returnValue(self._serviceCatalog)

Example 37

View license
    @inlineCallbacks
    def collect(self, config):
        log.debug("Collect for OpenStack Neutron Agent Status (%s)" % config.id)
        ds0 = config.datasources[0]

        client = APIClient(
            ds0.zCommandUsername,
            ds0.zCommandPassword,
            ds0.zOpenStackAuthUrl,
            ds0.zOpenStackProjectId)

        results = {}

        log.debug('Requesting agent-list')
        result = yield client.neutron_agents()
        results['agents'] = result['agents']

        defer.returnValue(results)

Example 38

Project: python-consul
Source File: twisted.py
View license
    @inlineCallbacks
    def _get_resp(self, response):
        # Merge multiple header values as per RFC2616
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
        headers = {
            self.compat_string(k): ','.join(map(self.compat_string, v))
            for k, v in dict(response.headers.getAllRawHeaders()).items()
        }
        body = yield response.text(encoding='utf-8')
        returnValue((response.code, headers, body))

Example 39

Project: conn-check
Source File: check_impl.py
View license
    @inlineCallbacks
    def check(self, pattern, results):
        """Call the check function."""
        if not pattern.matches(self.name):
            returnValue(None)
        results.notify_start(self.name, self.info)
        start = time.time()
        try:
            if self.blocking:
                result = yield maybeDeferToThread(self.check_fn)
            else:
                result = yield maybeDeferred(self.check_fn)
            results.notify_success(self.name, time.time() - start)
            returnValue(result)
        except Exception:
            results.notify_failure(self.name, self.info,
                                   sys.exc_info(), time.time() - start)

Example 40

Project: canvas
Source File: channels.py
View license
    @inlineCallbacks
    def backlog(self, start=-1):
        try:
            raw_json = yield self.svc.redis.zrangebyscore(self.rc.msg_backlog.key, start + 1, count=100, withscores=True)
        except RuntimeError:
            raise Channel.DisconnectedError
        messages = [{'id': int(id), 'payload': util.loads(payload)} for (payload, id) in raw_json]
        if not messages: returnValue({})
        else: returnValue({self.rc.channel: messages})

Example 41

Project: canvas
Source File: resources.py
View license
@inlineCallbacks
def wait_all(deferreds):
    try:
        returnValue((yield DeferredList(deferreds, fireOnOneCallback=False, fireOnOneErrback=True, consumeErrors=True)))
    except FirstError, exc:
        raise exc.subFailure.value

Example 42

Project: autobahn-testsuite
Source File: massconnect.py
View license
   @inlineCallbacks
   def run(self):
      print self.spec
      res = []
      for s in self.spec['servers']:
         t = MassConnect(s['name'],
                         s['uri'],
                         self.spec['options']['connections'],
                         self.spec['options']['batchsize'],
                         self.spec['options']['batchdelay'],
                         self.spec['options']['retrydelay'])
         r = yield t.run()
         res.append(r)
      returnValue(res)

Example 43

Project: crossbar
Source File: tx.py
View license
    @inlineCallbacks
    def _handle(self, data):

        try:
            res = yield self._handle_data(data)
            returnValue(res)
        except Exception:
            raise

Example 44

View license
  def testSimple(self):
    """Tests return of a simple value."""

    @inline.callbacks
    def simple():
      """Simple asynchronous function that returns a value."""
      yield time.sleep(0.01)
      defer.returnValue(5)

    return simple().addBoth(lambda result: self.assertEqual(5, result))

Example 45

View license
  def testChain(self):
    """Tests return of a chained value."""

    @inline.callbacks
    def chained():
      """Simple asynchronous function that returns a value."""
      result = yield time.sleep(0.01).addCallback(lambda _: time.sleep(0.01).addCallback(lambda _: 3.14))
      defer.returnValue(result)

    return chained().addBoth(lambda result: self.assertEqual(3.14, result))

Example 46

View license
  def testTuple(self):
    """Tests return of a tuple."""

    @inline.callbacks
    def tupleReturn():
      """Simple asynchronous function that returns a tuple."""
      yield time.sleep(0.01)
      defer.returnValue((5, 'abc'))

    return tupleReturn().addBoth(lambda result: self.assertEqual((5, 'abc'), result))

Example 47

View license
  def testUnroll(self):
    """Tests that a large stack isn't created."""

    @inline.callbacks
    def instantYields():
      """Simple asynchronous function that has instant results for a large number of yields."""
      for i in xrange(1000):
        yield i
      yield time.sleep(0.01) # Make it actually async.
      defer.returnValue('done')

    return instantYields().addBoth(lambda result: self.assertEqual('done', result))

Example 48

View license
  def testSynchronous(self):
    """Tests handling of synchronous results."""

    @inline.callbacks
    def synchronousResult():
      """Simple asynchronous function that is not really asynchronous."""
      yield 100
      defer.returnValue(200)

    self.assertEqual(200, synchronousResult())

Example 49

View license
  def testDescribeInlineDeferredFunction(self):
    """Test debugging descriptions of inline deferred functions."""

    @inline.callbacks
    def simple():
      """Simple asynchronous function."""
      yield time.sleep(0.01)
      defer.returnValue(200)

    d = simple()
    self.assertEquals(d.describeDeferred().partition(' -> ')[0], 'simple:0')
    return d.addBoth(lambda result: self.assertEqual(200, result))

Example 50

Project: greplin-twisted-utils
Source File: dnsRetry.py
View license
  @inline.callbacks
  def getHostByName(self, name, *args):
    """Gets a host by name."""
    sleepManager = None
    for tryIndex in range(self._tries):
      try:
        result = yield self._original.getHostByName(name, *args)
        defer.returnValue(result)
      except Exception: # This is intended to catch general exceptions! # pylint: disable=W0703
        if tryIndex == self._tries - 1:
          raise
        else:
          logging.warning('Failed to resolve %s', name, exc_info = True)
      sleepManager = sleepManager or self._sleep.clone()
      yield sleepManager.sleep()