예제 #1
0
    def call(self, *args, **kwargs):
        '''
            Calls the function (named by getattr) of this web service.

            Accepts dictionaries and/or TObjs as arguments or keyword arguments.
            Argument names and/or TObj sub-types can be set or overridden using
            the names given as keywords.
        '''
        import httplib as http              # to use its constants
        arglist = []                        # collect arguments here
        for arg in args:                    # std args
            if isinstance(arg, TObj):       # convert TObj to dictionary first
                arg = arg.__get_dict__(wrap=True)
            arglist.append(arg)
        argcount = len(arglist)             # record pos, for non-TObj below

        for kwname in kwargs:               # collect any keyword args
            kwvals = kwargs[kwname]
            if type(kwvals) != list: kwvals = [kwvals] # if not list create one
            for item in kwvals:
                if isinstance(item, TObj):  # convert to dictionary
                    item = item.__get_dict__()
                elif type(item) is bool:
                    item=str(item).lower()  # Java CM wants bool lowercase
                elif type(item) is dict:
                    for key in item:        # "
                        if type(item[key]) is bool:
                            item[key] = str(item[key]).lower()

                if str(item).isdigit():     # start if again, ints first
                    arglist.insert(argcount, {kwname:item})
                else:
                    arglist.append( {kwname:item} )

        log.info( '%s %s.%s%s' % (self.parent.api_vers, self.service,
            self.functionname, tuple(arglist)) )
        try:        # POST query
            response = soaplib.post(
                self.parent.baseurl + self.service,                 # url
                function='%s:%s' % (self.parent.nspace, self.functionname),#func
                xmlns=self.parent.namespace,                        # xmlns
                soapargs=arglist,                                   # soapargs
                authstr=self.parent.authstr,                        # authstr
                addheaders=[],                                      #prvnt issue
                debug=log.isEnabledFor(logging.DEBUG) ) # Don't create debug txt
                                                        # if it won't be used.
        except IOError, e:
            log.error('%s: %s', e.__class__.__name__, e)
            raise IOError, e
예제 #2
0
    def upload_file(self, filenames, network, chunked=True, subfolder='',
        upload_method='PUT', upload_type='auto'):
        '''
            Convenience function to upload files to this Content Manager.

            Argument:
                filenames           - A single or list of filenames to upload.
                network             - The Scala Network to upload to.
            Options:
                subfolder           - Place files in this subfolder.
                upload_method       - Which HTTP method to use to upload.
                                        "PUT"
                                        "POST" - not fully working yet.
                upload_type         - Upload type, e.g. media|maintenance|auto
                chunked             - Enable chunked transfer encoding on larger
                                      files.
            Returns
                mediaIds            - List of MediaItem id numbers of the files.
                                      If not found available, returns the file
                                      upload id instead.
            Example:
                # See the cm_upload.py script for a general solution.
                fileId = cm.upload_file('pow123.png', 'SCALA_CUSTOMER')[0]
        '''
        if type(filenames) is not list: filenames = [filenames]
        fileIds = []
        for filename in filenames:
            if not os.access(filename, os.R_OK):
                errstr = 'File "%s" cannot be accessed.' % filename
                log.error(errstr)
                raise IOError, errstr
            else:
                log.info('filename: "%s"' % filename )
                basename = os.path.basename(filename)
                # decide on a file type
                if upload_type.lower() == 'auto':
                    if os.path.splitext(basename)[1].lower() in ['.bat', '.cmd',
                        '.py', '.vbs', '.exe']:
                                            upload_type = 'MAINTENANCE'
                    else:                   upload_type = 'MEDIA'
                else:  upload_type = upload_type.upper()

                # Request an upload
                # -----------------------------------------------------------
                path = '/content'
                if subfolder: path = '%s/%s' % (path, subfolder)
                robj = TObj(filename=basename,
                    type=upload_type, path=path, size=os.path.getsize(filename))
                try:  # One error here, we should quit
                    uploadTO = self.uploadfile.requestUpload(arg0=robj)[0]
                except Exception, e:
                    log.error(str(e))
                    raise type(e), e

                fileId = uploadTO.mediaItemId or uploadTO.fileId # new attribute
                uploadAs = uploadTO.uploadAsFilename
                log.debug('as id#:%s - %s,' % (fileId, uploadAs))

                # Now, upload file
                # -----------------------------------------------------------
                import httplib as http  # use constants
                if upload_method == 'POST':
                    posturl = self.baseurl_orig + 'servlet/uploadFile'
                    try:
                        response = soaplib.post(posturl, filename=basename,
                            addheaders=[ ('filenameWithPath',
                            '%s%s/%s' % (network, path, uploadAs) ) ],
                            authstr=self.authstr, debug=self.debug)
                    except Exception, e:
                        log.error('%s: %s' % (type(e), e) )
                        raise e

                    if response[0] == http.OK:
                        log.debug('Uploaded.')
                    else:
                        errstr = 'file not uploaded: %s %s' % (
                            response[0], response[1])
                        log.error(errstr)
                        raise Exception, errstr

                elif upload_method.startswith('PUT'):
                    desturl = '%sdata/webdav/%s%s/%s' % (
                        self.baseurl_orig, network, path, uploadAs)
                    try:  # response is a tuple (code, abstract, document)
                        response = soaplib.put(filename, desturl,
                            authstr=self.authstr, chunked=chunked, debug=self.debug)
                    except Exception, e:
                        log.error(str(e))
                        raise e