Esempio n. 1
0
    def PUT(self, env, start_response):
        """ Handle Container update and create request """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)

        exists, headers, body = check_resource(env, 'HEAD', path,
                                               self.logger, False)

        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if (content_type.find('application/directory') < 0 and
                self.object_name):
                return get_err_response('Conflict')
        else:
            res = self._check_parent(env, start_response)
            if res:
                return res

        req = Request(env)
        req.headers['content-type'] = 'application/directory'
        req.headers['content-length'] = '0'
        req.body = ''
        res = req.get_response(self.app)
        return res
    def PUT(self, env, start_response):
        """ Handle Container update and create request """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)

        exists, headers, body = check_resource(env, 'GET', path, self.logger,
                                               False)

        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if (content_type.find('application/directory') < 0
                    and self.object_name):
                return get_err_response('Conflict')
        else:
            res = self._check_parent(env, start_response)
            if res:
                return res

        req = Request(env)
        req.headers['content-type'] = 'application/directory'
        req.headers['content-length'] = '0'
        req.body = ''
        res = req.get_response(self.app)
        return res
Esempio n. 3
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
    def __call__(self, environ, start_response):
        
        # Before we go any further, gzip is hard to parse, don't ask for it
        del environ['HTTP_ACCEPT_ENCODING']
        
        request = Request(environ)

        if request.method == "POST":
            NotImplemented
            valid = captcha in self.valid_captchas
            params = urllib.urlencode(request.POST)
            post = request.POST.copy()
            post['isHuman'] = valid
            request.body = urllib.urlencode(post)
        
        response = request.get_response(self.app)
        
        # We don't want to deal with images and the like
        if response.content_type == 'text/html':
            try:
                parsed = html.fromstring(response.body)
            except (XMLSyntaxError, TypeError):
                return response(environ, start_response)
            response.body = html.tostring(parsed)
        
        NotImplemented
        
        return response(environ, start_response)
Esempio n. 5
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
Esempio n. 6
0
    def test_request_post_redirect(self):
        environ = {'wsgi.input': StringIO('')}
        req=Request(environ)
        req.method = 'POST'
        req.body='dbformpage_d:name=a'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        r = self.widget(redirect="/foo").request(req)
        assert( r.status_int == 302 and r.location=="/foo" )
Esempio n. 7
0
    def test_request_post_valid(self):
        environ = {'wsgi.input': StringIO('')}
        req=Request(environ)
        req.method = 'POST'
        req.body='dblistform_d:0:name=a&dblistform_d:0:id=1'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        r = self.widget().request(req)
        assert r.body == """Form posted successfully [{'id': 1, 'name': u'a'}]""", r.body
    def __call__(self, environ, start_response):
        # Before we go any further, gzip is hard to parse, don't ask for it
        del environ['HTTP_ACCEPT_ENCODING']
        
        request = Request(environ)

        if request.method == "POST":
            valid = 'isHuman' in request.POST
            if not valid:
                params = urllib.urlencode(request.POST)
                if request.referrer is None:
                    # huh....
                    raise ValueError
                from_page = request.referrer.split("?")[0] + "?" + params
                response = Response(status=302, location=from_page)
                return response(environ, start_response)
            else:
                post = request.POST.copy()
                del post['isHuman']
                request.body = urllib.urlencode(post)
        
        response = request.get_response(self.app)
        
        # We don't want to deal with images and the like
        if response.content_type == 'text/html':
            try:
                parsed = html.fromstring(response.body)
            except (XMLSyntaxError, TypeError):
                return response(environ, start_response)
            forms = parsed.xpath("//form")
            index = 0

            for form in forms:
                if form.method.upper() == "GET":
                    continue
                try:
                    tags = [child for child in form.iterdescendants() if child.tag=='input']
                    submit = tags[-1] # maybe?
                except IndexError:
                    # Empty forms are weird.
                    continue
                
                box_id = "captcha%d" % index
                index += 1
                checkbox = Element("input", type="checkbox", name="isHuman", value="1", id=box_id)
                label = Element("label", attrib={'for':box_id})
                label.text = "I am a human"

                submit.addprevious(checkbox)
                submit.addprevious(label)
            response.body = html.tostring(parsed)

        return response(environ, start_response)
Esempio n. 9
0
    def test_request_post_counts_update(self):
        environ = {'wsgi.input': StringIO('')}
        req=Request(environ)
        req.method = 'POST'
        req.body='dblistform_d:0:name=a&dblistform_d:0:id=1&dblistform_d:1:name=b&dblistform_d:1:id=2'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        assert(self.DbTestCls1.query.count() == 2)
        r = self.widget().request(req)
        assert(self.DbTestCls1.query.count() == 2)
Esempio n. 10
0
    def test_request_post_valid(self):
        environ = {'wsgi.input': StringIO(''),
                   }
        req=Request(environ)
        req.method = 'POST'
        req.body='mytestwidget:field1=a&mytestwidget:field2=b&mytestwidget:field3=c'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        r = self.widget().request(req)
        assert (
            r.body == """Form posted successfully {'field2': 'b', 'field3': 'c', 'field1': 'a'}""" or
            r.body == """Form posted successfully {'field2': u'b', 'field3': u'c', 'field1': u'a'}"""
            ), r.body
Esempio n. 11
0
    def _test_request_post_content_update(self):
        environ = {'wsgi.input': StringIO('')}
        req=Request(environ)
        req.method = 'POST'
        req.body='dblistform_d:0:name=b&dblistform_d:0:id=1'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        original = self.DbTestCls1.query.filter(self.DbTestCls1.id==1).one()
        assert(original.name == 'foo1')
        r = self.widget().request(req)
        updated = self.DbTestCls1.query.filter(self.DbTestCls1.id=='1')
        assert(updated.count() == 1)
        updated = updated.one()
        assert(updated.name == 'b')
Esempio n. 12
0
    def test_no_query_property(self):
        old_prop = self.widget.entity.query
        self.widget.entity.query = None

        environ = {'wsgi.input': StringIO('')}
        req=Request(environ)
        req.method = 'POST'
        req.body='dbformpage_d:name=a'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

        self.mw.config.debug = True
        try:
            r = self.widget().request(req)
            assert False
        except AttributeError, e:
            print e
            assert(str(e) == 'entity has no query_property()')
Esempio n. 13
0
    def _reboot(self, req, request_data, *parts):
        """
        Handle the machine reboot request
        """
        data = {}
        force = request_data.get('force', False)
        if isinstance(force, str):
            force = 'HARD' if force.lower() == 'true' else 'SOFT'
        else:
            force = 'HARD' if force else 'SOFT'
        data['reboot'] = {'type': force}
        env = self._fresh_env(req)
        env['PATH_INFO'] = concat(self.os_path, '/', parts[0], '/action')
        env['CONTENT_TYPE'] = 'application/json'
        new_req = Request(env)
        new_req.body = json.dumps(data)
        res = new_req.get_response(self.app)

        return res
Esempio n. 14
0
def app(environ, start_response):
    try:
        request = Request(environ)
        response = Response()

        if len(request.body) == 0:
            try:
                request.body = sys.argv[1]
            except:
                response.status = 400 # Bad Request
                response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
                response.body = str(NoApplicableCode('No query string found.'))
                return response(environ, start_response)
    
        wps = pywps.Pywps(request.method)

        if wps.parseRequest(request.body):
#            pywps.debug(wps.inputs)
            response_msg = wps.performRequest()
            # request performed, write the response back
            if response_msg:
                response.status = 200 # OK
                response.headerlist = [('Content-Type', wps.request.contentType),]
                response.body = response_msg
#                pywps.response.response(wps.response,
#                    sys.stdout, wps.parser.soapVersion, wps.parser.isSoap,
#                    wps.parser.isSoapExecute, wps.request.contentType)
                    
    except WPSException as e:
        traceback.print_exc(file=pywps.logFile)
        response.status = 400 # Bad Request
        response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
        response.body = str(e)
#        pywps.response.response(e, sys.stdout, wps.parser.soapVersion,
#                                wps.parser.isSoap,
#                                wps.parser.isSoapExecute)
    except Exception as e:
        traceback.print_exc(file=pywps.logFile)
        response.status = 500 # Internal Server Error
        response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
        response.body = str(NoApplicableCode(e.message))
    
    return response(environ, start_response)
Esempio n. 15
0
    def PUT(self, env, start_response):
        """
        Handle Container update and create request
        """
        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)
        exists, headers, body = check_resource(env, 'HEAD', path, self.logger,
                                               False, None)
        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if content_type.find('application/directory') >= 0:
                return get_err_response('Conflict')
        else:
            path = '/' + concat_parts('v1', self.account_name,
                                      self.container_name)
            query_string = 'delimiter=/&prefix=' + \
                concat_parts(self.parent_name, self.object_name) + '/'
            parent_exists, dummy, body = check_resource(env, 'GET', path,
                                                        self.logger, True,
                                                        query_string)
            if parent_exists:
                try:
                    children = json.loads(body)
                    if len(children) > 0:
                        # No children under, no resource exist
                        return get_err_response('Conflict')
                except ValueError:
                    return get_err_response('InconsistantState')
            else:
                return get_err_response('NoParentContainer')

        # Check if the parent is OK. it should be either a real directory or
        # a virtual directory
        res = self._check_parent(env, start_response)
        if res:
            return res

        # Create a new WebOb Request object according to the current request
        req = Request(env)

        metadata = {}
        if req.body:
            try:
                body = json.loads(req.body)
            except ValueError:
                return get_err_response('InvalidContent')

            if body.get('metadata'):
                metadata = body['metadata']
                for key in metadata:
                    if metadata[key] == '':
                        req.headers[Consts.META_OBJECT_ID + key] = ''
                    else:
                        req.headers[Consts.META_OBJECT_ID + key] = \
                            key + ":" + str(metadata[key])
            else:
                metadata = {}

            try:
                req.body = str(body.get('value', ''))
                req.headers['content-type'] = body.get('mimetype',
                                                       'text/plain')
                req.headers[Consts.VALUE_ENCODING] = \
                    body.get('valuetransferencoding', 'utf-8')
            except KeyError:
                return get_err_response('InvalidContent')
        else:
            req.headers['content-length'] = '0'

        res = req.get_response(self.app)

        # Deal with the response now.
        # Build the response message body according to CDMI specification
        # If the response status is 201, then we know we have successfully
        # created the object. According to CDMI spec, only send response body
        # when creating new object.
        if res.status_int == 201:
            body = {}
            body['objectType'] = Consts.CDMI_APP_OBJECT
            body['objectName'] = self.object_name
            body['parentURI'] = concat_parts(self.account_name,
                                             self.container_name,
                                             self.parent_name) + '/'
            body['completionStatus'] = 'Complete'
            body['metadata'] = metadata
            res.body = json.dumps(body, indent=2)
        # Otherwise, no response body should be returned.
        else:
            res.body = ''

        return res
Esempio n. 16
0
    def PUT(self, env, start_response):
        """
        Handle Container update and create request
        """
        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)
        exists, headers, body = check_resource(env, 'GET', path, self.logger,
                                               False, None)
        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if content_type.find('application/directory') >= 0:
                return get_err_response('Conflict')
        else:
            path = '/' + concat_parts('v1', self.account_name,
                                      self.container_name)
            query_string = 'delimiter=/&prefix=' + \
                concat_parts(self.parent_name, self.object_name) + '/'
            parent_exists, dummy, body = check_resource(env, 'GET', path,
                                                        self.logger, True,
                                                        query_string)
            if parent_exists:
                try:
                    children = json.loads(body)
                    if len(children) > 0:
                        # No children under, no resource exist
                        return get_err_response('Conflict')
                except ValueError:
                    return get_err_response('InconsistantState')
            else:
                return get_err_response('NoParentContainer')

        # Check if the parent is OK. it should be either a real directory or
        # a virtual directory
        res = self._check_parent(env, start_response)
        if res:
            return res

        # Create a new WebOb Request object according to the current request
        #if we found X-Object-UploadID in the header, we need know that
        #the request is uploading a piece of a large object, the piece
        #will need to go to the segments folder

        try:
            self._handle_part(env)
        except Exception as ex:
            return get_err_response(ex.message)

        req = Request(env)

        metadata = {}
        if req.body:
            try:
                body = self._handle_body(env, True)
            except Exception:
                return get_err_response('InvalidBody')

            # headling copy object
            if body.get('copy'):
                # add the copy-from header to indicate a copy operation
                # for swift
                req.headers['X-Copy-From'] = body.get('copy')
                req.body = ''
            else:
                if body.get('metadata'):
                    metadata = body['metadata']
                    for key in metadata:
                        if metadata[key] == '':
                            req.headers[Consts.META_OBJECT_ID + key] = ''
                        else:
                            req.headers[Consts.META_OBJECT_ID + key] = \
                                key + ":" + str(metadata[key])
                else:
                    metadata = {}

                try:
                    req.body = str(body.get('value', ''))
                    req.headers['content-type'] = body.get('mimetype',
                        'text/plain').lower()
                    encoding = body.get('valuetransferencoding', 'utf-8')
                    req.headers[Consts.VALUE_ENCODING] = encoding
                    # if the value is encoded using base64, then
                    # we need to decode it and save as binary
                    if encoding == Consts.ENCODING_BASE64:
                        req.body = base64.decodestring(req.body)
                except KeyError:
                    return get_err_response('InvalidContent')
        else:
            req.headers['content-length'] = '0'

        res = req.get_response(self.app)

        # Deal with the response now.
        # Build the response message body according to CDMI specification
        # If the response status is 201, then we know we have successfully
        # created the object. According to CDMI spec, only send response body
        # when creating new object.
        if res.status_int == 201:
            body = {}
            body['objectType'] = Consts.CDMI_APP_OBJECT
            body['objectName'] = self.object_name
            body['parentURI'] = '/'.join(['', self.cdmi_root,
                                          self.account_name,
                                          self.container_name,
                                          self.parent_name, ''])

            body['capabilitiesURI'] = '/'.join(['', self.cdmi_root,
                                               self.account_name,
                                               self.cdmi_capability_id,
                                               'dataobject/'])

            if env.get('HTTP_X_USE_EXTRA_REQUEST'):
                extra_res = self._put_manifest(env)
                res.status_int = extra_res.status

            body['metadata'] = metadata
            res.body = json.dumps(body, indent=2)
        # Otherwise, no response body should be returned.
        else:
            res.body = ''

        return res
    def PUT(self, env, start_response):
        """ Handle non-CDMI Object update and create request. """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)

        exists, headers, body = check_resource(env, 'GET', path, self.logger,
                                               False, None)

        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if content_type.find('application/directory') >= 0:
                return get_err_response('Conflict')
        else:
            path = '/' + concat_parts('v1', self.account_name,
                                      self.container_name)

            query_string = 'delimiter=/&prefix=' + \
                concat_parts(self.parent_name, self.object_name) + '/'

            parent_exists, dummy, body = check_resource(
                env, 'GET', path, self.logger, True, query_string)

            if parent_exists:
                try:
                    children = json.loads(body)
                    if len(children) > 0:
                        #No children under, no resource exist
                        return get_err_response('Conflict')
                except ValueError:
                    return get_err_response('InconsistantState')
            else:
                return get_err_response('NoParentContainer')

        # Check if the parent is OK. it should be either a real directory
        # or a virtual directory
        res = self._check_parent(env, start_response)
        if res:
            return res

        try:
            self._handle_part(env)
        except Exception as ex:
            return get_err_response(ex.message)

        try:
            body = self._handle_body(env, False)
        except Exception as ex:
            return get_err_response('InvalidBody')
        else:
            env['CONTENT_TYPE'] = body.get('mimetype', 'text/plain')
            req = Request(env)
            req.body = body.get('value', '')
            req.headers['content-length'] = len(req.body)
            res = req.get_response(self.app)
            if (res.status_int in [201, 204]
                    and env.get('HTTP_X_USE_EXTRA_REQUEST')):
                extra_res = self._put_manifest(env)
                res.status_int = extra_res.status
            return res
Esempio n. 18
0
    def PUT(self, env, start_response):
        """
        Handle Container update and create request
        """
        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)
        exists, headers, body = check_resource(env, 'GET', path, self.logger,
                                               False, None)
        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if content_type.find('application/directory') >= 0:
                return get_err_response('Conflict')
        else:
            path = '/' + concat_parts('v1', self.account_name,
                                      self.container_name)
            query_string = 'delimiter=/&prefix=' + \
                concat_parts(self.parent_name, self.object_name) + '/'
            parent_exists, dummy, body = check_resource(env, 'GET', path,
                                                        self.logger, True,
                                                        query_string)
            if parent_exists:
                try:
                    children = json.loads(body)
                    if len(children) > 0:
                        # No children under, no resource exist
                        return get_err_response('Conflict')
                except ValueError:
                    return get_err_response('InconsistantState')
            else:
                return get_err_response('NoParentContainer')

        # Check if the parent is OK. it should be either a real directory or
        # a virtual directory
        res = self._check_parent(env, start_response)
        if res:
            return res

        # Create a new WebOb Request object according to the current request
        #if we found X-Object-UploadID in the header, we need know that
        #the request is uploading a piece of a large object, the piece
        #will need to go to the segments folder

        try:
            self._handle_part(env)
        except Exception as ex:
            return get_err_response(ex.message)

        req = Request(env)

        metadata = {}
        if req.body:
            try:
                body = self._handle_body(env, True)
            except Exception:
                return get_err_response('InvalidBody')

            # headling copy object
            if body.get('copy'):
                # add the copy-from header to indicate a copy operation
                # for swift
                req.headers['X-Copy-From'] = body.get('copy')
                req.body = ''
            else:
                if body.get('metadata'):
                    metadata = body['metadata']
                    for key in metadata:
                        if metadata[key] == '':
                            req.headers[Consts.META_OBJECT_ID + key] = ''
                        else:
                            req.headers[Consts.META_OBJECT_ID + key] = \
                                key + ":" + str(metadata[key])
                else:
                    metadata = {}

                try:
                    req.body = str(body.get('value', ''))
                    req.headers['content-type'] = body.get('mimetype',
                        'text/plain').lower()
                    encoding = body.get('valuetransferencoding', '7BIT')
                    req.headers[Consts.VALUE_ENCODING] = encoding
                    # if the value is encoded using base64, then
                    # we need to decode it and save as binary
                    if encoding == Consts.ENCODING_BASE64:
                        req.body = base64.decodestring(req.body)
                except KeyError:
                    return get_err_response('InvalidContent')
        else:
            req.headers['content-length'] = '0'

        res = req.get_response(self.app)

        # Deal with the response now.
        # Build the response message body according to CDMI specification
        # If the response status is 201, then we know we have successfully
        # created the object. According to CDMI spec, only send response body
        # when creating new object.
        if res.status_int == 201:
            body = {}
            body['objectType'] = Consts.CDMI_APP_OBJECT
            body['objectName'] = self.object_name
            if self.parent_name:
                body['parentURI'] = '/'.join(['', self.cdmi_root,
                                          self.account_name,
                                          self.container_name,
                                          self.parent_name, ''])
            else:
                body['parentURI'] = '/'.join(['', self.cdmi_root,
                                          self.account_name,
                                          self.container_name, ''])

            body['capabilitiesURI'] = '/'.join(['', self.cdmi_root,
                                               self.account_name,
                                               self.cdmi_capability_id,
                                               'dataobject/'])

            if env.get('HTTP_X_USE_EXTRA_REQUEST'):
                extra_res = self._put_manifest(env)
                res.status_int = extra_res.status

            body['metadata'] = metadata
            res.body = json.dumps(body, indent=2)
        # Otherwise, no response body should be returned.
        else:
            res.body = ''

        return res
Esempio n. 19
0
    def PUT(self, env, start_response):
        """
        Handle Container update and create request
        """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)
        exists, headers, dummy = check_resource(env, 'GET', path,
                                                self.logger, False)
        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if (content_type.find('application/directory') < 0 and
                self.object_name):
                return get_err_response('Conflict')
        # Not a top container, so it has to be virtual container
        else:
            res = self._check_parent(env, start_response)
            if res:
                return res

        # Create a new WebOb Request object according to the current request
        req = Request(env)

        # We are creating a container, set the content-type to be
        # application/directory
        req.headers['content-type'] = 'application/directory'

        metadata = {}
        if req.body:
            try:
                body = json.loads(req.body)
            except ValueError:
                return get_err_response('InvalidContent')

            metadata = body.get('metadata')
            if metadata:
                for key in metadata:
                    if metadata[key] == '':
                        req.headers[self.metadata_prefix + key] = ''
                    else:
                        req.headers[self.metadata_prefix + key] = \
                            key + ":" + str(metadata[key])
            else:
                metadata = {}

        # Now set the body to be empty and content-length to 0
        req.body = ''
        req.headers['Content-Length'] = 0

        res = req.get_response(self.app)

        # Deal with the response now.
        # Build the response message body according to CDMI specification
        # if the response status is 201, then we know we have successfully
        # created the container. According to CDMI spec, only send response
        # body when creating new container
        if res.status_int == 201:
            body = {}
            body['objectType'] = Consts.CDMI_APP_CONTAINER
            body['objectName'] = (self.object_name + '/') if self.object_name \
                else (self.container_name + '/')
            if self.object_name:
                body['parentURI'] = '/'.join(['', self.cdmi_root,
                                              self.account_name,
                                              self.container_name,
                                              self.parent_name, ''])
            else:
                body['parentURI'] = '/'.join(['', self.cdmi_root,
                                              self.account_name, ''])

            body['capabilitiesURI'] = '/'.join(['', self.cdmi_root,
                                                self.account_name,
                                                self.cdmi_capability_id,
                                                'container/'])
            body['completionStatus'] = 'Complete'
            body['metadata'] = metadata
            res.body = json.dumps(body, indent=2)
        # Otherwise, no body should be returned.
        else:
            res.body = ''

        return res
# {'METHOD': 'GET'}
req_environ=req.environ
#pprint(req.environ)
# 'GET'
req_method=req.method
#pprint(req.method)
#
req_dir=dir(req)
# req
# <Request at 0x27cd9e8 (invalid WSGI environ)>

req=Request.blank('/article?id=1&id=2')
pprint(req.environ)

# demo for request body
req.body='This is a request body'

req.path_info_peek()
req.path_info_pop()
req.script_name

# Headers
req.headers['Content-Type'] = 'application/x-www-urlencoded'
req.headers.items()
req.environ['CONTENT_TYPE']

# Query & POST
req = Request.blank('/test?check=a&check=b&name=Bob')
req.GET
req.GET['check']
req.GET.getall('check')
    def PUT(self, env, start_response):
        """ Handle non-CDMI Object update and create request. """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)

        exists, headers, body = check_resource(env, 'GET', path, self.logger,
                                               False, None)

        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if content_type.find('application/directory') >= 0:
                return get_err_response('Conflict')
        else:
            path = '/' + concat_parts('v1', self.account_name,
                                      self.container_name)

            query_string = 'delimiter=/&prefix=' + \
                concat_parts(self.parent_name, self.object_name) + '/'

            parent_exists, dummy, body = check_resource(env, 'GET', path,
                                                        self.logger, True,
                                                        query_string)

            if parent_exists:
                try:
                    children = json.loads(body)
                    if len(children) > 0:
                        #No children under, no resource exist
                        return get_err_response('Conflict')
                except ValueError:
                    return get_err_response('InconsistantState')
            else:
                return get_err_response('NoParentContainer')

        # Check if the parent is OK. it should be either a real directory
        # or a virtual directory
        res = self._check_parent(env, start_response)
        if res:
            return res

        try:
            self._handle_part(env)
        except Exception as ex:
            return get_err_response(ex.message)

        try:
            body = self._handle_body(env, False)
        except Exception as ex:
            return get_err_response('InvalidBody')
        else:
            env['CONTENT_TYPE'] = body.get('mimetype', 'text/plain')
            req = Request(env)
            req.body = body.get('value', '')
            req.headers['content-length'] = len(req.body)
            res = req.get_response(self.app)
            if (res.status_int in [201, 204] and
                env.get('HTTP_X_USE_EXTRA_REQUEST')):
                extra_res = self._put_manifest(env)
                res.status_int = extra_res.status
            return res
Esempio n. 22
0
# {'METHOD': 'GET'}
req_environ = req.environ
#pprint(req.environ)
# 'GET'
req_method = req.method
#pprint(req.method)
#
req_dir = dir(req)
# req
# <Request at 0x27cd9e8 (invalid WSGI environ)>

req = Request.blank('/article?id=1&id=2')
pprint(req.environ)

# demo for request body
req.body = 'This is a request body'

req.path_info_peek()
req.path_info_pop()
req.script_name

# Headers
req.headers['Content-Type'] = 'application/x-www-urlencoded'
req.headers.items()
req.environ['CONTENT_TYPE']

# Query & POST
req = Request.blank('/test?check=a&check=b&name=Bob')
req.GET
req.GET['check']
req.GET.getall('check')
Esempio n. 23
0
    def PUT(self, env, start_response):
        """
        Handle Container update and create request
        """

        # First check if the resource exists and if it is a directory
        path = '/' + concat_parts('v1', self.account_name, self.container_name,
                                  self.parent_name, self.object_name)
        exists, headers, dummy = check_resource(env, 'HEAD', path,
                                                self.logger, False)
        if exists:
            content_type = headers.get('content-type', '')
            content_type = content_type.lower() if content_type else ''
            if (content_type.find('application/directory') < 0 and
                self.object_name):
                return get_err_response('Conflict')
        # Not a top container, so it has to be virtual container
        else:
            res = self._check_parent(env, start_response)
            if res:
                return res

        # Create a new WebOb Request object according to the current request
        req = Request(env)

        # We are creating a container, set the content-type to be
        # application/directory
        req.headers['content-type'] = 'application/directory'

        metadata = {}
        if req.body:
            try:
                body = json.loads(req.body)
            except ValueError:
                return get_err_response('InvalidContent')

            metadata = body.get('metadata')
            if metadata:
                for key in metadata:
                    if metadata[key] == '':
                        req.headers[self.metadata_prefix + key] = ''
                    else:
                        req.headers[self.metadata_prefix + key] = \
                            key + ":" + str(metadata[key])
            else:
                metadata = {}

        # Now set the body to be empty and content-length to 0
        req.body = ''
        req.headers['Content-Length'] = 0

        res = req.get_response(self.app)

        # Deal with the response now.
        # Build the response message body according to CDMI specification
        # if the response status is 201, then we know we have successfully
        # created the container. According to CDMI spec, only send response
        # body when creating new container
        if res.status_int == 201:
            body = {}
            body['objectType'] = Consts.CDMI_APP_CONTAINER
            body['objectName'] = self.object_name if self.object_name else \
                self.container_name
            if self.object_name:
                body['parentURI'] = concat_parts(self.account_name,
                                                 self.container_name,
                                                 self.parent_name) + '/'
            else:
                body['parentURI'] = self.account_name + '/'
            body['completionStatus'] = 'Complete'
            body['metadata'] = metadata
            res.body = json.dumps(body, indent=2)
        # Otherwise, no body should be returned.
        else:
            res.body = ''

        return res
Esempio n. 24
0
    def POST(self, req, *parts):
        """
        Handle POST machineVolumeCollection request which will attach an volume
        """
        try:
            request_data = get_request_data(req.body, self.req_content_type)
        except Exception as error:
            return get_err_response('MalformedBody')

        if request_data:
            data = request_data.get('body').get('MachineVolume')
            if not data:
                data = request_data.get('body')
            if data:

                volume_url = data.get('volume', {}).get('href')
                if volume_url:
                    volume_id = volume_url.strip('/').split('/')[-1]
                else:
                    return get_err_response('MalformedBody')

                device = data.get('initialLocation')
                if not device:
                    return get_err_response('MalformedBody')

                reqdata = {}
                reqdata['volumeAttachment'] = {'volumeId': volume_id,
                                            'device': device}
                env = self._fresh_env(req)
                env['PATH_INFO'] = concat(self.os_path, '/', parts[0],
                                          '/os-volume_attachments')
                env['CONTENT_TYPE'] = 'application/json'
                new_req = Request(env)
                new_req.body = json.dumps(reqdata)
                res = new_req.get_response(self.app)
                if res.status_int == 200:
                    data = json.loads(res.body).get('volumeAttachment')
                    attach_id = data.get('id')
                    server_id = data.get('serverId')
                    volume_id = data.get('volumeId')

                    body = {}
                    match_up(body, data, 'initialLocation', 'device')

                    body['id'] = concat(self.tenant_id, '/machinevolume/',
                                        server_id, '/', attach_id)
                    location = '/'.join([self.request_prefix, body['id']])

                    body['volume'] = {'href': concat(self.tenant_id,
                                                    '/volume/', volume_id)}

                    # deal with volume attach operations
                    operations = []
                    operations.append(self._create_op('edit', body['id']))

                    operations.append(self._create_op('delete', body['id']))
                    body['operations'] = operations
                    body['state'] = 'ATTACHING'

                    if self.res_content_type == 'application/xml':
                        response_data = {'MachineVolume': body}
                    else:
                        body['resourceURI'] = concat(self.uri_prefix,
                                                    '/MachineVolume')
                        response_data = body

                    new_content = make_response_data(response_data,
                                                 self.res_content_type,
                                                 self.machine_volume_metadata,
                                                 self.uri_prefix)
                    resp = Response()
                    self._fixup_cimi_header(resp)
                    resp.headers['Content-Type'] = self.res_content_type
                    resp.headers['Location'] = location
                    resp.status = 201
                    resp.body = new_content
                    return resp
                else:
                    return res

            else:
                return get_err_response('BadRequest')
        else:
            return get_err_response('BadRequest')
Esempio n. 25
0
 def POST(self):
     req = WebRequest(self.env)
     req.method = "POST"
     req.body = self.input_data
     return req.POST