def __iter__(self): if self._prefix: methods = self._methods else: for postfix in self._postfixes: if self.request.path.endswith(postfix): break else: raise web.HTTPMethodNotAllowed(self.request.method, ()) methods = self._methods[postfix] if self.request.method not in methods: raise web.HTTPMethodNotAllowed(self.request.method, tuple(methods)) method_name = methods[self.request.method.upper()] method = getattr(self, method_name) params = inspect.signature(method).parameters kwargs = {} if 'request' in params: kwargs['request'] = self.request for k in params: if k in self.request.match_info: kwargs[k] = self.request.match_info[k] resp = yield from method(**kwargs) return resp
async def __call__(self, path_list: List[str], method: Method, ctx: Context) -> web.Response: # If the remaining path list is empty then we must want this route! if path_list == []: if self.handlers[method]: # let's get our result from our handler return await self.handlers[method](ctx) # uh oh! we don't have a handler for this method if self.has_handlers: allowed_methods = list( map( lambda x: x.value, filter(lambda x: self.handlers[x] is not None, self.handlers))) raise web.HTTPMethodNotAllowed(allowed_methods=allowed_methods, method=method.value) raise web.HTTPNotFound() # The path list isn't empty so the next section sould # be a child right? for child in self.children: if path_list[0] == child.path: # Hey the path matches! let's get the result from the child. return await child(path_list[1:], method, ctx) # There wasn't a matching path? well is there a child we have that's # variable? if self.variable_child: # Let's update the url_data parameter with this path. ctx.url_data[self.variable_child.path] = path_list[0] return await self.variable_child(path_list[1:], method, ctx) # Wait there isn't a variable child either? Then what is the client # requesting? LOGGER.info('Nowhere found for: %s', path_list) raise web.HTTPNotFound()
def abort(code): if code == 400: return web.HTTPBadRequest() elif code == 401: return web.HTTPUnauthorized() elif code == 402: return web.HTTPPaymentRequired() elif code == 403: return web.HTTPForbidden() elif code == 404: return web.HTTPNotFound() elif code == 405: return web.HTTPMethodNotAllowed() elif code == 406: return web.HTTPNotAcceptable() elif code == 407: return web.HTTPProxyAuthenticationRequired() elif code == 408: return web.HTTPRequestTimeout() elif code == 409: return web.HTTPConflict() elif code == 410: return web.HTTPGone() elif code == 411: return web.HTTPLengthRequired() elif code == 412: return web.HTTPPreconditionFailed() elif code == 413: return web.HTTPRequestEntityTooLarge() elif code == 414: return web.HTTPRequestURITooLong() elif code == 415: return web.HTTPUnsupportedMediaType() elif code == 416: return web.HTTPRequestRangeNotSatisfiable() elif code == 417: return web.HTTPExpectationFailed() elif code == 421: return web.HTTPMisdirectedRequest() elif code == 422: return web.HTTPUnprocessableEntity() elif code == 424: return web.HTTPFailedDependency() elif code == 426: return web.HTTPUpgradeRequired() elif code == 428: return web.HTTPPreconditionRequired() elif code == 429: return web.HTTPTooManyRequests() elif code == 431: return web.HTTPRequestHeaderFieldsTooLarge() elif code == 451: return web.HTTPUnavailableForLegalReasons() else: return web.HTTPBadRequest()
async def registration(request): if request.method == "GET": page = """ <!DOCTYPE html> <html> <body> <form action='.' method='post'> <input type="text" name="username"> <input type="password" name="pass"> <input type="submit" value="register"> </form> </body> </html> """ return web.Response(text=page, content_type='text/html') elif request.method == "POST": data = await request.post() with await request.app['db'] as conn: hpass = await conn.get(data['username']) salt = generate_salt() salt = 'K6O5AIO2CX' # hpass = create_password(data['pass'], "sha256", salt=salt) hpass = create_password(data['pass'], "pbkdf2", salt=salt) await conn.set(data['username'], hpass) return web.Response() raise web.HTTPMethodNotAllowed(request.method, ['GET', 'POST'])
async def wrapper(request): if request.method not in _allowed_methods: raise web.HTTPMethodNotAllowed( method=request.method, allowed_methods=_allowed_methods, ) from BadRequest(HTTPStatus.METHOD_NOT_ALLOWED) return await wrapped_function(request)
def _raise_allowed_methods(self): allowed_methods = { m for m in hdrs.METH_ALL | DAV_METHODS if hasattr(self, m.lower()) } raise web.HTTPMethodNotAllowed(self.request.method, sorted(allowed_methods))
async def login(request): if request.method == "GET": page = """ <!DOCTYPE html> <html> <body> <form action='.' method='post'> <input type="text" name="username"> <input type="password" name="pass"> <input type="submit" value="login"> </form> </body> </html> """ return web.Response(text=page, content_type='text/html') elif request.method == "POST": data = await request.post() #if 'login' in data and 'pass' in data: with await request.app['db'] as conn: hpass = await conn.get(data['username']) hpass = '******' # hpass = '******' check_password(hpass, data['pass']) sessionid = generate_salt() sessionid = "sessionid" await conn.set(sessionid , data['username']) response = web.Response() response.set_cookie('sessionid', sessionid) return response raise web.HTTPMethodNotAllowed(request.method, ['GET', 'POST'])
async def all_handler(self, request): """ Handles requests from client, check if parameter exists and its type :param request: sent on the client side :return: n first row of pandas Dataframe or error in JSON format """ if request.method == 'GET': params = request.rel_url.query n = params.get('n', None) if not n: error_json('Parameter n should be defined as integer.') try: n = int(n) except (ValueError, TypeError) as e: error_json('Parameter n should be defined as integer.') else: executor = request.app["executor"] result = await self.loop.run_in_executor( executor, self.get_head, n) return web.json_response(await result) else: # for POST, PUT, HEAD ect. message = 'Method not allowed.' data = {'Error': message} api_logger.debug(message) raise web.HTTPMethodNotAllowed(request.method, allowed_methods=['GET'], body=json.dumps(data).encode())
async def allow_get_requests_only(request, handler): """ Only allow GET request, otherwise raise 405 Method Not Allowed. """ if request.method != 'GET': raise web.HTTPMethodNotAllowed(method=request.method, allowed_methods=['GET']) return await handler(request)
async def add_channel(request): if request.method == 'GET': return elif request.method == 'POST': form_data = await request.post() channel_id = await db.channel_create(form_data['description'], 'rtsp://' + form_data['rtsp_link']) raise web.HTTPFound(request.app.router['player'].url_for(channel_id=str(channel_id))) else: raise web.HTTPMethodNotAllowed()
def method_handler_wrapper(request, **kwargs): method = request.method.upper() if method not in methods: raise web.HTTPMethodNotAllowed(method=method, allowed_methods=methods) if inject: return handler(request, **kwargs, method=method) else: return handler(request, **kwargs)
def function715(function376, function972): var1791 = web.HTTPMethodNotAllowed('get', ['POST', 'PUT']) assert ('GET' == var1791.method) assert (['POST', 'PUT'] == var1791.allowed_methods) assert ('POST,PUT' == var1791.headers['allow']) yield from var1791.prepare(function972) yield from var1791.write_eof() var172 = function376.decode('utf8') assert re.match( 'HTTP/1.1 405 Method Not Allowed\r\nContent-Type: text/plain; charset=utf-8\r\nAllow: POST,PUT\r\nContent-Length: 23\r\nDate: .+\r\nServer: .+\r\n\r\n405: Method Not Allowed', var172)
async def wrapper(request, *, github_app, webhook_secret=None): if request.method not in _allowed_methods: raise web.HTTPMethodNotAllowed( method=request.method, allowed_methods=_allowed_methods, ) from BadRequest(HTTPStatus.METHOD_NOT_ALLOWED) return await wrapped_function( request, github_app=github_app, webhook_secret=webhook_secret, )
def _web_path(self, pathstr, method=None): assert pathstr[0] == '/' pathstr = pathstr[1:] share_name, sep, rest = pathstr.partition('/') if len(share_name) == 0: assert len(sep) == 0 and len(rest) == 0 root = None elif share_name in self._fd: root = self._fd[share_name] else: raise web.HTTPNotFound readonly = True if root is None else share_name in self._ro if method is not None: if readonly and method != 'GET': raise web.HTTPMethodNotAllowed(method, ['GET']) if method != 'GET' and method != 'POST': raise web.HTTPMethodNotAllowed(method, ['GET', 'POST']) rest = pathlib.Path(rest) if rest.anchor: raise web.HTTPForbidden return share_name, root, readonly, rest
async def handle_request(self, request: web.Request) -> web.Response: if request.method != 'POST': return web.HTTPMethodNotAllowed(method=request.method, allowed_methods=('POST',)) try: input_data = await request.json() except json.JSONDecodeError: rpc_response = JsonRpcResponse(error=exceptions.ParseError()) return web.json_response(rpc_response.to_dict(), dumps=self.dumps) output_data = await self.process_input_data(input_data, http_request=request) return web.json_response(output_data, dumps=self.dumps)
def test_HTTPMethodNotAllowed(self): req = self.make_request() resp = web.HTTPMethodNotAllowed(req, 'get', ['POST', 'PUT']) self.assertEqual('GET', resp.method) self.assertEqual(['POST', 'PUT'], resp.allowed_methods) self.assertEqual('POST,PUT', resp.headers['allow']) self.loop.run_until_complete(resp.write_eof()) txt = self.buf.decode('utf8') self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\r\n' 'CONTENT-LENGTH: 0\r\n' 'ALLOW: POST,PUT\r\n' 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\n' 'SERVER: .+\r\n\r\n'))
async def handler(self, request: web.Request): method = getattr(self, request.method.lower(), None) if not method: raise web.HTTPMethodNotAllowed('') wanted_args = list(inspect.signature(method).parameters.keys()) available_args = request.match_info.copy() available_args.update({'request': request}) unsatisfied_args = set(wanted_args) - set(available_args.keys()) if unsatisfied_args: raise web.HttpBadRequest('') return await method(**{arg_name: available_args[arg_name] for arg_name in wanted_args})
async def wrapped(request: web.BaseRequest): if request.path not in self.routes: raise web.HTTPNotFound() path_routes = self.routes[request.path] if request.method not in path_routes: raise web.HTTPMethodNotAllowed( method=request.method, allowed_methods=path_routes.keys()) method = path_routes[request.method] result = await method['func'](bot.get_cog(name=method['plugin']), request=request) return result
def test_HTTPMethodNotAllowed(buf, request): resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT']) assert 'GET' == resp.method assert ['POST', 'PUT'] == resp.allowed_methods assert 'POST,PUT' == resp.headers['allow'] yield from resp.prepare(request) yield from resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 405 Method Not Allowed\r\n' 'CONTENT-TYPE: text/plain; charset=utf-8\r\n' 'CONTENT-LENGTH: 23\r\n' 'ALLOW: POST,PUT\r\n' 'DATE: .+\r\n' 'SERVER: .+\r\n\r\n' '405: Method Not Allowed', txt)
def _web_path(self, pathstr, method=None): if not pathstr.startswith(self._prefix): raise web.HTTPMovedPermanently(self._prefix) pathstr = pathstr[len(self._prefix):] share_name, sep, rest = pathstr.partition('/') if len(share_name) == 0: assert len(sep) == 0 and len(rest) == 0 root = None elif share_name in self._fd: root = self._fd[share_name] else: raise web.HTTPNotFound if callable(root): return root readonly = root is None or share_name in self._ro if method is not None: if readonly and method != 'GET': raise web.HTTPMethodNotAllowed(method, ['GET']) if method != 'GET' and method != 'POST': raise web.HTTPMethodNotAllowed(method, ['GET', 'POST']) rest = pathlib.Path(rest) if rest.anchor: raise web.HTTPForbidden return share_name, root, readonly, rest
def test_HTTPMethodNotAllowed(buf, request): resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT']) assert 'GET' == resp.method assert ['POST', 'PUT'] == resp.allowed_methods assert 'POST,PUT' == resp.headers['allow'] yield from resp.prepare(request) yield from resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 405 Method Not Allowed\r\n' 'Content-Type: text/plain; charset=utf-8\r\n' 'Content-Length: 23\r\n' 'Allow: POST,PUT\r\n' 'Date: .+\r\n' 'Server: .+\r\n\r\n' '405: Method Not Allowed', txt)
async def __call__(self, request): """Main Resource Entry point Handles user auth Method level ACL """ mn = request.method.lower() if hasattr(self, mn): ins = self.from_request(request) m = getattr(ins, request.method.lower(), None) if not m: raise web.HTTPMethodNotAllowed(request) # perm checks await self.verify_permissions() return await m(**dict(request.match_info))
async def test_ctor(self) -> None: resp = web.HTTPMethodNotAllowed('GET', ['POST', 'PUT'], headers={'X-Custom': 'value'}, reason='Unsupported', text='text', content_type='custom') assert resp.method == 'GET' assert resp.allowed_methods == {'POST', 'PUT'} assert resp.text == 'text' assert resp.headers == { 'X-Custom': 'value', 'Content-Type': 'custom', 'Allow': 'POST,PUT' } assert resp.reason == 'Unsupported' assert resp.status == 405
async def wrapper(self: View, *args, **kwargs): swagger = self.request.app['swagger'] base_path = swagger.base_path paths = swagger.specification['paths'] path, _ = swagger.get_path_spec(self.rel_url.raw_path) assert path is not None assert path.startswith(base_path) path = path[len(base_path):] method = p_method or self.request.method if method.lower() not in paths[path]: raise web.HTTPMethodNotAllowed( method, list([method.upper() for method in paths[path].keys()])) method_info = paths[path][method.lower()] if 'security' in method_info: await enforce_one_of(self.request, method_info['security']) return await f(self, *args, **kwargs)
def test_pickle(self) -> None: resp = web.HTTPMethodNotAllowed(method='GET', allowed_methods=('POST', 'PUT'), headers={'X-Custom': 'value'}, reason='Unsupported', text='text', content_type='custom') resp.foo = 'bar' for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): pickled = pickle.dumps(resp, proto) resp2 = pickle.loads(pickled) assert resp2.method == 'GET' assert resp2.allowed_methods == {'POST', 'PUT'} assert resp2.text == 'text' assert resp2.headers == resp.headers assert resp2.reason == 'Unsupported' assert resp2.status == 405 assert resp2.foo == 'bar'
async def handle_http_request(self, http_request: web.Request) -> web.Response: if http_request.method != 'POST': raise web.HTTPMethodNotAllowed(method=http_request.method, allowed_methods=('POST', )) try: input_data = await http_request.json() except json.JSONDecodeError as e: response = protocol.JsonRpcResponse( error=errors.ParseError(utils.get_exc_message(e))) return web.json_response(response.to_dict(), dumps=self.json_serialize) output_data = await self._process_input_data( input_data, context={'http_request': http_request}) return web.json_response(output_data, dumps=self.json_serialize)
async def put(self): editable_resource = self.resource / self.relative try: await editable_resource.populate_props() is_collection = editable_resource.is_collection except errors.ResourceDoesNotExist: is_collection = False if is_collection: raise web.HTTPMethodNotAllowed('PUT', ', '.join(DAV_METHODS), text="Can't PUT to collection") if isinstance(self.request.content, EmptyStreamReader): reader = None else: reader = self.request.content.readany created = await editable_resource.put_content(reader) if created: return web.HTTPCreated() return web.HTTPOk()
async def test_ctor(self) -> None: resp = web.HTTPMethodNotAllowed( "GET", ["POST", "PUT"], headers={"X-Custom": "value"}, reason="Unsupported", text="text", content_type="custom", ) assert resp.method == "GET" assert resp.allowed_methods == {"POST", "PUT"} assert resp.text == "text" assert resp.headers == { "X-Custom": "value", "Content-Type": "custom", "Allow": "POST,PUT", } assert resp.reason == "Unsupported" assert resp.status == 405
async def db_request(request): if request.method == "GET": page = """ <!DOCTYPE html> <html> <body> <form action='.' method='post'> <input type="text" name="request"> <input type="submit" value="commit"> </form> </body> </html> """ return web.Response(text=page, content_type='text/html') elif request.method == "POST": data = await request.post() with await request.app['db'] as conn: await conn.get(data['request']) return web.Response() raise web.HTTPMethodNotAllowed(request.method, ['GET', 'POST'])
async def to_dict(self): swagger = self.request.app['swagger'] base_path = swagger.base_path paths = swagger.specification['paths'] path, _ = swagger.get_path_spec( self.rel_url.raw_path ) assert path is not None assert path.startswith(base_path) path = path[len(base_path):] if 'get' not in paths[path]: raise web.HTTPMethodNotAllowed( 'GET', list([ method.upper() for method in paths[path].keys() ]) ) method_info = paths[path]['get'] if 'security' in method_info: await authorization.enforce_one_of(self.request, method_info['security']) return await super().to_dict()