def _fallback_view(request): # Maybe we failed to match any definitions for the request method? if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods raise response # Maybe we failed to match an acceptable content-type? # First search all the definitions to find the acceptable types. # XXX: precalculate this like the defined_methods list? acceptable = [] for method, _, args in service.definitions: if method != request.method: continue if 'accept' in args: acceptable.extend( service.get_acceptable(method, filter_callables=True)) if 'acceptable' in request.info: for content_type in request.info['acceptable']: if content_type not in acceptable: acceptable.append(content_type) # Now check if that was actually the source of the problem. if not request.accept.best_match(acceptable): response = HTTPNotAcceptable() response.content_type = "application/json" response.body = json.dumps(acceptable) raise response # In the absence of further information about what went wrong, # let upstream deal with the mismatch. raise PredicateMismatch(service.name)
def test_check_request_method_view(web_app, pyramid_request): root = pyramid_request.root root['resource'] = DummyResource({'foo': 'Hello', 'bar': 123}) resource_url = pyramid_request.resource_url(root['resource']) res = web_app.get(resource_url) assert res.content_type == 'application/json' assert res.json_body == {'foo': 'Hello', 'bar': 123} params = {'foo': 'World', 'bar': 456} res = web_app.put_json(resource_url, params=params) assert res.json_body == params web_app.post_json(resource_url, params=params, exception=HTTPMethodNotAllowed()) web_app.delete_json(resource_url, params=params, exception=HTTPMethodNotAllowed()) web_app.patch_json(resource_url, params=params, exception=HTTPMethodNotAllowed()) # View deriver do not work for custom views custom_view_url = resource_url + 'custom_view' res = web_app.patch_json(custom_view_url) assert res.json_body == {'custom': 'view', 'result': 789}
def _fallback_view(request): # Maybe we failed to match any definitions for the request method? if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods raise response # Maybe we failed to match an acceptable content-type? # First search all the definitions to find the acceptable types. # XXX: precalculate this like the defined_methods list? acceptable = [] supported_contenttypes = [] for method, _, args in service.definitions: if method != request.method: continue if 'accept' in args: acceptable.extend( service.get_acceptable(method, filter_callables=True)) acceptable.extend( request.info.get('acceptable', [])) acceptable = list(set(acceptable)) # Now check if that was actually the source of the problem. if not request.accept.best_match(acceptable): request.errors.add( 'header', 'Accept', 'Accept header should be one of {0}'.format( acceptable).encode('ascii')) request.errors.status = HTTPNotAcceptable.code error = service.error_handler(request) raise error if 'content_type' in args: supported_contenttypes.extend( service.get_contenttypes(method, filter_callables=True)) supported_contenttypes.extend( request.info.get('supported_contenttypes', [])) supported_contenttypes = list(set(supported_contenttypes)) # Now check if that was actually the source of the problem. if not content_type_matches(request, supported_contenttypes): request.errors.add( 'header', 'Content-Type', 'Content-Type header should be one of {0}'.format( supported_contenttypes).encode('ascii')) request.errors.status = HTTPUnsupportedMediaType.code error = service.error_handler(request) raise error # In the absence of further information about what went wrong, # let upstream deal with the mismatch. # After "custom predicates" feature has been added there is no need in # this line. Instead requests will be filtered by "custom predicates" # feature filter and exception "404 Not found" error will be raised. In # order to avoid unpredictable cases, we left this line in place and # excluded it from coverage. raise PredicateMismatch(service.name) # pragma: no cover
def _fallback_view(request): # Maybe we failed to match any definitions for the request method? if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods raise response # Maybe we failed to match an acceptable content-type? # First search all the definitions to find the acceptable types. # XXX: precalculate this like the defined_methods list? acceptable = [] supported_contenttypes = [] for method, _, args in service.definitions: if method != request.method: continue if 'accept' in args: acceptable.extend( service.get_acceptable(method, filter_callables=True)) acceptable.extend( request.info.get('acceptable', [])) acceptable = list(set(acceptable)) # Now check if that was actually the source of the problem. if not request.accept.acceptable_offers(offers=acceptable): request.errors.add( 'header', 'Accept', 'Accept header should be one of {0}'.format( acceptable).encode('ascii')) request.errors.status = HTTPNotAcceptable.code error = service.error_handler(request) raise error if 'content_type' in args: supported_contenttypes.extend( service.get_contenttypes(method, filter_callables=True)) supported_contenttypes.extend( request.info.get('supported_contenttypes', [])) supported_contenttypes = list(set(supported_contenttypes)) # Now check if that was actually the source of the problem. if not content_type_matches(request, supported_contenttypes): request.errors.add( 'header', 'Content-Type', 'Content-Type header should be one of {0}'.format( supported_contenttypes).encode('ascii')) request.errors.status = HTTPUnsupportedMediaType.code error = service.error_handler(request) raise error # In the absence of further information about what went wrong, # let upstream deal with the mismatch. # After "custom predicates" feature has been added there is no need in # this line. Instead requests will be filtered by "custom predicates" # feature filter and exception "404 Not found" error will be raised. In # order to avoid unpredictable cases, we left this line in place and # excluded it from coverage. raise PredicateMismatch(service.name) # pragma: no cover
def _fallback_view(request): # Maybe we failed to match any definitions for the request method? if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods raise response # Maybe we failed to match an acceptable content-type? # First search all the definitions to find the acceptable types. # XXX: precalculate this like the defined_methods list? acceptable = [] supported_contenttypes = [] for method, _, args in service.definitions: if method != request.method: continue if 'accept' in args: acceptable.extend( service.get_acceptable(method, filter_callables=True)) acceptable.extend( request.info.get('acceptable', [])) acceptable = list(set(acceptable)) # Now check if that was actually the source of the problem. if not request.accept.best_match(acceptable): request.errors.add( 'header', 'Accept', 'Accept header should be one of {0}'.format( acceptable).encode('ascii')) request.errors.status = HTTPNotAcceptable.code error = service.error_handler(request.errors) raise error if 'content_type' in args: supported_contenttypes.extend( service.get_contenttypes(method, filter_callables=True)) supported_contenttypes.extend( request.info.get('supported_contenttypes', [])) supported_contenttypes = list(set(supported_contenttypes)) # Now check if that was actually the source of the problem. if not content_type_matches(request, supported_contenttypes): request.errors.add( 'header', 'Content-Type', 'Content-Type header should be one of {0}'.format( supported_contenttypes).encode('ascii')) request.errors.status = HTTPUnsupportedMediaType.code error = service.error_handler(request.errors) raise error # In the absence of further information about what went wrong, # let upstream deal with the mismatch. raise PredicateMismatch(service.name)
def cornice_tween(request): response = handler(request) service = get_service(request) if service is not None: if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods else: # get the filters for this call kwargs = service.definitions[request.method] for _filter in kwargs.get('filters', []): response = _filter(response) return response
def _notfound(request): match = request.matchdict # the route exists, raising a 405 if match is not None: pattern = request.matched_route.pattern service = request.registry['cornice_services'].get(pattern) if service is not None: res = HTTPMethodNotAllowed() res.allow = service.defined_methods return res # 404 return HTTPNotFound()
def generate_suggested_password(request): """ The suggested password is saved in session to avoid form hijacking """ password_length = request.registry.settings.get('password_length', 12) if request.method == 'GET': password = generate_password(length=password_length) password = '******'.join( [password[i * 4:i * 4 + 4] for i in range(0, len(password) / 4)]) request.session['last_generated_password'] = password return password elif request.method == 'POST': password = request.session.get( 'last_generated_password', generate_password(length=password_length)) return password # We should not rely solely on the configuration of the # reverse proxy to filter out only GET and POST. else: raise HTTPMethodNotAllowed( _('Invalid request: only GET and POST accepted.'))
def post(self): if self.request.method != "POST": return HTTPMethodNotAllowed() if 'submit' not in self.request.POST: # this was submitted without submitting the form, no good msg = 'Unable to delete domains except by form submission' return HTTPBadRequest(msg) target_domainname = self.request.POST.get('name', None) domain_found = False msg = 'Unable to delete %s, ' msg_queue = 'error' try: query = self.request.db_session.query(DomainProfile).filter( DomainProfile.name == target_domainname) target_domain = query.one() domain_found = True except MultipleResultsFound: msg += 'the name does not uniquely identify a domain record.' except NoResultFound: msg += 'the domain record does not exist.' if domain_found: self.request.db_session.delete(target_domain) authzn_query = self.request.db_session.query(OAuthAuthorization) authzn_query.filter( OAuthAuthorization.client_id == target_domainname, ).delete() msg = 'The domain %s was successfully deleted' msg_queue = 'success' self.request.session.flash(msg % target_domainname, queue=msg_queue) return HTTPFound(location=self.return_url)
def post(self): if self.request.method != "POST": return HTTPMethodNotAllowed() if 'submit' not in self.request.POST and \ 'cancel' not in self.request.POST: return self.get() if 'contact_name' not in self.request.POST.keys( ) and self.request.user: self.request.POST['contact_name'] = self.request.user.full_name if 'reply_email' not in self.request.POST.keys() and self.request.user: self.request.POST['reply_email'] = self.request.user.email try: controls = self.request.POST.items() captured = self.frm.validate(controls) self.notify(captured) if captured['came_from']: return HTTPFound(location=captured['came_from']) else: return HTTPFound(location=self.request.route_url('home')) except ValidationFailure as e: # the submitted values could not be validated html = e.render() if 'cancel' in self.request.POST and \ e.cstruct['came_from']: return HTTPFound(location=e.cstruct['came_from']) return { 'forms': [self.frm], 'rendered_form': html, }
def create_design_request_post(req: Request): if req.method != 'POST': return HTTPMethodNotAllowed("This route only valid for POST request") is_logged_in = verify_user_token(req) user = DBSession.query( m.DoctorUser).filter_by(username=req.session.get('uname')).first() if not is_logged_in or not user: return HTTPUnauthorized("You must be logged in to view this page") data = req.POST title = data['title'] body = data['body'] files_list = data.getall('files') # file_path_list = [] # if files_list: # file_path_list = store_file_view(files_list) if data and title and body: new_design_request = m.DesignPost(title, body, [], user, datetime.datetime.now()) DBSession.add(new_design_request) transaction.manager.commit() return HTTPFound(req.params.get('return', '/')) else: return HTTPBadRequest("Malformed request")
def submit_design_response_post(req: Request): if req.method != 'POST': return HTTPMethodNotAllowed("This route only valid for POST request") post = DBSession.query( m.DesignPost).filter_by(post_id=req.matchdict['post_id']).first() data = req.POST body = data.get('print-notes') files_list = data.getall('files') file_path_list = [] if files_list: file_path_list = store_file_view(files_list) if body and file_path_list: new_design_submission = m.DesignResponse(body, file_path_list, req.session.get('uname'), post) DBSession.add(new_design_submission) transaction.manager.commit() return HTTPFound(req.params.get('return', '/')) else: return HTTPBadRequest("Malformed request")
def cornice_tween(request): response = handler(request) if request.matched_route is not None: # do some sanity checking on the response using filters pattern = request.matched_route.pattern service = request.registry['cornice_services'].get(pattern) if service is not None: if request.method not in service.defined_methods: response = HTTPMethodNotAllowed() response.allow = service.defined_methods else: # get the filters for this call kwargs = service.definitions[request.method] for _filter in kwargs.get('filters', []): response = _filter(response) return response
def post(self): if self.request.method != "POST": return HTTPMethodNotAllowed() if 'submit' not in self.request.POST: return self.get() controls = self.request.POST.items() self.request.target_user = self.target_user activity_detail = {} try: appstruct = self.frm.validate(controls) # call validate except ValidationFailure, e: # Don't leak hash information if ('password' in self.frm.cstruct and self.frm.cstruct['password'] != ''): self.frm.cstruct['password'] = '' data = { 'forms': [self.frm], 'rendered_form': e.render(), 'target_username': self.target_username, } ex_data = self.get_extended_data() if ex_data: data.update(ex_data) return data
def create(self, request): """ Read the GeoJSON feature collection from the request body and create new objects in the database. """ if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) collection = loads(request.body, object_hook=GeoJSON.to_instance) if not isinstance(collection, FeatureCollection): return HTTPBadRequest() session = self.Session() objects = [] for feature in collection.features: create = False obj = None if hasattr(feature, 'id') and feature.id is not None: obj = session.query(self.mapped_class).get(feature.id) if self.before_create is not None: self.before_create(request, feature, obj) if obj is None: obj = self.mapped_class(feature) create = True else: obj.__update__(feature) if create: session.add(obj) objects.append(obj) session.flush() collection = FeatureCollection(objects) if len(objects) > 0 else None request.response.status_int = 201 return collection
def post(self): if self.request.method != "POST": return HTTPMethodNotAllowed() if 'submit' not in self.request.POST: return self.get() try: controls = self.request.POST.items() captured = self.frm.validate(controls) query = self.request.db_session.query(UserProfile) query = query.filter(UserProfile.email == captured['email']) profile = query.first() self.request.registry.notify( PasswordRequested(self.request, profile, came_from=captured['came_from'])) self.request.session.flash( 'A link to reset your password has been sent to your email. Please check.', queue='success') url = self.request.route_url('home') return HTTPFound(location=url) except ValidationFailure as e: # the submitted values could not be validated html = e.render() return { 'forms': [self.frm], 'rendered_form': html, }
def create_print_request_post(req: Request): if req.method != 'POST': return HTTPMethodNotAllowed("This route only valid for POST request") is_logged_in = verify_user_token(req) user = DBSession.query( m.DoctorUser).filter_by(username=req.session.get('uname')).first() if not is_logged_in or not user: return HTTPUnauthorized("You must be logged in to view this page") data = req.POST title = data.get('title') # body = data.get('print-notes') num_parts = data.get('num-items') date_needed = datetime.datetime.strptime(data.get('completion-date'), '%Y-%m-%d') files_list = data.getall('files') file_path_list = [] if files_list: file_path_list = store_file_view(files_list) if title and num_parts and date_needed: new_print_request = m.PrintPost(title, "", file_path_list, user, date_needed, num_parts) DBSession.add(new_print_request) transaction.manager.commit() return HTTPFound(req.params.get('return', '/')) else: return HTTPBadRequest("Malformed request")
def collection_get(self): """ Acquire all existing builds for a given release Currently ONLY allow with a query string to find highest build number, as there's no good definition or use for the general case yet """ md = self.request.matchdict if self.request.params: param_keys = list(self.request.params.keys()) if param_keys != ['filter']: return HTTPBadRequest( f'Invalid set of parameters: {", ".join(param_keys)}') else: filter_name = self.request.params['filter'] if filter_name == 'highest_build_num': result = { 'build_num': self.build_info.get_highest_release_build( md['product_name'], md['release_name']) } else: return HTTPBadRequest( f'Filter "{filter_name}" not supported for builds') else: return HTTPMethodNotAllowed( f'Endpoint {self.request.path} without parameters ' f'not supported') return result
def whitenoise_tween(request): whn = request.registry.whitenoise if whn.autorefresh: static_file = whn.find_file(request.path_info) else: static_file = whn.files.get(request.path_info) # We could not find a static file, so we'll just continue processing # this as normal. if static_file is None: return handler(request) request_headers = dict(kv for kv in request.environ.items() if kv[0].startswith("HTTP_")) if request.method not in {"GET", "HEAD"}: return HTTPMethodNotAllowed() else: path, headers = static_file.get_path_and_headers(request_headers) headers = MultiDict(headers) resp = FileResponse( path, request=request, content_type=headers.pop("Content-Type", None), content_encoding=headers.pop("Content-Encoding", None), ) resp.md5_etag() resp.headers.update(headers) return resp
def register_fab_post(req: Request): if req.method != 'POST': return HTTPMethodNotAllowed("This route only valid for POST request") data = req.POST uname = data.get('uname') passwd = data.get('password') email = data.get('email') fname = data.get('fname') lname = data.get('lname') country = data.get('country') state = data.get('state') city = data.get('city') printer_model = data.get('printer model') print_quality = data.get('print quality') if uname and passwd and email and fname and lname and country and state and city and printer_model and print_quality: new_fab = m.FabUser(uname, passwd, email, fname, lname, country, state, city, printer_model, print_quality) dbs = DBSession() dbs.add(new_fab) new_token = new_fab.refresh_session() transaction.manager.commit() req.session['uname'] = uname req.session['session_token'] = new_token return HTTPFound(req.params.get('return', '/')) else: return HTTPBadRequest("Malformed request")
def __call__(self): context = self.context request = self.request root = request.root login = root['login'] logout = root['logout'] if context == logout: authentication_ticket = None else: authentication_ticket = request.authenticated_userid if context != login and not authentication_ticket: request.session['next'] = request.path return HTTPFound(request.resource_url(login)) method = request.method.lower() if method not in self.methods: return HTTPMethodNotAllowed() result = getattr(self, method)(request) if isinstance(result, Response): return result elif isinstance(result, dict): data = dict(title=context.title, username=getattr(authentication_ticket, 'username', None)) data.update(result) return data elif result: return Response(result) else: return HTTPInternalServerError()
def persona_login(request): if request.method != 'POST': return HTTPMethodNotAllowed('Only POST is allowed') assertion = request.POST.get('assertion', None) if assertion is None: return HTTPBadRequest('The assertion parameter is required') if 'next_url' in request.params and request.params['next_url']: request.session['next_url'] = request.params['next_url'] settings = request.registry.settings data = { 'assertion': assertion, 'audience': get_audience(settings['public_url_root']) } response = requests.post(settings['persona_verifier_url'], data=data, verify=True) if response.ok: verification_data = response.json() if verification_data['status'] == 'okay': email = verification_data['email'] info = {'email': email} user_id = hashlib.sha1(email.encode('utf-8')).hexdigest() return register_or_update(request, 'persona', user_id, info, request.route_path('home')) else: return HTTPForbidden( 'Mozilla Persona verifier can not verify your identity') else: return HTTPBadGateway( 'Mozilla Persona verifier is not working properly')
def advice(parent_object, *args, **kw): if isinstance(parent_object.provider, SQLAlchemyProvider) and \ 'external' not in parent_object.provider.get_metadata()['subject']: return fn(parent_object, *args, **kw) else: raise HTTPMethodNotAllowed()
def metrics_collection(request): if request.method == 'GET': metrics = metric_manager.metrics.values() dump_result = metric_schema.dump(metrics, many=True).data return dump_result elif request.method == 'POST': print(len(request.json_body)) if not request.json_body: raise HTTPBadRequest('No input data provided') errors = metric_schema.validate(request.json_body) if errors: raise HTTPBadRequest(errors) metric = SurfboardMetricModel( status=SurferStatus[request.json_body['status']], speed_in_mph=request.json_body['speed_in_mph'], altitude_in_feet=request.json_body['altitude_in_feet'], water_temperature_in_f=request.json_body['water_temperature_in_f']) metric_manager.insert_metric(metric) dumped_metric = metric_schema.dump(metric).data response = Response() response.status_code = HTTPCreated.code # It is necessary to set the content_type # The default is text/html; charset=UTF-8 response.content_type = 'application/json; charset=UTF-8' response.json_body = dumped_metric return response else: # The method is neither GET nor POST raise HTTPMethodNotAllowed()
def collection_get(self): """ Acquire all existing changesets, which doesn't have any useful logical definition, so we don't support it """ return HTTPMethodNotAllowed( f'Endpoint {self.request.path} not supported')
def get(self): """ Acquire specific build for a given release - currently NOT supported as there's no good definition or use for this yet """ return HTTPMethodNotAllowed( f'Endpoint {self.request.path} not supported')
def collection_get(self): """ Acquire all existing builds - currently NOT supported as it would return ALL build information from the database (which isn't useful) """ return HTTPMethodNotAllowed( f'Endpoint {self.request.path} not supported')
def __call__(self): """ Call the view to trigger the method which implements the requested HTTP verb. """ try: return getattr(self, self.request.method.lower())() except AttributeError: return HTTPMethodNotAllowed()
def wrapped(context, request): # If the current request is using an unallowed method then we'll reject # it *UNLESS* it is an exception view, then we'll allow it again # *UNLESS* the exception view set an explicit require_methods itself. if request.method not in require_methods and ( getattr(request, "exception", None) is None or explicit): raise HTTPMethodNotAllowed( headers={"Allow": ", ".join(sorted(require_methods))}) return view(context, request)
def http_method_not_allowed(self, request, *args, **kwargs): logger.warning('Method Not Allowed (%s): %s', request.method, request.path, extra={ 'status_code': 405, 'request': request }) raise HTTPMethodNotAllowed()
def admin_traversal(context, request): m = request.method.lower() if not hasattr(context, m): raise HTTPMethodNotAllowed() c = getattr(context, m)(request) if isinstance(c, HTTPException): return c c['templates'] = [context.main_template] + context.templates c['view_context'] = context c['left_menu'] = context.left_menu or [] return render_to_response('admin/layout.mako', c, request=request)
def logout(request: Request) -> Response: """Logout view. :param request: Pyramid request. :return: Context to be used by the renderer. """ if request.method != "POST": # No GET / CSRF logouts return HTTPMethodNotAllowed() login_service = get_login_service(request) return login_service.logout()
def block_webdav(event): """ Microsoft Office will now cause Internet Explorer to attempt to open Word Docs using WebDAV when viewing Word Docs in the browser. It is imperative that we disavow any knowledge of WebDAV to prevent IE from doing insane things. http://serverfault.com/questions/301955/ """ if event.request.method in ('PROPFIND', 'OPTIONS'): raise HTTPMethodNotAllowed(event.request.method)
def mapped_view(context, request: PyramidRequest): method = request.method if (context is not request.root and IResource.providedBy(context) and method != 'OPTIONS'): if method == 'HEAD': method = 'GET' if method not in context.get_allowed_methods(): raise HTTPMethodNotAllowed( f'The method {request.method} is not allowed for this resource.' ) return view(context, request)
def _fallback_view(self, request): """Fallback view for this service, called when nothing else matches. This method provides the view logic to be executed when the request does not match any explicitly-defined view. Its main responsibility is to produce an accurate error response, such as HTTPMethodNotAllowed or HTTPNotAcceptable. """ # Maybe we failed to match any definitions for the request method? if request.method not in self.defined_methods: response = HTTPMethodNotAllowed() response.allow = self.defined_methods return response # Maybe we failed to match an acceptable content-type? # First search all the definitions to find the acceptable types. # XXX: precalculate this like the defined_methods list? acceptable = [] for api_kwargs in self.definitions: if api_kwargs["request_method"] != request.method: continue if "accept" in api_kwargs: accept = to_list(api_kwargs.get("accept")) acceptable.extend(a for a in accept if not callable(a)) if "acceptable" in request.info: for content_type in request.info["acceptable"]: if content_type not in acceptable: acceptable.append(content_type) # Now check if that was actually the source of the problem. if not request.accept.best_match(acceptable): response = HTTPNotAcceptable() response.content_type = "application/json" response.body = json.dumps(acceptable) return response # In the absence of further information about what went wrong, # let upstream deal with the mismatch. raise PredicateMismatch(self.name)