Here are the examples of the python api aiohttp.web.HTTPBadRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
17 Examples
4
Example 1
async def vote(self, request):
question_id = int(request.match_info['question_id'])
data = await request.post()
try:
choice_id = int(data['choice'])
except (KeyError, TypeError, ValueError) as e:
raise web.HTTPBadRequest(
text='You have not specified choice value') from e
try:
await db.vote(self.postgres, question_id, choice_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
router = request.app.router
url = router['results'].url(parts={'question_id': question_id})
return web.HTTPFound(location=url)
3
Example 2
def get_project(self, project_id):
"""
Returns a Project instance.
:param project_id: Project identifier
:returns: Project instance
"""
try:
UUID(project_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="Project ID {} is not a valid UUID".format(project_id))
if project_id not in self._projects:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id))
return self._projects[project_id]
3
Example 3
async def vote(request):
async with request.app['db'].acquire() as conn:
question_id = int(request.match_info['question_id'])
data = await request.post()
try:
choice_id = int(data['choice'])
except (KeyError, TypeError, ValueError) as e:
raise web.HTTPBadRequest(
text='You have not specified choice value') from e
try:
await db.vote(conn, question_id, choice_id)
except db.RecordNotFound as e:
raise web.HTTPNotFound(text=str(e))
router = request.app.router
url = router['results'].url(parts={'question_id': question_id})
return web.HTTPFound(location=url)
3
Example 4
@asyncio.coroutine
def user_info(self, loop=None, **kwargs):
"""Load user information from provider."""
if not self.user_info_url:
raise NotImplementedError('The provider doesnt support user_info method.')
response = yield from self.request('GET', self.user_info_url, loop=loop, **kwargs)
if response.status / 100 > 2:
raise web.HTTPBadRequest(reason='Failed to obtain User information. '
'HTTP status code: %s' % response.status)
data = (yield from response.json())
user = User(**dict(self.user_parse(data)))
return user, data
3
Example 5
Project: aioauth-client
License: View license
Source File: aioauth_client.py
Function: get_request_token
License: View license
Source File: aioauth_client.py
Function: get_request_token
@asyncio.coroutine
def get_request_token(self, loop=None, **params):
"""Get a request_token and request_token_secret from OAuth1 provider."""
params = dict(self.params, **params)
response = yield from self.request('GET', self.request_token_url, params=params, loop=loop)
if response.status / 100 > 2:
raise web.HTTPBadRequest(
reason='Failed to obtain OAuth 1.0 request token. HTTP status code: %s'
% response.status)
data = yield from response.text()
data = dict(parse_qsl(data))
response.close()
self.oauth_token = data.get('oauth_token')
self.oauth_token_secret = data.get('oauth_token_secret')
return self.oauth_token, self.oauth_token_secret, data
2
Example 6
@asyncio.coroutine
def world_image(self, request):
""" 显示正确的镇守府图片。
舰娘游戏中客户端FLASH请求的镇守府图片是根据FLASH本身的URL生成的,需要根据用户所在的镇守府IP为其显示正确的图片。
:param request: aiohttp.web.Request
:return: aiohttp.web.HTTPFound or aiohttp.web.HTTPBadRequest
"""
size = request.match_info['size']
session = yield from get_session(request)
world_ip = session['world_ip']
if world_ip:
ip_sections = map(int, world_ip.split('.'))
image_name = '_'.join([format(x, '03') for x in ip_sections]) + '_' + size
if image_name in self.worlds:
body = self.worlds[image_name]
else:
url = 'http://203.104.209.102/kcs/resources/image/world/' + image_name + '.png'
coro = aiohttp.get(url, connector=self.connector)
try:
response = yield from asyncio.wait_for(coro, timeout=5)
except asyncio.TimeoutError:
return aiohttp.web.HTTPBadRequest()
body = yield from response.read()
self.worlds[image_name] = body
return aiohttp.web.Response(body=body, headers={'Content-Type': 'image/png', 'Cache-Control': 'no-cache'})
else:
return aiohttp.web.HTTPBadRequest()
0
Example 7
def get_vm(self, vm_id, project_id=None):
"""
Returns a VM instance.
:param vm_id: VM identifier
:param project_id: Project identifier
:returns: VM instance
"""
if project_id:
# check the project_id exists
project = ProjectManager.instance().get_project(project_id)
try:
UUID(vm_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="VM ID {} is not a valid UUID".format(vm_id))
if vm_id not in self._vms:
raise aiohttp.web.HTTPNotFound(text="VM ID {} doesn't exist".format(vm_id))
vm = self._vms[vm_id]
if project_id:
if vm.project.id != project.id:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't belong to VM {}".format(project_id, vm.name))
return vm
0
Example 8
def get_device(self, device_id, project_id=None):
"""
Returns a device instance.
:param device_id: Device identifier
:param project_id: Project identifier
:returns: Device instance
"""
if project_id:
# check the project_id exists
project = ProjectManager.instance().get_project(project_id)
try:
UUID(device_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="Device ID} is not a valid UUID".format(device_id))
if device_id not in self._devices:
raise aiohttp.web.HTTPNotFound(text="Device ID {} doesn't exist".format(device_id))
device = self._devices[device_id]
if project_id:
if device.project.id != project.id:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't belong to device {}".format(project_id, device.name))
return device
0
Example 9
def __init__(self, name=None, project_id=None, path=None, location=None, temporary=False):
self._name = name
if project_id is None:
self._id = str(uuid4())
else:
try:
UUID(project_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="{} is not a valid UUID".format(project_id))
self._id = project_id
self._location = None
if location is None:
self._location = self._config().get("project_directory", self._get_default_project_directory())
else:
self.location = location
self._vms = set()
self._vms_to_destroy = set()
self.temporary = temporary
self._used_tcp_ports = set()
self._used_udp_ports = set()
# clients listening for notifications
self._listeners = set()
if path is None:
path = os.path.join(self._location, self._id)
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
self.path = path
log.info("Project {id} with path '{path}' created".format(path=self._path, id=self._id))
0
Example 10
def json(self, answer):
"""
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
"""
self.content_type = "application/json"
if hasattr(answer, '__json__'):
answer = answer.__json__()
elif isinstance(answer, list):
newanswer = []
for elem in answer:
if hasattr(elem, '__json__'):
elem = elem.__json__()
newanswer.append(elem)
answer = newanswer
if self._output_schema is not None:
try:
jsonschema.validate(answer, self._output_schema)
except jsonschema.ValidationError as e:
log.error("Invalid output query. JSON schema error: {}".format(e.message))
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))
self.body = json.dumps(answer, indent=4, sort_keys=True).encode('utf-8')
0
Example 11
@asyncio.coroutine
def parse_request(request, input_schema, raw):
"""Parse body of request and raise HTTP errors in case of problems"""
content_length = request.content_length
if content_length is not None and content_length > 0 and not raw:
body = yield from request.read()
try:
request.json = json.loads(body.decode('utf-8'))
except ValueError as e:
request.json = {"malformed_json": body.decode('utf-8')}
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))
else:
request.json = {}
# Parse the query string
if len(request.query_string) > 0:
for (k, v) in urllib.parse.parse_qs(request.query_string).items():
request.json[k] = v[0]
if input_schema:
try:
jsonschema.validate(request.json, input_schema)
except jsonschema.ValidationError as e:
log.error("Invalid input query. JSON schema error: {}".format(e.message))
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
e.message,
json.dumps(e.schema)))
return request
0
Example 12
@classmethod
def _route(cls, method, path, *args, **kw):
# This block is executed only the first time
output_schema = kw.get("output", {})
input_schema = kw.get("input", {})
api_version = kw.get("api_version", 1)
raw = kw.get("raw", False)
# If it's a JSON api endpoint just register the endpoint an do nothing
if api_version is None:
cls._path = path
else:
cls._path = "/v{version}{path}".format(path=path, version=api_version)
def register(func):
route = cls._path
handler = func.__module__.replace("_handler", "").replace("gns3server.handlers.api.", "")
cls._docuementation.setdefault(handler, {})
cls._docuementation[handler].setdefault(route, {"api_version": api_version,
"methods": []})
cls._docuementation[handler][route]["methods"].append({
"method": method,
"status_codes": kw.get("status_codes", {200: "OK"}),
"parameters": kw.get("parameters", {}),
"output_schema": output_schema,
"input_schema": input_schema,
"description": kw.get("description", ""),
})
func = asyncio.coroutine(func)
@asyncio.coroutine
def control_schema(request):
# This block is executed at each method call
server_config = Config.instance().get_section_config("Server")
# Authenticate
response = cls.authenticate(request, route, server_config)
if response:
return response
# Non API call
if api_version is None or raw is True:
response = Response(request=request, route=route, output_schema=output_schema)
request = yield from parse_request(request, None, raw)
yield from func(request, response)
return response
# API call
try:
request = yield from parse_request(request, input_schema, raw)
record_file = server_config.get("record")
if record_file:
try:
with open(record_file, "a", encoding="utf-8") as f:
f.write("curl -X {} 'http://{}{}' -d '{}'".format(request.method, request.host, request.path_qs, json.dumps(request.json)))
f.write("\n")
except OSError as e:
log.warn("Could not write to the record file {}: {}".format(record_file, e))
response = Response(request=request, route=route, output_schema=output_schema)
yield from func(request, response)
except aiohttp.web.HTTPBadRequest as e:
response = Response(request=request, route=route)
response.set_status(e.status)
response.json({"message": e.text, "status": e.status, "path": route, "request": request.json, "method": request.method})
except aiohttp.web.HTTPException as e:
response = Response(request=request, route=route)
response.set_status(e.status)
response.json({"message": e.text, "status": e.status})
except (VMError, UbridgeError) as e:
log.error("VM error detected: {type}".format(type=type(e)), exc_info=1)
response = Response(request=request, route=route)
response.set_status(409)
response.json({"message": str(e), "status": 409})
except asyncio.futures.CancelledError as e:
log.error("Request canceled")
response = Response(request=request, route=route)
response.set_status(408)
response.json({"message": "Request canceled", "status": 408})
except aiohttp.ClientDisconnectedError:
log.warn("Client disconnected")
response = Response(request=request, route=route)
response.set_status(408)
response.json({"message": "Client disconnected", "status": 408})
except ConnectionResetError:
log.error("Client connection reset")
response = Response(request=request, route=route)
response.set_status(408)
response.json({"message": "Connection reset", "status": 408})
except Exception as e:
log.error("Uncaught exception detected: {type}".format(type=type(e)), exc_info=1)
response = Response(request=request, route=route)
response.set_status(500)
CrashReport.instance().capture_exception(request)
exc_type, exc_value, exc_tb = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_tb)
if api_version is not None:
tb = "".join(lines)
response.json({"message": tb, "status": 500})
else:
tb = "\n".join(lines)
response.html("<h1>Internal error</h1><pre>{}</pre>".format(tb))
return response
@asyncio.coroutine
def vm_concurrency(request):
"""
To avoid strange effect we prevent concurrency
between the same instance of the vm
"""
if "vm_id" in request.match_info or "device_id" in request.match_info:
vm_id = request.match_info.get("vm_id")
if vm_id is None:
vm_id = request.match_info["device_id"]
cls._vm_locks.setdefault(vm_id, {"lock": asyncio.Lock(), "concurrency": 0})
cls._vm_locks[vm_id]["concurrency"] += 1
with (yield from cls._vm_locks[vm_id]["lock"]):
response = yield from control_schema(request)
cls._vm_locks[vm_id]["concurrency"] -= 1
# No more waiting requests, garbage collect the lock
if cls._vm_locks[vm_id]["concurrency"] <= 0:
del cls._vm_locks[vm_id]
else:
response = yield from control_schema(request)
return response
cls._routes.append((method, cls._path, vm_concurrency))
return vm_concurrency
return register
0
Example 13
Project: aioauth-client
License: View license
Source File: aioauth_client.py
Function: get_access_token
License: View license
Source File: aioauth_client.py
Function: get_access_token
@asyncio.coroutine
def get_access_token(self, oauth_verifier, request_token=None, loop=None, **params):
"""Get access_token from OAuth1 provider.
:returns: (access_token, access_token_secret, provider_data)
"""
# Possibility to provide REQUEST DATA to the method
if not isinstance(oauth_verifier, str) and self.shared_key in oauth_verifier:
oauth_verifier = oauth_verifier[self.shared_key]
if request_token and self.oauth_token != request_token:
raise web.HTTPBadRequest(
reason='Failed to obtain OAuth 1.0 access token. Request token is invalid')
response = yield from self.request('POST', self.access_token_url, params={
'oauth_verifier': oauth_verifier, 'oauth_token': request_token}, loop=loop)
if response.status / 100 > 2:
raise web.HTTPBadRequest(
reason='Failed to obtain OAuth 1.0 access token. HTTP status code: %s'
% response.status)
data = yield from response.text()
data = dict(parse_qsl(data))
response.close()
self.oauth_token = data.get('oauth_token')
self.oauth_token_secret = data.get('oauth_token_secret')
return self.oauth_token, self.oauth_token_secret, data
0
Example 14
Project: aioauth-client
License: View license
Source File: aioauth_client.py
Function: get_access_token
License: View license
Source File: aioauth_client.py
Function: get_access_token
@asyncio.coroutine
def get_access_token(self, code, loop=None, redirect_uri=None, **payload):
"""Get an access_token from OAuth provider.
:returns: (access_token, provider_data)
"""
# Possibility to provide REQUEST DATA to the method
if not isinstance(code, str) and self.shared_key in code:
code = code[self.shared_key]
payload.setdefault('grant_type', 'authorization_code')
payload.update({
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
})
redirect_uri = redirect_uri or self.params.get('redirect_uri')
if redirect_uri:
payload['redirect_uri'] = redirect_uri
response = yield from self.request('POST', self.access_token_url, data=payload, loop=loop)
if 'json' in response.headers.get('CONTENT-TYPE'):
data = yield from response.json()
else:
data = yield from response.text()
data = dict(parse_qsl(data))
try:
self.access_token = data['access_token']
except Exception:
raise web.HTTPBadRequest(reason='Failed to obtain OAuth access token.')
finally:
response.close()
return self.access_token, data
0
Example 15
async def data_factory(app, handler):
async def parse_data(request):
logging.info('data_factory...')
if request.method in ('POST', 'PUT'):
if not request.content_type:
return web.HTTPBadRequest(text='Missing Content-Type.')
content_type = request.content_type.lower()
if content_type.startswith('application/json'):
request.__data__ = await request.json()
if not isinstance(request.__data__, dict):
return web.HTTPBadRequest(text='JSON body must be object.')
logging.info('request json: %s' % request.__data__)
elif content_type.startswith(('application/x-www-form-urlencoded', 'multipart/form-data')):
params = await request.post()
request.__data__ = dict(**params)
logging.info('request form: %s' % request.__data__)
else:
return web.HTTPBadRequest(text='Unsupported Content-Type: %s' % content_type)
elif request.method == 'GET':
qs = request.query_string
request.__data__ = {k: v[0] for k, v in parse.parse_qs(qs, True).items()}
logging.info('request query: %s' % request.__data__)
else:
request.__data__ = dict()
return await handler(request)
return parse_data
0
Example 16
async def __call__(self, request): # 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用
# 获取函数的参数表
required_args = inspect.signature(self._func).parameters
logging.info('required args: %s' % required_args)
# 获取从GET或POST传进来的参数值,如果函数参数表有这参数名就加入
kw = {arg: value for arg, value in request.__data__.items() if arg in required_args}
# 获取match_info的参数值,例如@get('/blog/{id}')之类的参数值
kw.update(request.match_info)
# 如果有request参数的话也加入
if 'request' in required_args:
kw['request'] = request
# 检查参数表中有没参数缺失
for key, arg in required_args.items():
# request参数不能为可变长参数
if key == 'request' and arg.kind in (arg.VAR_POSITIONAL, arg.VAR_KEYWORD):
return web.HTTPBadRequest(text='request parameter cannot be the var argument.')
# 如果参数类型不是变长列表和变长字典,变长参数是可缺省的
if arg.kind not in (arg.VAR_POSITIONAL, arg.VAR_KEYWORD):
# 如果还是没有默认值,而且还没有传值的话就报错
if arg.default == arg.empty and arg.name not in kw:
return web.HTTPBadRequest(text='Missing argument: %s' % arg.name)
logging.info('call with args: %s' % kw)
try:
return await self._func(**kw)
except APIError as e:
return dict(error=e.error, data=e.data, message=e.message)
0
Example 17
def get_last_events(self, request):
try:
last_event_id = int(request.headers.get('Last-Event-Id', request.GET.get('last-event-id')))
except (ValueError, TypeError):
last_event_id = None
interval = request.GET.get('interval')
if interval is not None and last_event_id is None:
last_event_id = 0
if last_event_id is not None:
events = self.metadata.tables['events']
query = sqlalchemy.select([
events.c.id, events.c.event, events.c.data, events.c.time
])
query = query.where(events.c.id > last_event_id)
if interval is not None:
query = query.where(events.c.time > sqlalchemy.func.current_timestamp() - sqlalchemy.cast(interval, sqlalchemy.Interval))
query = query.order_by(events.c.id)
try:
with self.engine.begin() as conn:
return [
{'id': id, 'event': event, 'data': dict(data, time=time.isoformat())}
for id, event, data, time in conn.execute(query)
]
except sqlalchemy.exc.DataError as e:
raise aiohttp.web.HTTPBadRequest from e
return []