Here are the examples of the python api aiohttp.web.HTTPNotFound taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
25 Examples
3
Example 1
def add_routes(app):
app.router.add_route('GET', '/', make_dummy_handler())
app.router.add_route('GET', '/articles/', make_dummy_handler())
# https://github.com/KeepSafe/aiohttp/pull/362/files#r30354438
def handler1(req):
raise web.HTTPNotFound()
def handler2(req):
pass
app.router.add_route("GET", '/root/resource/', handler1)
app.router.add_route("GET", "/root/resource/{tail:.*}", handler2)
3
Example 2
Project: ircb 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)))
network_id = self.request.match_info['id']
networks = yield from NetworkStore.get(
dict(query={'user_id': user.id, 'id': int(network_id)}))
network = (networks and networks[0]) or None
if network is None:
raise web.HTTPNotFound()
return web.Response(body=self.serialize(network).encode(),
content_type='application/json')
3
Example 3
Project: ircb Source File: network.py
@auth_required
@asyncio.coroutine
def put(self):
network_id = self.request.match_info['id']
username = yield from get_auth(self.request)
data = yield from self.request.post()
user = yield from UserStore.get(
dict(query=('username', username)))
networks = yield from NetworkStore.get(
dict(query={'user_id': user.id, 'id': network_id})
)
if not networks:
raise web.HTTPNotFound()
resp = yield from self._create_or_update(data, username, networks[0])
return resp
3
Example 4
async def poll(self, request):
question_id = request.match_info['question_id']
try:
question, choices = await db.get_question(self.postgres,
question_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
return {
'question': question,
'choices': choices
}
3
Example 5
async def results(self, request):
question_id = request.match_info['question_id']
try:
question, choices = await db.get_question(self.postgres,
question_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
return {
'question': question,
'choices': choices
}
3
Example 6
Project: sockjs Source File: test_route.py
def test_handler_unknown_transport(self):
route = self.make_route()
request = self.make_request(
'GET', '/sm/', match_info={'transport': 'unknown'})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPNotFound)
3
Example 7
Project: sockjs Source File: test_route.py
def test_handler_emptry_session(self):
route = self.make_route()
request = self.make_request(
'GET', '/sm/',
match_info={'transport': 'websocket', 'session': ''})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPNotFound)
3
Example 8
Project: sockjs Source File: test_route.py
def test_handler_bad_session_id(self):
route = self.make_route()
request = self.make_request(
'GET', '/sm/',
match_info={'transport': 'websocket',
'session': 'test.1', 'server': '000'})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPNotFound)
3
Example 9
Project: sockjs Source File: test_route.py
def test_handler_bad_server_id(self):
route = self.make_route()
request = self.make_request(
'GET', '/sm/',
match_info={'transport': 'websocket',
'session': 'test', 'server': 'test.1'})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPNotFound)
3
Example 10
Project: sockjs Source File: test_route.py
def test_new_session_before_read(self):
route = self.make_route()
request = self.make_request(
'GET', '/sm/',
match_info={
'transport': 'xhr_send', 'session': 's1', 'server': '000'})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPNotFound)
3
Example 11
Project: sakia Source File: server.py
async def middleware_factory(self, app, handler):
async def middleware_handler(request):
try:
resp = await handler(request)
return resp
except web.HTTPNotFound:
return web.Response(status=404, body=bytes(json.dumps({"ucode":1001,
"message": "404 error"}),
"utf-8"),
headers={'Content-Type': 'application/json'})
return middleware_handler
3
Example 12
def remove_project(self, project_id):
"""
Removes a Project instance from the list of projects in use.
:param project_id: Project identifier
"""
if project_id not in self._projects:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id))
del self._projects[project_id]
3
Example 13
async def poll(request):
async with request.app['db'].acquire() as conn:
question_id = request.match_info['question_id']
try:
question, choices = await db.get_question(conn,
question_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
return {
'question': question,
'choices': choices
}
3
Example 14
async def results(request):
async with request.app['db'].acquire() as conn:
question_id = request.match_info['question_id']
try:
question, choices = await db.get_question(conn,
question_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
return {
'question': question,
'choices': choices
}
3
Example 15
Project: aiohttp Source File: test_web_exceptions.py
def test_override_body_with_text():
resp = web.HTTPNotFound(text="Page not found")
assert 404 == resp.status
assert "Page not found".encode('utf-8') == resp.body
assert "Page not found" == resp.text
assert "text/plain" == resp.content_type
assert "utf-8" == resp.charset
3
Example 16
Project: aiohttp Source File: test_web_exceptions.py
def test_override_body_with_binary():
txt = "<html><body>Page not found</body></html>"
resp = web.HTTPNotFound(body=txt.encode('utf-8'),
content_type="text/html")
assert 404 == resp.status
assert txt.encode('utf-8') == resp.body
assert txt == resp.text
assert "text/html" == resp.content_type
assert resp.charset is None
3
Example 17
@asyncio.coroutine
def page_handler(request):
# If the visitor gets "/pages/page-one", then page_name is "page-one".
page_name = request.match_info.get('page_name')
# Retrieve the long-lived database handle.
db = request.app['db']
# Find the page by its unique id.
docuement = yield from db.pages.find_one(page_name)
if not docuement:
return web.HTTPNotFound(text='No page named {!r}'.format(page_name))
return web.Response(body=docuement['body'].encode(),
content_type='text/html')
0
Example 18
@asyncio.coroutine
def __call__(self, app, handler):
@asyncio.coroutine
def middleware(request):
try:
return (yield from handler(request))
except web.HTTPNotFound as exc:
if request.method in ('POST', 'PUT', 'PATCH'):
# should check for empty request.content
# actually even GET may have a BODY
raise exc
router = request.app.router
new_path = None
if self.merge_slashes:
if '//' in request.path:
path = request.path
while True:
path = path.replace('//', '/')
if '//' not in path:
break
match_info = yield from resolve2(router, request.method, path)
if not isinstance(match_info.route, SystemRoute):
new_path = path
if self.append_slash:
if not request.path.endswith('/'):
path = request.path + '/'
match_info = yield from resolve2(router, request.method, path)
if not isinstance(match_info.route, SystemRoute):
new_path = path
if new_path is not None:
if request.query_string:
new_path += '?' + request.query_string
return self.redirect_class(new_path)
else:
raise exc
return middleware
0
Example 19
Project: ircb Source File: network.py
@auth_required
@asyncio.coroutine
def put(self):
network_id = self.request.match_info['id']
action = self.request.match_info['action']
if action not in ('connect', 'disconnect'):
raise web.HTTPNotFound()
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, 'id': network_id})
)
if not networks:
raise web.HTTPNotFound()
network = networks[0]
network = yield from NetworkStore.update(
dict(filter=('id', network.id),
update={'status': '0' if action == 'connect' else '2'})
)
return web.Response(body=self.serialize(network).encode(),
content_type='application/json')
0
Example 20
async def user_timeline(self, request):
username = request.match_info['username']
profile_user = await self.mongo.user.find_one({'username': username})
if profile_user is None:
raise web.HTTPNotFound()
followed = False
session = await get_session(request)
user_id = session.get('user_id')
user = None
if user_id:
user = await self.mongo.user.find_one({'_id': ObjectId(user_id)})
followed = await self.mongo.follower.find_one(
{'who_id': ObjectId(session['user_id']),
'whom_id': {'$in': [ObjectId(profile_user['_id'])]}})
followed = followed is not None
messages = await (self.mongo.message
.find({'author_id': ObjectId(profile_user['_id'])})
.sort('pub_date', -1)
.to_list(30))
profile_user['_id'] = str(profile_user['_id'])
return {"messages": messages,
"followed": followed,
"profile_user": profile_user,
"user": user,
"endpoint": request.match_info.route.name}
0
Example 21
Project: sockjs Source File: route.py
@asyncio.coroutine
def handler(self, request):
info = request.match_info
# lookup transport
tid = info['transport']
if tid not in self.handlers or tid in self.disable_transports:
return web.HTTPNotFound()
create, transport = self.handlers[tid]
# session
manager = self.manager
if not manager.started:
manager.start()
sid = info['session']
if not sid or '.' in sid or '.' in info['server']:
return web.HTTPNotFound()
try:
session = manager.get(sid, create, request=request)
except KeyError:
return web.HTTPNotFound(headers=session_cookie(request))
t = transport(manager, session, request)
try:
return (yield from t.process())
except asyncio.CancelledError:
raise
except web.HTTPException as exc:
return exc
except Exception as exc:
log.exception('Exception in transport: %s' % tid)
if manager.is_acquired(session):
yield from manager.release(session)
return web.HTTPInternalServerError()
0
Example 22
Project: sockjs Source File: test_route.py
def test_raw_websocket_fail(self):
route = self.make_route()
request = self.make_request('GET', '/sm/')
res = self.loop.run_until_complete(route.websocket(request))
self.assertFalse(isinstance(res, web.HTTPNotFound))
0
Example 23
Project: gns3-server Source File: test_project_manager.py
def test_project_not_found():
pm = ProjectManager.instance()
with pytest.raises(aiohttp.web.HTTPNotFound):
pm.get_project('00010203-0405-0607-0809-000000000000')
0
Example 24
Project: aioauth-client Source File: app.py
@asyncio.coroutine
def oauth(request):
provider = request.match_info.get('provider')
if provider not in clients:
raise web.HTTPNotFound(reason='Unknown provider')
# Create OAuth1/2 client
Client = clients[provider]['class']
params = clients[provider]['init']
client = Client(**params)
client.params['oauth_callback' if issubclass(Client, OAuth1Client) else 'redirect_uri'] = \
'http://%s%s' % (request.host, request.path)
# Check if is not redirect from provider
if client.shared_key not in request.GET:
# For oauth1 we need more work
if isinstance(client, OAuth1Client):
token, secret, _ = yield from client.get_request_token()
# Dirty save a token_secret
# Dont do it in production
request.app.secret = secret
request.app.token = token
# Redirect client to provider
return web.HTTPFound(client.get_authorize_url())
# For oauth1 we need more work
if isinstance(client, OAuth1Client):
client.oauth_token_secret = request.app.secret
client.oauth_token = request.app.token
yield from client.get_access_token(request.GET)
user, info = yield from client.user_info()
text = (
"<a href='/'>back</a><br/><br/>"
"<ul>"
"<li>ID: %(id)s</li>"
"<li>Username: %(username)s</li>"
"<li>First, last name: %(first_name)s, %(last_name)s</li>"
"<li>Gender: %(gender)s</li>"
"<li>Email: %(email)s</li>"
"<li>Link: %(link)s</li>"
"<li>Picture: %(picture)s</li>"
"<li>Country, city: %(country)s, %(city)s</li>"
"</ul>"
) % user.__dict__
text += "<pre>%s</pre>" % html.escape(pformat(info))
return web.Response(text=text, content_type='text/html')
0
Example 25
def _process(self, request, collection, action, resource_id=None,
success_status_code=200, **kwargs):
payload = {}
request_body = yield from request.text()
if request_body:
try:
request_body = json.loads(request_body)
payload.update(request_body)
except (ValueError, UnicodeDecodeError):
self.logger.warning('Bad body: %s',
request_body,
exc_info=True)
payload.update({'collection_name': collection, 'action': action})
if resource_id:
payload['resource_id'] = resource_id
payload.update(kwargs)
self.logger.info('Payload %s' % payload)
try:
result = yield from self.service.send(**payload)
self.logger.info('Result is %s' % result)
except UnknownService as e:
self.logger.error('Payload error %s' % e)
err_body = json.dumps({'error': str(e)}).encode('utf-8')
raise web.HTTPNotFound(content_type="application/json",
body=err_body)
else:
response_body = json.dumps(result).encode('utf-8')
return web.Response(content_type="application/json",
body=response_body, status=success_status_code)