aiohttp.web.Response

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

147 Examples 7

Example 1

Project: home-assistant
License: View license
Source File: __init__.py
Function: get
    @asyncio.coroutine
    def get(self, request, entity_id):
        """Start a get request."""
        camera = self.entities.get(entity_id)

        if camera is None:
            return web.Response(status=404)

        authenticated = (request.authenticated or
                         request.GET.get('token') == camera.access_token)

        if not authenticated:
            return web.Response(status=401)

        response = yield from self.handle(request, camera)
        return response

Example 2

Project: prometheus_async
License: View license
Source File: web.py
Function: cheap
def _cheap(request):
    """
    A view that links to metrics.

    Useful for cheap health checks.
    """
    return web.Response(body=_REF)

Example 3

@asyncio.coroutine
def test_load_existing_sesssion(test_client):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert not session.new
        assert not session._changed
        assert session.created is not None
        assert {'a': 1, 'b': 2} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler)
    make_cookie(client, {'a': 1, 'b': 2})
    resp = yield from client.get('/')
    assert resp.status == 200

Example 4

Project: sockjs
License: View license
Source File: route.py
    def iframe(self, request):
        cached = request.headers.get(hdrs.IF_NONE_MATCH)
        if cached:
            response = web.Response(status=304)
            response.headers.extend(cache_headers())
            return response

        return web.Response(
            body=self.iframe_html,
            content_type='text/html',
            headers=((hdrs.ETAG, self.iframe_html_hxd),) + cache_headers())

Example 5

@asyncio.coroutine
def test_load_existing_sesssion(test_client, fernet, key):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert not session.new
        assert not session._changed
        assert {'a': 1, 'b': 12} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, key)
    make_cookie(client, fernet, {'a': 1, 'b': 12})
    resp = yield from client.get('/')
    assert resp.status == 200

Example 6

Project: aiohttp-security
License: View license
Source File: test_no_identity.py
@asyncio.coroutine
def test_forget(loop, test_client):

    @asyncio.coroutine
    def do_forget(request):
        response = web.Response()
        yield from forget(request, response)

    app = web.Application(loop=loop)
    app.router.add_route('POST', '/', do_forget)
    client = yield from test_client(app)
    resp = yield from client.post('/')
    assert 500 == resp.status
    assert (('Security subsystem is not initialized, '
             'call aiohttp_security.setup(...) first') ==
            resp.reason)
    yield from resp.release()

Example 7

Project: home-assistant
License: View license
Source File: emulated_hue.py
    @core.callback
    def async_get_light_state(self, entity_id):
        """Process a request to get the state of an individual light."""
        entity = self.hass.states.get(entity_id)
        if entity is None or not self.is_entity_exposed(entity):
            return web.Response(text="Entity not found", status=404)

        cached_state = self.cached_states.get(entity_id, None)

        if cached_state is None:
            final_state = entity.state == STATE_ON
            final_brightness = entity.attributes.get(
                ATTR_BRIGHTNESS, 255 if final_state else 0)
        else:
            final_state, final_brightness = cached_state

        json_response = entity_to_json(entity, final_state, final_brightness)

        return self.json(json_response)

Example 8

Project: aiohttp-security
License: View license
Source File: handlers.py
Function: index
    @asyncio.coroutine
    def index(self, request):
        username = yield from authorized_userid(request)
        if username:
            template = self.index_template.format(
                message='Hello, {username}!'.format(username=username))
        else:
            template = self.index_template.format(message='You need to login')
        response = web.Response(body=template.encode())
        return response

Example 9

Project: snakepit-game
License: View license
Source File: server.py
Function: handle
async def handle(request):
    ALLOWED_FILES = ["index.html", "style.css"]
    name = request.match_info.get('name', 'index.html')
    if name in ALLOWED_FILES:
        try:
            with open(name, 'rb') as index:
                return web.Response(body=index.read(), content_type='text/html')
        except FileNotFoundError:
            pass
    return web.Response(status=404)

Example 10

Project: aiohttp-security
License: View license
Source File: handlers.py
    @require('public')
    @asyncio.coroutine
    def internal_page(self, request):
        response = web.Response(
            body=b'This page is visible for all registered users')
        return response

Example 11

Project: sockjs
License: View license
Source File: route.py
    def info(self, request):
        resp = web.Response(content_type='application/json')
        resp.headers[hdrs.CACHE_CONTROL] = (
            'no-store, no-cache, must-revalidate, max-age=0')
        resp.headers.extend(cors_headers(request.headers))

        info = {'entropy': random.randint(1, 2147483647),
                'websocket': 'websocket' not in self.disable_transports,
                'cookie_needed': self.cookie_needed,
                'origins': ['*:*']}
        resp.text = json.dumps(info)
        return resp

Example 12

@asyncio.coroutine
def test_create_new_sesssion(test_client, secretbox, key):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert session.new
        assert not session._changed
        assert {} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, key)
    resp = yield from client.get('/')
    assert resp.status == 200

Example 13

Project: aiohttp-security
License: View license
Source File: test_no_auth.py
@asyncio.coroutine
def test_permits(loop, test_client):

    @asyncio.coroutine
    def check(request):
        ret = yield from permits(request, 'read')
        assert ret
        ret = yield from permits(request, 'write')
        assert ret
        ret = yield from permits(request, 'unknown')
        assert ret
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', check)
    client = yield from test_client(app)
    resp = yield from client.get('/')
    assert 200 == resp.status
    yield from resp.release()

Example 14

Project: unicode-solutions
License: View license
Source File: http_charfinder.py
Function: home
def home(request):  # <1>
    query = request.GET.get('query', '').strip()  # <2>
    print('Query: {!r}'.format(query))  # <3>
    if query:  # <4>
        descriptions = list(index.find_descriptions(query))
        res = '\n'.join(ROW_TPL.format(**vars(descr))
                        for descr in descriptions)
        msg = index.status(query, len(descriptions))
    else:
        descriptions = []
        res = ''
        msg = 'Enter words describing characters.'

    html = template.format(query=query, result=res,  # <5>
                           message=msg)
    print('Sending {} results'.format(len(descriptions)))  # <6>
    return web.Response(content_type=CONTENT_TYPE, text=html) # <7>

Example 15

Project: dcos
License: View license
Source File: async_server.py
Function: root
def root(request):
    """Return the root endpoint, serve the index.html.

    :param request: a web requeest object.
    :type request: request | None
    """
    log.info("Root page requested.")
    index_file = open(index_path)
    log.info("Serving %s", index_path)
    resp = web.Response(body=index_file.read().encode('utf-8'))
    resp.headers['content-type'] = 'text/html'
    return resp

Example 16

Project: home-assistant
License: View license
Source File: emulated_hue.py
Function: get
    @core.callback
    def get(self, request, username, entity_id=None):
        """Handle a GET request."""
        if entity_id is None:
            return self.async_get_lights_list()

        if not request.path.endswith('state'):
            return self.async_get_light_state(entity_id)

        return web.Response(text="Method not allowed", status=405)

Example 17

@asyncio.coroutine
def test_max_age_also_returns_expires(test_client):

    @asyncio.coroutine
    def handler(request):
        time.monotonic.return_value = 0.0
        session = yield from get_session(request)
        session['c'] = 3
        return web.Response(body=b'OK')

    with mock.patch('time.monotonic') as m_monotonic:
        m_monotonic.return_value = 0.0

        client = yield from test_client(create_app, handler)
        make_cookie(client, {'a': 1, 'b': 2})
        resp = yield from client.get('/')
        assert resp.status == 200
        assert 'expires=Thu, 01-Jan-1970 00:00:10 GMT' in \
               resp.headers['SET-COOKIE']

Example 18

Project: home-assistant
License: View license
Source File: test_api.py
    def test_api_get_error_log(self):
        """Test the return of the error log."""
        test_string = 'Test String°'

        @asyncio.coroutine
        def mock_send():
            """Mock file send."""
            return web.Response(text=test_string)

        with patch('homeassistant.components.http.HomeAssistantView.file',
                   Mock(return_value=mock_send())):
            req = requests.get(_url(const.URL_API_ERROR_LOG),
                               headers=HA_HEADERS)
            self.assertEqual(test_string, req.text)
            self.assertIsNone(req.headers.get('expires'))

Example 19

Project: aiohttp-devtools
License: View license
Source File: serve.py
Function: handle
    async def _handle(self, request):
        self.modify_request(request)
        status, length = 'unknown', ''
        try:
            response = await super()._handle(request)
        except HTTPNotModified:
            status, length = 304, 0
            raise
        except HTTPNotFound:
            _404_msg = '404: Not Found\n\n' + _get_asset_content(self._asset_path)
            response = web.Response(body=_404_msg.encode(), status=404, content_type='text/plain')
            status, length = response.status, response.content_length
        else:
            status, length = response.status, response.content_length
        finally:
            l = logger.info if status in {200, 304} else logger.warning
            l('> %s %s %s %s', request.method, request.path, status, fmt_size(length))
        return response

Example 20

Project: wechatpy
License: View license
Source File: app.py
@asyncio.coroutine
def user_group_id(request):
    resp = Response()
    client = AsyncWeChatClient(APPID, SECRET, timeout=10)
    try:
        group_id = yield from client.user.get_group_id(OPENID)
    except Exception as e:
        print(e)
        resp.body = str(e).encode('utf-8')
    else:
        resp.body = str(group_id).encode('utf-8')
    return resp

Example 21

Project: aiohttp-session
License: View license
Source File: test_cookie_storage.py
@asyncio.coroutine
def test_dont_save_not_requested_session(test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler)
    make_cookie(client, {'a': 1, 'b': 2})
    resp = yield from client.get('/')
    assert resp.status == 200
    assert 'AIOHTTP_SESSION' not in resp.cookies

Example 22

@asyncio.coroutine
def test_create_new_sesssion_broken_by_format(test_client, fernet, key):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert session.new
        assert not session._changed
        assert {} == session
        return web.Response(body=b'OK')

    new_fernet = Fernet(Fernet.generate_key())
    client = yield from test_client(create_app, handler, key)
    make_cookie(client, new_fernet, {'a': 1, 'b': 12})
    resp = yield from client.get('/')
    assert resp.status == 200

Example 23

Project: aiohttp_runserver
License: View license
Source File: serve.py
async def livereload_js(request):
    if request.if_modified_since:
        aux_logger.debug('> %s %s %s 0', request.method, request.path, 304)
        raise HTTPNotModified()

    script_key = 'livereload_script'
    lr_script = request.app.get(script_key)
    if lr_script is None:
        lr_path = Path(__file__).absolute().parent.joinpath('livereload.js')
        with lr_path.open('rb') as f:
            lr_script = f.read()
            request.app[script_key] = lr_script

    aux_logger.debug('> %s %s %s %s', request.method, request.path, 200, fmt_size(len(lr_script)))
    return web.Response(body=lr_script, content_type='application/javascript',
                        headers={LAST_MODIFIED: 'Fri, 01 Jan 2016 00:00:00 GMT'})

Example 24

@asyncio.coroutine
def test_clear_cookie_on_sesssion_invalidation(test_client, fernet, key):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        session.invalidate()
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, key)
    make_cookie(client, fernet, {'a': 1, 'b': 2})
    resp = yield from client.get('/')
    assert resp.status == 200

    morsel = resp.cookies['AIOHTTP_SESSION']
    assert '' == morsel.value
    assert not morsel['httponly']
    assert morsel['path'] == '/'

Example 25

@asyncio.coroutine
def test_remember(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        response = web.Response()
        yield from remember(request, response, 'Andrew')
        return response

    app = web.Application(loop=loop)
    _setup(app, CookiesIdentityPolicy(), Autz())
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.get('/')
    assert 200 == resp.status
    assert 'Andrew' == resp.cookies['AIOHTTP_SECURITY'].value
    yield from resp.release()

Example 26

@asyncio.coroutine
def test_load_existing_sesssion(test_client, redis):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert not session.new
        assert not session._changed
        assert {'a': 1, 'b': 12} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, redis)
    yield from make_cookie(client, redis, {'a': 1, 'b': 12})
    resp = yield from client.get('/')
    assert resp.status == 200

Example 27

@asyncio.coroutine
def test_load_existing_sesssion(test_client, secretbox, key):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert not session.new
        assert not session._changed
        assert {'a': 1, 'b': 12} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, key)
    make_cookie(client, secretbox, {'a': 1, 'b': 12})
    resp = yield from client.get('/')
    assert resp.status == 200

Example 28

Project: aiohttp-security
License: View license
Source File: test_no_auth.py
Function: test_authorized_userid
@asyncio.coroutine
def test_authorized_userid(loop, test_client):

    @asyncio.coroutine
    def check(request):
        userid = yield from authorized_userid(request)
        assert userid is None
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', check)
    client = yield from test_client(app)
    resp = yield from client.get('/')
    assert 200 == resp.status
    yield from resp.release()

Example 29

Project: sockjs
License: View license
Source File: route.py
    def info_options(self, request):
        resp = web.Response(status=204, content_type='application/json')
        resp.headers[hdrs.CACHE_CONTROL] = (
            'no-store, no-cache, must-revalidate, max-age=0')
        resp.headers[hdrs.ACCESS_CONTROL_ALLOW_METHODS] = 'OPTIONS, GET'
        resp.headers.extend(cors_headers(request.headers))
        resp.headers.extend(cache_headers())
        resp.headers.extend(session_cookie(request))
        return resp

Example 30

Project: ircb
License: View license
Source File: user.py
    @asyncio.coroutine
    def post(self):
        data = yield from self.request.post()
        user = yield from UserStore.get(
            dict(query=('auth', (data.get('username'), data.get('password'))))
        )
        if user:
            yield from auth.remember(self.request, user.username)
            return web.Response(body=b'OK')
        raise web.HTTPForbidden()

Example 31

Project: sakia
License: View license
Source File: server.py
Function: handler
    async def _handler(self, request, data_dict, http_code):
        await request.read()
        self.requests.append(Request(request.method, request.path, request.content))
        return web.Response(body=bytes(json.dumps(data_dict), "utf-8"),
                            headers={'Content-Type': 'application/json'},
                            status=http_code)

Example 32

Project: aiohttp-security
License: View license
Source File: test_no_identity.py
@asyncio.coroutine
def test_remember(loop, test_client):

    @asyncio.coroutine
    def do_remember(request):
        response = web.Response()
        yield from remember(request, response, 'Andrew')

    app = web.Application(loop=loop)
    app.router.add_route('POST', '/', do_remember)
    client = yield from test_client(app)
    resp = yield from client.post('/')
    assert 500 == resp.status
    assert (('Security subsystem is not initialized, '
             'call aiohttp_security.setup(...) first') ==
            resp.reason)
    yield from resp.release()

Example 33

Project: concorrente.py
License: View license
Source File: http_charfinder.py
Function: handle
@asyncio.coroutine
def handle(request):
    query = request.GET.get('query', '')
    print('Query: {!r}'.format(query))
    if query:
        lines = list(index.find_descriptions(query))
        res = '\n'.join(lines)
        msg = index.status(query, len(lines))
    else:
        lines = []
        res = ''
        msg = 'Type words describing characters.'

    links = ', '.join(LINK_TPL.format(word)
                      for word in sorted(EXAMPLE_WORDS, key=str.upper))
    text = PAGE_TPL.format(query=query, result=res,
                           message=msg, links=links)
    print('Sending {} results'.format(len(lines)))
    return web.Response(content_type=CONTENT_TYPE, text=text)

Example 34

Project: aiohttp-devtools
License: View license
Source File: serve.py
async def livereload_js(request):
    if request.if_modified_since:
        logger.debug('> %s %s %s 0B', request.method, request.path, 304)
        raise HTTPNotModified()

    script_key = 'livereload_script'
    lr_script = request.app.get(script_key)
    if lr_script is None:
        lr_path = Path(__file__).absolute().parent.joinpath('livereload.js')
        with lr_path.open('rb') as f:
            lr_script = f.read()
            request.app[script_key] = lr_script

    logger.debug('> %s %s %s %s', request.method, request.path, 200, fmt_size(len(lr_script)))
    return web.Response(body=lr_script, content_type='application/javascript',
                        headers={LAST_MODIFIED: 'Fri, 01 Jan 2016 00:00:00 GMT'})

Example 35

Project: home-assistant
License: View license
Source File: __init__.py
Function: handle
    @asyncio.coroutine
    def handle(self, request, camera):
        """Serve camera image."""
        image = yield from camera.async_camera_image()

        if image is None:
            return web.Response(status=500)

        return web.Response(body=image)

Example 36

Project: aiohttp-session
License: View license
Source File: main.py
Function: handler
@asyncio.coroutine
def handler(request):
    session = yield from get_session(request)
    last_visit = session['last_visit'] if 'last_visit' in session else None
    session['last_visit'] = time.time()
    text = 'Last visited: {}'.format(last_visit)
    return web.Response(body=text.encode('utf-8'))

Example 37

Project: home-assistant
License: View license
Source File: emulated_hue.py
Function: put
    @asyncio.coroutine
    def put(self, request, username, entity_id=None):
        """Handle a PUT request."""
        if not request.path.endswith('state'):
            return web.Response(text="Method not allowed", status=405)

        if entity_id and self.hass.states.get(entity_id) is None:
            return self.json_message('Entity not found', HTTP_NOT_FOUND)

        try:
            json_data = yield from request.json()
        except ValueError:
            return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)

        result = yield from self.async_put_light_state(json_data, entity_id)
        return result

Example 38

Project: aiohttp-jinja2
License: View license
Source File: __init__.py
Function: render_template
def render_template(template_name, request, context, *,
                    app_key=APP_KEY, encoding='utf-8'):
    response = web.Response()
    if context is None:
        context = {}
    text = render_string(template_name, request, context, app_key=app_key)
    response.content_type = 'text/html'
    response.charset = encoding
    response.text = text
    return response

Example 39

Project: home-assistant
License: View license
Source File: http.py
Function: json
    def json(self, result, status_code=200):
        """Return a JSON response."""
        msg = json.dumps(
            result, sort_keys=True, cls=rem.JSONEncoder).encode('UTF-8')
        return web.Response(
            body=msg, content_type=CONTENT_TYPE_JSON, status=status_code)

Example 40

@asyncio.coroutine
def test_create_new_sesssion(test_client):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert session.new
        assert not session._changed
        assert {} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler)
    resp = yield from client.get('/')
    assert resp.status == 200

Example 41

Project: prometheus_async
License: View license
Source File: web.py
Function: server_stats
@_needs_aiohttp
def server_stats(request):
    """
    Return a web response with the plain text version of the metrics.

    :rtype: :class:`aiohttp.web.Response`
    """
    rsp = web.Response(body=generate_latest(core.REGISTRY))
    rsp.content_type = CONTENT_TYPE_LATEST
    return rsp

Example 42

Project: rororo
License: View license
Source File: test_schemas.py
    def test_schema_custom_response_factory(self):
        schema = Schema(schemas.index, response_factory=json_response_factory)
        schema.validate_request({'name': TEST_NAME})
        response = schema.make_response({'name': TEST_NAME,
                                         'time': time.time()})
        self.assertIsInstance(response, web.Response)
        self.assertEqual(response.content_type, 'application/json')

Example 43

Project: wechatpy
License: View license
Source File: app.py
Function: user_info
@asyncio.coroutine
def user_info(request):
    resp = Response()
    client = AsyncWeChatClient(APPID, SECRET)
    try:
        user = yield from client.user.get(OPENID)
    except Exception as e:
        print(e)
        resp.body = str(e).encode('utf-8')
    else:
        resp.body = json.dumps(user).encode('utf-8')
    return resp

Example 44

@asyncio.coroutine
def test_clear_cookie_on_sesssion_invalidation(test_client):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        session.invalidate()
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler)
    make_cookie(client, {'a': 1, 'b': 2})
    resp = yield from client.get('/')
    assert resp.status == 200
    assert ('Set-Cookie: AIOHTTP_SESSION="{}"; '
            'domain=127.0.0.1; httponly; Path=/'.upper()) == \
        resp.cookies['AIOHTTP_SESSION'].output().upper()

Example 45

Project: aiohttp-security
License: View license
Source File: handlers.py
    @require('public')
    @asyncio.coroutine
    def logout(self, request):
        response = web.Response(body=b'You have been logged out')
        yield from forget(request, response)
        return response

Example 46

Project: rororo
License: View license
Source File: test_schemas.py
    def test_schema_custom_response_class(self):
        schema = Schema(schemas.project_page, response_factory=web.Response)
        schema.validate_request({'project_id': 1})
        response = schema.make_response(status=204)
        self.assertIsInstance(response, web.Response)
        self.assertEqual(response.status, 204)

Example 47

Project: rororo
License: View license
Source File: test_schemas.py
    def test_schema_custom_response_factory_empty_response(self):
        schema = Schema(schemas.project_page,
                        response_factory=json_response_factory)
        schema.validate_request({'project_id': 1})
        response = schema.make_response({})
        self.assertIsInstance(response, web.Response)
        self.assertEqual(response.content_type, 'application/json')

Example 48

Project: ircb
License: View license
Source File: network.py
    @auth_required
    @asyncio.coroutine
    def get(self):
        username = yield from get_auth(self.request)
        user = yield from UserStore.get(
            dict(query=('username', username)))
        networks = yield from NetworkStore.get(
            dict(query={'user_id': user.id})) or []
        return web.Response(body=self.serialize(networks).encode(),
                            content_type='application/json')

Example 49

Project: aiohttp-security
License: View license
Source File: test_dict_autz.py
@asyncio.coroutine
def test_authorized_userid_not_authorized(loop, test_client):

    @asyncio.coroutine
    def check(request):
        userid = yield from authorized_userid(request)
        assert userid is None
        return web.Response()

    app = web.Application(loop=loop)
    _setup(app, CookiesIdentityPolicy(), Autz())
    app.router.add_route('GET', '/', check)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    yield from resp.release()

Example 50

@asyncio.coroutine
def test_create_new_sesssion(test_client, redis):

    @asyncio.coroutine
    def handler(request):
        session = yield from get_session(request)
        assert isinstance(session, Session)
        assert session.new
        assert not session._changed
        assert {} == session
        return web.Response(body=b'OK')

    client = yield from test_client(create_app, handler, redis)
    resp = yield from client.get('/')
    assert resp.status == 200
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3