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
3
Example 1
@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
3
Example 2
def _cheap(request):
"""
A view that links to metrics.
Useful for cheap health checks.
"""
return web.Response(body=_REF)
3
Example 3
Project: aiohttp-session
License: View license
Source File: test_cookie_storage.py
Function: test_load_existing_sesssion
License: View license
Source File: test_cookie_storage.py
Function: test_load_existing_sesssion
@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
3
Example 4
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())
3
Example 5
Project: aiohttp-session
License: View license
Source File: test_encrypted_cookie_storage.py
Function: test_load_existing_sesssion
License: View license
Source File: test_encrypted_cookie_storage.py
Function: test_load_existing_sesssion
@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
3
Example 6
@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()
3
Example 7
@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)
3
Example 8
@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
3
Example 9
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)
3
Example 10
@require('public')
@asyncio.coroutine
def internal_page(self, request):
response = web.Response(
body=b'This page is visible for all registered users')
return response
3
Example 11
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
3
Example 12
Project: aiohttp-session
License: View license
Source File: test_nacl_storage.py
Function: test_create_new_sesssion
License: View license
Source File: test_nacl_storage.py
Function: test_create_new_sesssion
@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
3
Example 13
@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()
3
Example 14
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>
3
Example 15
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
3
Example 16
@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)
3
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']
3
Example 18
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'))
3
Example 19
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
3
Example 20
@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
3
Example 21
@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
3
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
3
Example 23
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'})
3
Example 24
Project: aiohttp-session
License: View license
Source File: test_encrypted_cookie_storage.py
Function: test_clear_cookie_on_sesssion_invalidation
License: View license
Source File: test_encrypted_cookie_storage.py
Function: test_clear_cookie_on_sesssion_invalidation
@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'] == '/'
3
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()
3
Example 26
Project: aiohttp-session
License: View license
Source File: test_redis_storage.py
Function: test_load_existing_sesssion
License: View license
Source File: test_redis_storage.py
Function: test_load_existing_sesssion
@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
3
Example 27
Project: aiohttp-session
License: View license
Source File: test_nacl_storage.py
Function: test_load_existing_sesssion
License: View license
Source File: test_nacl_storage.py
Function: test_load_existing_sesssion
@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
3
Example 28
Project: aiohttp-security
License: View license
Source File: test_no_auth.py
Function: test_authorized_userid
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()
3
Example 29
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
3
Example 30
@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()
3
Example 31
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)
3
Example 32
@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()
3
Example 33
@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)
3
Example 34
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'})
3
Example 35
@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)
3
Example 36
@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'))
3
Example 37
@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
3
Example 38
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
3
Example 39
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)
3
Example 40
Project: aiohttp-session
License: View license
Source File: test_cookie_storage.py
Function: test_create_new_sesssion
License: View license
Source File: test_cookie_storage.py
Function: test_create_new_sesssion
@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
3
Example 41
@_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
3
Example 42
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')
3
Example 43
@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
3
Example 44
Project: aiohttp-session
License: View license
Source File: test_cookie_storage.py
Function: test_clear_cookie_on_sesssion_invalidation
License: View license
Source File: test_cookie_storage.py
Function: test_clear_cookie_on_sesssion_invalidation
@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()
3
Example 45
@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
3
Example 46
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)
3
Example 47
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')
3
Example 48
@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')
3
Example 49
@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()
3
Example 50
Project: aiohttp-session
License: View license
Source File: test_redis_storage.py
Function: test_create_new_sesssion
License: View license
Source File: test_redis_storage.py
Function: test_create_new_sesssion
@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