aiohttp.request

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

76 Examples 7

Page 1 Selected Page 2

Example 1

Project: python-consul Source File: aio.py
    @asyncio.coroutine
    def _request(self, callback, method, uri, data=None):
        resp = yield from aiohttp.request(method, uri,
                                          connector=self._connector,
                                          data=data, loop=self._loop)
        body = yield from resp.text(encoding='utf-8')
        if resp.status == 599:
            raise base.Timeout
        r = base.Response(resp.status, resp.headers, body)
        return callback(r)

Example 2

Project: Flask-aiohttp Source File: app.py
Function: api
@app.route('/api')
@async
def api():
    response = yield from aiohttp.request(
        'GET', 'https://graph.facebook.com/zuck')
    data = yield from response.read()
    return data

Example 3

Project: vyked Source File: pinger.py
    def ping_coroutine(self, payload=None):
        try:
            res = yield from request('get', self._url)
            if res.status == 200:
                self.pong_received(payload=payload)
                res.close()
        except Exception:
            self.logger.exception('Error while ping')

Example 4

Project: aiorest Source File: server_test.py
Function: test_simple_get
    def test_simple_GET(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
                                           self.server.make_handler,
                                           '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/post/123'.format(port)

        def query():
            response = yield from aiohttp.request('GET', url, loop=self.loop)
            self.assertEqual(200, response.status)
            data = yield from response.read()
            self.assertEqual(b'{"success": true}', data)

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 5

Project: aiorest Source File: cookie_session_test.py
    @mock.patch('aiorest.session.cookie_session.time')
    def test_get_from_session(self, time_mock):
        time_mock.time.return_value = 1
        with self.run_server() as (srv, base_url):

            url = base_url + '/get'

            @asyncio.coroutine
            def query():
                resp = yield from aiohttp.request(
                    'GET', url,
                    cookies={'test_cookie': make_cookie({'foo': 'bar'}, 1)},
                    loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)

            self.loop.run_until_complete(query())

Example 6

Project: ks-email-parser Source File: service.py
    def request(self, path='', method='GET', timeout=5, **kwargs):
        url = urllib.parse.urljoin(self._host, path)
        req = aiohttp.request(method, url, loop=self._loop, **kwargs)
        try:
            res = yield from asyncio.wait_for(req, timeout, loop=self._loop)
        except concurrent.futures.TimeoutError:
            msg = 'service request timed out after %ss' % timeout
            raise TimeoutError(msg)
        if res.status != 200:
            text = yield from res.text()
            raise ServiceError('service returned error', res.status, text)
        return (yield from res.text())

Example 7

Project: gns3-server Source File: test_file.py
def test_stream_file_not_pcap(server, tmpdir, loop):
    def go(future):
        query = json.dumps({"location": str(tmpdir / "test")})
        headers = {'content-type': 'application/json'}
        response = yield from aiohttp.request("GET", server.get_url("/files/stream", 1), data=query, headers=headers)
        response.close()
        future.set_result(response)

    future = asyncio.Future()
    asyncio.async(go(future))
    response = loop.run_until_complete(future)
    assert response.status == 403

Example 8

Project: aiorest Source File: cors_test.py
    def test_preflight_404(self):
        with self.run_server() as url:

            @asyncio.coroutine
            def query():
                resp = yield from aiohttp.request('OPTIONS', url,
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 404)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)

            self.loop.run_until_complete(query())

Example 9

Project: drogulus Source File: http.py
    def send(self, contact, message, sender=None):
        """
        Sends the message to the referenced contact. The sender argument isn't
        required for the HTTP implementation.
        """
        payload = to_dict(message)
        headers = {'content-type': 'application/json'}
        return asyncio.Task(aiohttp.request('post',
                                            contact.uri,
                                            data=json.dumps(payload),
                                            headers=headers))

Example 10

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_dummy_setup_roundtrip(self):
        """Test a dummy configuration with a message round-trip."""
        app = web.Application()
        setup(app)

        app.router.add_route("GET", "/", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 11

Project: pycon2014 Source File: e06asyncextract.py
Function: fetch_async
@asyncio.coroutine
def fetch_async(url):
    logging.info('Fetching %s', url)
    response = yield from aiohttp.request('get', url, timeout=5)
    try:
        assert response.status == 200
        data = yield from response.read()
        assert data
        return data.decode('utf-8')
    finally:
        response.close()

Example 12

Project: aiorest Source File: cors_test.py
Function: test_preflight
    def test_preflight(self):
        with self.run_server() as url:

            @asyncio.coroutine
            def query():
                headers = {
                    'ACCESS-CONTROL-REQUEST-METHOD': 'GET',
                    'ORIGIN': 'localhost',
                    }
                resp = yield from aiohttp.request('OPTIONS', url,
                                                  headers=headers,
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                self.assertIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)
                self.assertEqual(resp.headers['ACCESS-CONTROL-ALLOW-ORIGIN'],
                                 '*')

            self.loop.run_until_complete(query())

Example 13

Project: aiorest Source File: cors_test.py
Function: test_simple_get
    def test_simple_GET(self):
        with self.run_server() as url:

            @asyncio.coroutine
            def query():
                headers = {
                    'ORIGIN': 'localhost',
                    }
                resp = yield from aiohttp.request('GET', url,
                                                  headers=headers,
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                self.assertIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)
                self.assertEqual(resp.headers['ACCESS-CONTROL-ALLOW-ORIGIN'],
                                 '*')

            self.loop.run_until_complete(query())

Example 14

Project: aiorest Source File: server_test.py
Function: test_set_cookie
    def test_set_cookie(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/cookie/123'.format(port)

        @asyncio.coroutine
        def query():
            response = yield from aiohttp.request('GET', url, loop=self.loop)
            yield from response.read()
            self.assertEqual(200, response.status)
            self.assertIn('test_cookie', response.cookies)
            self.assertEqual(response.cookies['test_cookie'].value, '123')

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 15

Project: python-concurrency Source File: async_imgur.py
@asyncio.coroutine
def async_download_link(directory, link):
    download_path = directory / os.path.basename(link)
    response = yield from aiohttp.request('get', link)
    with download_path.open('wb') as f:
        while True:
            chunk = yield from response.content.read(1000)
            if not chunk:
                break
            f.write(chunk)
    logger.info('Downloaded %s', link)

Example 16

Project: gns3-server Source File: test_file.py
def test_stream_file_not_found(server, tmpdir, loop):
    def go(future):
        query = json.dumps({"location": str(tmpdir / "test.pcap")})
        headers = {'content-type': 'application/json'}
        response = yield from aiohttp.request("GET", server.get_url("/files/stream", 1), data=query, headers=headers)
        response.close()
        future.set_result(response)

    future = asyncio.Future()
    asyncio.async(go(future))
    response = loop.run_until_complete(future)
    assert response.status == 404

Example 17

Project: aiorest Source File: server_test.py
Function: test_no_session
    def test_no_session(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/check/no/session'.format(port)

        @asyncio.coroutine
        def query():
            resp = yield from aiohttp.request('GET', url, loop=self.loop)
            self.assertEqual(200, resp.status)
            yield from resp.read()
        self.loop.run_until_complete(query())

Example 18

Project: gns3-server Source File: test_project.py
Function: test_notification
def test_notification(server, project, loop):
    @asyncio.coroutine
    def go(future):
        response = yield from aiohttp.request("GET", server.get_url("/projects/{project_id}/notifications".format(project_id=project.id), 1))
        response.body = yield from response.content.read(200)
        project.emit("vm.created", {"a": "b"})
        response.body += yield from response.content.read(50)
        response.close()
        future.set_result(response)

    future = asyncio.Future()
    asyncio.async(go(future))
    response = loop.run_until_complete(future)
    assert response.status == 200
    assert b'"action": "ping"' in response.body
    assert b'"cpu_usage_percent"' in response.body
    assert b'{"action": "vm.created", "event": {"a": "b"}}\n' in response.body

Example 19

Project: aiorest Source File: cookie_session_test.py
    @mock.patch('aiorest.session.cookie_session.time')
    def test_init_session(self, time_mock):
        time_mock.time.return_value = 1
        with self.run_server() as (srv, base_url):
            url = base_url + '/init'

            @asyncio.coroutine
            def query():
                resp = yield from aiohttp.request('GET', url, loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                cookies = {k: v.value for k, v in resp.cookies.items()}
                value = make_cookie({'foo': 'bar'}, 1)
                self.assertEqual(cookies, {'test_cookie': value})

            self.loop.run_until_complete(query())

Example 20

Project: webbies Source File: Bing.py
Function: search
    @asyncio.coroutine
    def search(self,query,page):
        params = {
            "Query":query,
            "$skip": self.parameters["$top"] * page
        }
        params.update(self.parameters)
        try:
            r = yield from aiohttp.request(
                    'get',
                    self.url,
                    params=params,
                    headers=self.headers
                    )
            results = yield from r.json()
            yield from self.__process(results)
        except aiohttp.ClientError as client_error:
            print("Error: {emsg}".format(emsg=client_error))

Example 21

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_message_roundtrip(self):
        """Test that aiohttp server is correctly setup in the base class."""

        app = web.Application()

        app.router.add_route("GET", "/", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 22

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_dummy_setup_roundtrip_resource(self):
        """Test a dummy configuration with a message round-trip."""
        app = web.Application()
        setup(app)

        app.router.add_resource("/").add_route("GET", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 23

Project: pusher-http-python Source File: aiohttp.py
    def send_request(self, request):
        method = request.method
        url = "%s%s" % (request.base_url, request.path)
        params = request.query_params
        data = request.body
        headers = request.headers

        response = yield from asyncio.wait_for(
            aiohttp.request(
                method, url, params=params, data=data, headers=headers,
                connector=self.conn),
            timeout=self.client.timeout)

        body = yield from response.read_and_close()
        return process_response(response.status, body.decode('utf8'))

Example 24

Project: interest Source File: tester.py
Function: request
    def request(self, method, path, **kwargs):
        @asyncio.coroutine
        def coroutine():
            response = yield from aiohttp.request(
                method, self.__make_url(path), **kwargs)
            try:
                response.read = yield from response.read()
                response.text = yield from response.text()
                response.json = yield from response.json()
            except Exception:
                pass
            return response
        response = self.__loop.run_until_complete(coroutine())
        return response

Example 25

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_headers_resource(self):
        """Test CORS preflight request handlers handling."""
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers=("Content-Type", "X-Header"),
            )
        })

        cors.add(app.router.add_route("PUT", "/", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type",
            }
        )
        self.assertEqual((yield from response.text()), "")
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS].upper(),
            "content-type".upper())

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "X-Header,content-type",
            }
        )
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            frozenset(response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS]
                      .upper().split(",")),
            {"X-Header".upper(), "content-type".upper()})
        self.assertEqual((yield from response.text()), "")

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type,Test",
            }
        )
        self.assertEqual(response.status, 403)
        self.assertNotIn(
            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
            response.headers)
        self.assertIn(
            "headers are not allowed: TEST",
            (yield from response.text()))

Example 26

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_headers(self):
        """Test CORS preflight request handlers handling."""
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers=("Content-Type", "X-Header"),
            )
        })

        resource = cors.add(app.router.add_resource("/"))
        cors.add(resource.add_route("PUT", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type",
            }
        )
        self.assertEqual((yield from response.text()), "")
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS].upper(),
            "content-type".upper())

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "X-Header,content-type",
            }
        )
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            frozenset(response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS]
                      .upper().split(",")),
            {"X-Header".upper(), "content-type".upper()})
        self.assertEqual((yield from response.text()), "")

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type,Test",
            }
        )
        self.assertEqual(response.status, 403)
        self.assertNotIn(
            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
            response.headers)
        self.assertIn(
            "headers are not allowed: TEST",
            (yield from response.text()))

Example 27

Project: aiorest Source File: auth.py
def main():
    loop = asyncio.get_event_loop()

    identity_policy = CookieIdentityPolicy()
    auth_policy = DictionaryAuthorizationPolicy({'chris': ('read',)})

    server = aiorest.RESTServer(
        hostname='127.0.0.1', loop=loop,
        identity_policy=identity_policy,
        auth_policy=auth_policy
    )
    server.add_url('GET', '/auth/{permission}', handler)

    srv = loop.run_until_complete(loop.create_server(
        server.make_handler, '127.0.0.1', 8080))

    @asyncio.coroutine
    def query():
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/auth/read',
            cookies={},
            loop=loop)
        json_data = yield from resp.json()
        assert json_data == {'error': 'Identity not found'}

        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/auth/read',
            cookies={'user_id': 'john'},
            loop=loop)
        json_data = yield from resp.json()
        assert json_data == {'error': 'User not found'}

        # correct user, must have read permission
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/auth/read',
            cookies={'user_id': 'chris'},
            loop=loop)
        json_data = yield from resp.json()
        assert json_data == {'allowed': True}

        # correct user, don't have write permission
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/auth/write',
            cookies={'user_id': 'chris'},
            loop=loop)
        json_data = yield from resp.json()
        assert json_data == {'allowed': False}

        print('Success')

    loop.run_until_complete(query())
    srv.close()
    loop.run_until_complete(srv.wait_closed())
    loop.close()

Example 28

Project: aiorest Source File: cors_test.py
    def test_check_origin(self):
        with self.run_server() as url:

            @asyncio.coroutine
            def query():
                resp = yield from aiohttp.request('GET', url + '/check_origin',
                                                  headers={},
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-METHOD', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-HEADERS', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-CREDENTIALS',
                                 resp.headers)

                headers = {
                    'ORIGIN': 'localhost',
                    }
                resp = yield from aiohttp.request('GET', url + '/check_origin',
                                                  headers=headers,
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-METHOD', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-HEADERS', resp.headers)
                self.assertNotIn('ACCESS-CONTROL-ALLOW-CREDENTIALS',
                                 resp.headers)

                headers = {
                    'ORIGIN': 'http://example.com/',
                    }
                resp = yield from aiohttp.request('GET', url + '/check_origin',
                                                  headers=headers,
                                                  loop=self.loop)
                yield from resp.read()
                self.assertEqual(resp.status, 200)
                self.assertIn('ACCESS-CONTROL-ALLOW-ORIGIN', resp.headers)

            self.loop.run_until_complete(query())

Example 29

Project: aiorest Source File: security_test.py
    def test_identity_missing(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
                                           self.server.make_handler,
                                           '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/auth'.format(port)

        def query():
            resp = yield from aiohttp.request(
                'GET', url+'/read',
                cookies={},
                loop=self.loop
            )
            json_data = yield from resp.json()
            self.assertEqual(json_data['error'], 'Identity not found')

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 30

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_multiple_routes_with_one_options_resource(self):
        """Test CORS preflight handling on resource that is available through
        several routes.
        """
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })

        resource = cors.add(app.router.add_resource("/{name}"))
        cors.add(resource.add_route("GET", handler))
        cors.add(resource.add_route("PUT", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url + "user",
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
            }
        )
        self.assertEqual(response.status, 200)

        data = yield from response.text()
        self.assertEqual(data, "")

Example 31

Project: aiorest Source File: security_test.py
    def test_user_missing(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
                                           self.server.make_handler,
                                           '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/auth'.format(port)

        def query():
            resp = yield from aiohttp.request(
                'GET', url+'/read',
                cookies={'user_id': 'john'},  # not chris
                loop=self.loop
            )
            json_data = yield from resp.json()
            self.assertEqual(json_data['error'], 'User not found')

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 32

Project: aiorest Source File: security_test.py
    def test_permission_missing(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
                                           self.server.make_handler,
                                           '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/auth'.format(port)

        def query():
            resp = yield from aiohttp.request(
                'GET', url+'/write',  # not read
                cookies={'user_id': 'chris'},
                loop=self.loop
            )
            json_data = yield from resp.json()
            self.assertEqual(json_data['allowed'], False)

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 33

Project: aiorest Source File: security_test.py
    def test_permission_present(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
                                           self.server.make_handler,
                                           '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/auth'.format(port)

        def query():
            resp = yield from aiohttp.request(
                'GET', url+'/read',
                cookies={'user_id': 'chris'},
                loop=self.loop
            )
            json_data = yield from resp.json()
            self.assertEqual(json_data['allowed'], True)

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 34

Project: aiorest Source File: server_test.py
Function: test_simple_post
    def test_simple_POST(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/post/123'.format(port)

        def query():
            response = yield from aiohttp.request(
                'POST', url,
                data=json.dumps({'q': 'val'}).encode('utf-8'),
                headers={'Content-Type': 'application/json'},
                loop=self.loop)
            self.assertEqual(200, response.status)
            data = yield from response.read()
            self.assertEqual(b'{"success": true}', data)

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 35

Project: hangups Source File: channel.py
    @asyncio.coroutine
    def _longpoll_request(self):
        """Open a long-polling request and receive arrays.

        This method uses keep-alive to make re-opening the request faster, but
        the remote server will set the "Connection: close" header once an hour.

        Raises hangups.NetworkError or UnknownSIDError.
        """
        params = {
            'VER': 8,  # channel protocol version
            'gsessionid': self._gsessionid_param,
            'RID': 'rpc',  # request identifier
            't': 1,  # trial
            'SID': self._sid_param,  # session ID
            'CI': 0,  # 0 if streaming/chunked requests should be used
            'ctype': 'hangouts',  # client type
            'TYPE': 'xmlhttp',  # type of request
        }
        headers = get_authorization_headers(self._cookies['SAPISID'])
        logger.info('Opening new long-polling request')
        try:
            res = yield from asyncio.wait_for(aiohttp.request(
                'get', CHANNEL_URL_PREFIX.format('channel/bind'),
                params=params, cookies=self._cookies, headers=headers,
                connector=self._connector
            ), CONNECT_TIMEOUT)
        except asyncio.TimeoutError:
            raise exceptions.NetworkError('Request timed out')
        except aiohttp.ClientError as e:
            raise exceptions.NetworkError('Request connection error: {}'
                                          .format(e))
        except aiohttp.ServerDisconnectedError as e:
            raise exceptions.NetworkError('Server disconnected error: {}'
                                          .format(e))
        if res.status == 400 and res.reason == 'Unknown SID':
            raise UnknownSIDError('SID became invalid')
        elif res.status != 200:
            raise exceptions.NetworkError(
                'Request return unexpected status: {}: {}'
                .format(res.status, res.reason)
            )
        while True:
            try:
                chunk = yield from asyncio.wait_for(
                    res.content.read(MAX_READ_BYTES), PUSH_TIMEOUT
                )
            except asyncio.TimeoutError:
                raise exceptions.NetworkError('Request timed out')
            except aiohttp.ClientError as e:
                raise exceptions.NetworkError('Request connection error: {}'
                                              .format(e))
            except aiohttp.ServerDisconnectedError as e:
                raise exceptions.NetworkError('Server disconnected error: {}'
                                              .format(e))
            except asyncio.CancelledError:
                # Prevent ResourceWarning when channel is disconnected.
                res.close()
                raise
            if chunk:
                yield from self._on_push_data(chunk)
            else:
                # Close the response to allow the connection to be reused for
                # the next request.
                res.close()
                break

Example 36

Project: aiohttp-jinja2 Source File: test_context_processors.py
@pytest.mark.run_loop
def test_context_processors(create_server, loop):

    @aiohttp_jinja2.template('tmpl.jinja2')
    @asyncio.coroutine
    def func(request):
        return {'bar': 2}

    app, url = yield from create_server(
        middlewares=[
            aiohttp_jinja2.context_processors_middleware])
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         'foo: {{ foo }}, bar: {{ bar }}, path: {{ request.path }}'}))

    app['aiohttp_jinja2_context_processors'] = (
        aiohttp_jinja2.request_processor,
        asyncio.coroutine(
            lambda request: {'foo': 1, 'bar': 'should be overwriten'}),
    )

    app.router.add_route('GET', '/', func)

    resp = yield from aiohttp.request('GET', url, loop=loop)
    assert 200 == resp.status
    txt = yield from resp.text()
    assert 'foo: 1, bar: 2, path: /' == txt

Example 37

Project: aiorest Source File: server_test.py
    def test_GET_with_query_string(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/post/123/2?a=1&b=2'.format(port)

        def query():
            response = yield from aiohttp.request('GET', url, loop=self.loop)
            self.assertEqual(200, response.status)
            data = yield from response.read()
            dct = json.loads(data.decode('utf-8'))
            self.assertEqual({'success': True,
                              'args': ['a', 'b'],
                              }, dct)

        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 38

Project: aiorest Source File: server_test.py
Function: test_get_cookie
    def test_get_cookie(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/get_cookie/'.format(port)

        @asyncio.coroutine
        def query():
            response = yield from aiohttp.request(
                'GET', url,
                cookies={'test_cookie': 'value'},
                loop=self.loop)
            self.assertEqual(200, response.status)
            data = yield from response.read()
            dct = json.loads(data.decode('utf-8'))
            self.assertEqual({'success': True,
                              'cookie': 'value',
                              }, dct)
        self.loop.run_until_complete(query())

        srv.close()
        self.loop.run_until_complete(srv.wait_closed())

Example 39

Project: aiohttp-jinja2 Source File: test_context_processors.py
@pytest.mark.run_loop
def test_context_processors_new_setup_style(create_server, loop):

    @aiohttp_jinja2.template('tmpl.jinja2')
    @asyncio.coroutine
    def func(request):
        return {'bar': 2}

    app, url = yield from create_server()
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.DictLoader(
            {'tmpl.jinja2':
             'foo: {{ foo }}, bar: {{ bar }}, '
             'path: {{ request.path }}'}),
        context_processors=(aiohttp_jinja2.request_processor,
                            asyncio.coroutine(
                                lambda request: {
                                    'foo': 1,
                                    'bar': 'should be overwriten'})))

    app.router.add_route('GET', '/', func)

    resp = yield from aiohttp.request('GET', url, loop=loop)
    assert 200 == resp.status
    txt = yield from resp.text()
    assert 'foo: 1, bar: 2, path: /' == txt

Example 40

Project: aiorest Source File: server_test.py
    def test_accept_encoding__deflate(self):
        srv = self.loop.run_until_complete(self.loop.create_server(
            self.server.make_handler,
            '127.0.0.1', 0))
        self.port = port = server_port(srv)
        url = 'http://127.0.0.1:{}/post/123'.format(port)

        @asyncio.coroutine
        def query():
            response = yield from aiohttp.request(
                'GET', url, headers={'ACCEPT-ENCODING': 'deflate'},
                loop=self.loop)
            self.assertEqual(200, response.status)
            data = yield from response.read()
            dct = json.loads(data.decode('utf-8'))
            self.assertEqual({'success': True}, dct)
            headers = response.message.headers
            enc = headers['CONTENT-ENCODING']
            self.assertEqual('deflate', enc)
        self.loop.run_until_complete(query())

Example 41

Project: asyncio-examples Source File: parallel_http_get.py
@asyncio.coroutine
def download_and_count_word(word, url):
    response = yield from aiohttp.request('GET', url)
    text = yield from response.read()
    return text.decode().count(word)

Example 42

Project: aiohttp-jinja2 Source File: test_jinja_globals.py
@pytest.mark.run_loop
def test_url(create_server, loop):

    @aiohttp_jinja2.template('tmpl.jinja2')
    @asyncio.coroutine
    def index(request):
        return {}

    @asyncio.coroutine
    def other(request):
        return

    app, url = yield from create_server()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('other', parts={'name': 'John_Doe'})}}"}))

    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/user/{name}', other, name='other')

    resp = yield from aiohttp.request('GET', url, loop=loop)
    assert 200 == resp.status
    txt = yield from resp.text()
    assert '/user/John_Doe' == txt

Example 43

Project: meteora Source File: requestor.py
Function: make_request
    @asyncio.coroutine
    def make_request(self, url, request_number):
        response = yield from aiohttp.request('GET', url)
        self.results[request_number] = yield from response.read()

Example 44

Project: hangups Source File: http_utils.py
Function: fetch
@asyncio.coroutine
def fetch(method, url, params=None, headers=None, cookies=None, data=None,
          connector=None):
    """Make an HTTP request.

    If the request times out or a encounters a connection issue, it will be
    retried MAX_RETRIES times before finally raising hangups.NetworkError.

    Returns FetchResponse.
    """
    logger.debug('Sending request %s %s:\n%r', method, url, data)
    error_msg = None
    for retry_num in range(MAX_RETRIES):
        try:
            res = yield from asyncio.wait_for(aiohttp.request(
                method, url, params=params, headers=headers, cookies=cookies,
                data=data, connector=connector
            ), CONNECT_TIMEOUT)
            body = yield from asyncio.wait_for(res.read(), REQUEST_TIMEOUT)
            logger.debug('Received response %d %s:\n%r', res.status,
                         res.reason, body)
        except asyncio.TimeoutError:
            error_msg = 'Request timed out'
        except aiohttp.ClientError as e:
            error_msg = 'Request connection error: {}'.format(e)
        except aiohttp.ServerDisconnectedError as e:
            error_msg = 'Server disconnected error: {}'.format(e)
        else:
            error_msg = None
            break
        logger.info('Request attempt %d failed: %s', retry_num, error_msg)
    if error_msg:
        logger.info('Request failed after %d attempts', MAX_RETRIES)
        raise exceptions.NetworkError(error_msg)
    if res.status > 200 or res.status < 200:
        logger.info('Request returned unexpected status: %d %s', res.status,
                    res.reason)
        raise exceptions.NetworkError(
            'Request return unexpected status: {}: {}'
            .format(res.status, res.reason)
        )
    cookie_dict = {name: morsel.value for name, morsel in res.cookies.items()}
    return FetchResponse(res.status, body, cookie_dict)

Example 45

Project: waterbutler Source File: backup.py
@utils.task
def _push_archive_complete(self, version_id, callback_url, metadata):
    signer = signing.Signer(settings.HMAC_SECRET, settings.HMAC_ALGORITHM)
    with utils.RetryHook(self):
        data = signing.sign_data(
            signer,
            {
                'version': version_id,
                'metadata': metadata,
            },
        )
        future = aiohttp.request(
            'PUT',
            callback_url,
            data=json.dumps(data),
            headers={'Content-Type': 'application/json'},
        )
        loop = asyncio.get_event_loop()
        response = loop.run_until_complete(future)

        if response.status != http.client.OK:
            raise Exception('Failed to report archive completion, got status code {}'.format(response.status))

Example 46

Project: aiohttp-jinja2 Source File: test_simple_renderer.py
    @asyncio.coroutine
    def _create_app_with_template(self, template, func):
        """
        Helper method that creates application with single handler that process
        request to root '/' with any http method and returns response for
        rendered `template`
        """
        app = web.Application(loop=self.loop)
        aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
            'tmpl.jinja2': template
        }))

        app.router.add_route('*', '/', func)

        port = self.find_unused_port()
        handler = app.make_handler()
        srv = yield from self.loop.create_server(
            handler, '127.0.0.1', port)
        url = 'http://127.0.0.1:{}/'.format(port)

        resp = yield from aiohttp.request('GET', url, loop=self.loop)

        yield from handler.finish_connections()
        srv.close()
        self.addCleanup(srv.close)

        return resp

Example 47

Project: aiorest Source File: class_server.py
Function: main
def main():
    loop = asyncio.get_event_loop()

    server = App(hostname='127.0.0.1', loop=loop)

    srv = loop.run_until_complete(loop.create_server(
        server.make_handler, '127.0.0.1', 8080))

    @asyncio.coroutine
    def query():
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/hello-world',
            loop=loop)
        json_data = yield from resp.json()
        print(json_data)

        name = os.environ.get('USER', 'John')
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/hello/{}'.format(name))

        json_data = yield from resp.json()
        print(json_data)

    loop.run_until_complete(query())
    srv.close()
    loop.run_until_complete(srv.wait_closed())
    loop.close()

Example 48

Project: aiorest Source File: hello_world.py
def main():
    loop = asyncio.get_event_loop()

    server = aiorest.RESTServer(hostname='127.0.0.1', loop=loop)
    server.add_url('GET', '/hello-world', handler)
    server.add_url('GET', '/hello/{name}', say_hello)

    srv = loop.run_until_complete(loop.create_server(
        server.make_handler, '127.0.0.1', 8080))

    @asyncio.coroutine
    def query():
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/hello-world',
            loop=loop)
        json_data = yield from resp.json()
        print(json_data)

        name = os.environ.get('USER', 'John')
        resp = yield from aiohttp.request(
            'GET', 'http://127.0.0.1:8080/hello/{}'.format(name))

        json_data = yield from resp.json()
        print(json_data)

    loop.run_until_complete(query())
    srv.close()
    loop.run_until_complete(srv.wait_closed())
    loop.close()

Example 49

Project: pyzmq Source File: _test_asyncio.py
    def test_aiohttp(self):
        try:
            import aiohttp
        except ImportError:
            raise SkipTest("Requires aiohttp")
        from aiohttp import web
        
        zmq.asyncio.install()
        
        @asyncio.coroutine
        def echo(request):
            print(request.path)
            return web.Response(body=str(request).encode('utf8'))
        
        @asyncio.coroutine
        def server(loop):
            app = web.Application(loop=loop)
            app.router.add_route('GET', '/', echo)

            srv = yield from loop.create_server(app.make_handler(),
                                                '127.0.0.1', 8080)
            print("Server started at http://127.0.0.1:8080")
            return srv

        @asyncio.coroutine
        def client():
            push, pull = self.create_bound_pair(zmq.PUSH, zmq.PULL)
            
            res = yield from aiohttp.request('GET', 'http://127.0.0.1:8080/')
            text = yield from res.text()
            yield from push.send(text.encode('utf8'))
            rcvd = yield from pull.recv()
            self.assertEqual(rcvd.decode('utf8'), text)

        loop = asyncio.get_event_loop()
        loop.run_until_complete(server(loop))
        print("servered")
        loop.run_until_complete(client())

Example 50

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_multiple_routes_with_one_options(self):
        """Test CORS preflight handling on resource that is available through
        several routes.
        """
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })

        cors.add(app.router.add_route("GET", "/{name}", handler))
        cors.add(app.router.add_route("PUT", "/{name}", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url + "user",
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
            }
        )
        self.assertEqual(response.status, 200)

        data = yield from response.text()
        self.assertEqual(data, "")
See More Examples - Go to Next Page
Page 1 Selected Page 2