def _network_gateway(self, name='gw1', devices=None, fmt='json', tenant_id=_uuid()): device = None if not devices: device_res = self._create_gateway_device( fmt, tenant_id, 'stt', '1.1.1.1', 'xxxxxx', name='whatever') if device_res.status_int >= 400: raise exc.HTTPClientError(code=device_res.status_int) device = self.deserialize(fmt, device_res) devices = [{'id': device[self.dev_resource]['id'], 'interface_name': 'xyz'}] res = self._create_network_gateway(fmt, tenant_id, name=name, devices=devices) if res.status_int >= 400: raise exc.HTTPClientError(code=res.status_int) network_gateway = self.deserialize(fmt, res) yield network_gateway self._delete(networkgw.NETWORK_GATEWAYS, network_gateway[self.gw_resource]['id']) if device: self._delete(networkgw.GATEWAY_DEVICES, device[self.dev_resource]['id'])
def update(self, request, environment_id, body): LOG.debug('Environments:Update <Id: {0}, ' 'Body: {1}>'.format(environment_id, body)) target = {"environment_id": environment_id} policy.check('update_environment', request.context, target) session = db_session.get_session() environment = session.query(models.Environment).get(environment_id) if environment is None: LOG.info( _('Environment <EnvId {0}> is not ' 'found').format(environment_id)) raise exc.HTTPNotFound if environment.tenant_id != request.context.tenant: LOG.info( _('User is not authorized to access ' 'this tenant resources.')) raise exc.HTTPUnauthorized LOG.debug('ENV NAME: {0}>'.format(body['name'])) if VALID_NAME_REGEX.match(str(body['name'])): environment.update(body) environment.save(session) else: msg = _('Environment name must contain only alphanumeric ' 'or "_-." characters, must start with alpha') LOG.exception(msg) raise exc.HTTPClientError(msg) return environment.to_dict()
def update(self, request, environment_id, body): """"Rename an environment.""" LOG.debug('Environments:Update <Id: {id}, ' 'Body: {body}>'.format(id=environment_id, body=body)) target = {"environment_id": environment_id} policy.check('update_environment', request.context, target) session = db_session.get_session() environment = session.query(models.Environment).get(environment_id) new_name = six.text_type(body['name']) if new_name.strip(): if len(new_name) > 255: msg = _('Environment name should be 255 characters maximum') LOG.error(msg) raise exc.HTTPBadRequest(explanation=msg) try: environment.update({'name': new_name}) environment.save(session) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.error(msg) raise exc.HTTPConflict(explanation=msg) else: msg = _('Environment name must contain at least one ' 'non-white space symbol') LOG.error(msg) raise exc.HTTPClientError(explanation=msg) return environment.to_dict()
def create(self, request, body): """It creates the env template from the payload obtaining. This payload can contain just the template name, or include also service information. :param request: the operation request. :param body: the env template description :return: the description of the created template. """ LOG.debug('EnvTemplates:Create <Body {body}>'.format(body=body)) policy.check('create_env_template', request.context) try: LOG.debug( 'ENV TEMP NAME: {templ_name}>'.format(templ_name=body['name'])) if not envs_api.VALID_NAME_REGEX.match(str(body['name'])): msg = _('Environment Template must contain only alphanumeric ' 'or "_-." characters, must start with alpha') LOG.error(msg) raise exc.HTTPBadRequest(msg) except Exception: msg = _('Env template body is incorrect') LOG.exception(msg) raise exc.HTTPClientError(msg) if len(body['name']) > 255: msg = _('Environment Template name should be 255 characters ' 'maximum') LOG.exception(msg) raise exc.HTTPBadRequest(explanation=msg) try: template = env_temps.EnvTemplateServices.create( body.copy(), request.context.tenant) return template.to_dict() except db_exc.DBDuplicateEntry: msg = _('Env Template with specified name already exists') LOG.exception(msg) raise exc.HTTPConflict(msg)
def start_handle_request(self, app, environ, start_response, services_service): websocket = self.create_websocket(environ) if websocket is not None: environ.pop('set_websocket')(websocket, environ) request = app.create_request(environ) try: request.params, request.url except UnicodeDecodeError: response = exc.HTTPClientError() else: try: if websocket is not None: def start_response(status, headers, sr=start_response): sr(status, headers + [('Content-length', '0')]) response = services_service( super(Publisher, self).start_handle_request, app, request=request, start_response=start_response, response=app.create_response(request), websocket=websocket ) if websocket is not None: response = self.websocket_app(['binary'], handler_cls=self.websocket_handler) except exc.HTTPException as e: response = e except Exception: self.logger.critical('Unhandled exception', exc_info=True) response = exc.HTTPInternalServerError() return [] if response is None else response(environ, start_response)
def create(self, request, body): LOG.debug('Environments:Create <Body {body}>'.format(body=body)) policy.check('create_environment', request.context) if not body.get('name'): msg = _('Please, specify a name of the environment to create') LOG.exception(msg) raise exc.HTTPBadRequest(explanation=msg) name = unicode(body['name']) if len(name) > 255: msg = _('Environment name should be 255 characters maximum') LOG.exception(msg) raise exc.HTTPBadRequest(explanation=msg) if VALID_NAME_REGEX.match(name): try: environment = envs.EnvironmentServices.create( body.copy(), request.context) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.exception(msg) raise exc.HTTPConflict(explanation=msg) else: msg = _('Environment name must contain only alphanumericor "_-." ' 'characters, must start with alpha') LOG.exception(msg) raise exc.HTTPClientError(explanation=msg) return environment.to_dict()
def put(self, parent_identifier, key, body): body_dict = body.as_dict() parent_attr = body_dict.get(new_cls.parent_attribute_name) if parent_attr is not None and parent_attr != parent_identifier: raise exc.HTTPClientError( 'API parent identifier(%s): %s does not match parent ' 'key value: %s' % (self.parent_attribute_name, parent_attr, parent_identifier)) return self.api_mgr.handle_update(self, key, body.as_dict())
def _network_gateway(self, name='gw1', devices=None, fmt='json', tenant_id=_uuid()): if not devices: devices = [{'id': _uuid(), 'interface_name': 'xyz'}] res = self._create_network_gateway(fmt, tenant_id, name=name, devices=devices) network_gateway = self.deserialize(fmt, res) if res.status_int >= 400: raise exc.HTTPClientError(code=res.status_int) yield network_gateway self._delete(networkgw.COLLECTION_NAME, network_gateway[self.resource]['id'])
def _do_request(self, method, path, data=None, params=None, action=None): content_type = 'application/json' body = None if data is not None: # empty dict is valid body = wsgi.Serializer().serialize(data, content_type) req = testlib_api.create_request( path, body, content_type, method, query_string=params) res = req.get_response(self._api) if res.status_code >= 400: raise webexc.HTTPClientError(detail=res.body, code=res.status_code) if res.status_code != webexc.HTTPNoContent.code: return res.json
def test_http_client_exception(self): req = wsgi_resource.Request({}) language = req.best_match_language() e = exc.HTTPClientError() result = common.convert_exception_to_http_exc(e, {}, language) except_res = {'message': 'The server could not comply with' ' the request since it is either ' 'malformed or otherwise incorrect.', 'type': 'HTTPClientError', 'detail': ''} self.assertEqual( except_res, jsonutils.loads(result.body)["TackerError"]) self.assertEqual(400, result.code)
class AccessTokenHandler(BaseHandler): """The access token request handler. """ ROUTES = [(r'/oauth/access_token/?', 'oauth.AccessTokenHandler')] @staticmethod def is_valid_token(conn, access_token): """Returns True if the given access token is valid, False otherwise.""" cursor = conn.execute( 'SELECT token FROM oauth_access_tokens WHERE token = ?', (access_token, )) return cursor.fetchone() is not None def get(self): """Handles a /oauth/access_token request to allocate an access token. Writes the response directly. """ try: grant_type = self.request.get('grant_type') redirect_uri = self.request.get('redirect_uri') try: client_id, _, code = self.get_required_args( 'client_id', 'client_secret', 'code') except AssertionError, e: assert False, ERROR_JSON % 'Missing %s parameter' % unicode(e) # app login. background: # http://developers.facebook.com/docs/authentication/#applogin if grant_type == 'client_credentials': redirect_uri = '' code = self.create_auth_code(client_id, redirect_uri) token = self.create_access_token(code, client_id, redirect_uri) self.response.charset = 'utf-8' self.response.out.write( urllib.urlencode({ 'access_token': token, 'expires': EXPIRES })) except AssertionError, e: raise exc.HTTPClientError(unicode(e).encode('utf8'))
def create(self, request, body): LOG.debug('Environments:Create <Body {0}>'.format(body)) policy.check('create_environment', request.context) LOG.debug('ENV NAME: {0}>'.format(body['name'])) if VALID_NAME_REGEX.match(str(body['name'])): try: environment = envs.EnvironmentServices.create( body.copy(), request.context.tenant) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.exception(msg) raise exc.HTTPConflict(msg) else: msg = _('Environment name must contain only alphanumeric ' 'or "_-." characters, must start with alpha') LOG.exception(msg) raise exc.HTTPClientError(msg) return environment.to_dict()
def _gateway_device(self, name='gw_dev', connector_type='stt', connector_ip='1.1.1.1', client_certificate='xxxxxxxxxxxxxxx', fmt='json', tenant_id=_uuid()): res = self._create_gateway_device( fmt, tenant_id, connector_type=connector_type, connector_ip=connector_ip, client_certificate=client_certificate, name=name) if res.status_int >= 400: raise exc.HTTPClientError(code=res.status_int) gateway_device = self.deserialize(fmt, res) yield gateway_device self._delete(networkgw.GATEWAY_DEVICES, gateway_device[self.dev_resource]['id'])
def service_type(self, name='svc_type', default=True, service_defs=None, do_delete=True): if not service_defs: service_defs = [{ 'service_class': constants.DUMMY, 'plugin': dp.DUMMY_PLUGIN_NAME }] res = self._create_service_type(name, service_defs) if res.status_int >= 400: raise webexc.HTTPClientError(code=res.status_int) svc_type = self.deserialize(res) yield svc_type if do_delete: # The do_delete parameter allows you to control whether the # created network is immediately deleted again. Therefore, this # function is also usable in tests, which require the creation # of many networks. self._delete_service_type(svc_type[self.resource_name]['id'])
def update(self, request, environment_id, body): LOG.debug('Environments:Update <Id: {id}, ' 'Body: {body}>'.format(id=environment_id, body=body)) target = {"environment_id": environment_id} policy.check('update_environment', request.context, target) session = db_session.get_session() environment = session.query(models.Environment).get(environment_id) if VALID_NAME_REGEX.match(str(body['name'])): try: environment.update(body) environment.save(session) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.error(msg) raise exc.HTTPConflict(explanation=msg) else: msg = _('Environment name must contain only alphanumeric ' 'or "_-." characters, must start with alpha') LOG.error(msg) raise exc.HTTPClientError(explanation=msg) return environment.to_dict()
def __call__(self, environ, start_response): """WSGI interface In: - ``environ`` -- dictionary of the received elements - ``start_response`` -- callback to send the headers to the browser Return: - the content to send back to the browser """ local.request.clear() # Create the ``WebOb`` request and response objects # ------------------------------------------------- request = self.create_request(environ) try: request.params, request.url except UnicodeDecodeError: return exc.HTTPClientError()(environ, start_response) response = self.create_response( request, 'text/html' if self.always_html else str(request.accept)) channel_id = request.params.get('_channel') nb = request.params.get('_nb') if channel_id and nb: if environ['wsgi.multiprocess']: response.status = 501 # "Not Implemented" else: comet.channels.connect(channel_id, int(nb), environ['wsgi.input'].file.fileno(), response) return response(environ, start_response) xhr_request = request.is_xhr state = None self.last_exception = None log.set_logger('nagare.application.' + self.name) # Set the dedicated application logger # Create a database transaction for each request with database.session.begin(): try: # Phase 1 # ------- # Test the request validity if not request.path_info: self.on_incomplete_url(request, response) try: state = self.sessions.get_state(request, response, xhr_request) except ExpirationError: self.on_expired_session(request, response) except SessionSecurityError: self.on_invalid_session(request, response) state.acquire() try: root, callbacks = state.get_root() or (self.create_root(), None) except ExpirationError: self.on_expired_session(request, response) except SessionSecurityError: self.on_invalid_session(request, response) self.start_request(root, request, response) if callbacks is None: # New state request.method = request.params.get( '_method', request.method) if request.method not in ('GET', 'POST'): self.on_bad_http_method(request, response) url = request.path_info.strip('/') if url: # If a URL is given, initialize the objects graph with it presentation.init(root, tuple(url.split('/')), None, request.method, request) try: render = self._phase1(root, request, response, callbacks) except CallbackLookupError: render = self.on_callback_lookuperror( request, response, xhr_request) except exc.HTTPException, response: # When a ``webob.exc`` object is raised during phase 1, skip the # phase 2 and use it as the response object pass except Exception: self.last_exception = (request, sys.exc_info()) response = self.on_exception(request, response)