Python pycurl.FORM_FILE Examples

The following are 7 code examples of pycurl.FORM_FILE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pycurl , or try the search function .
Example #1
Source File: client.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def add_file(self, fieldname, pathname, mimetype=None, filename=None):
        """Add a file section.

        The file will be uploaded. You must use the full path name.

        Args:
            fieldname:  name of the form field.
             pahtname:  Full path to the file.
             mimetype:  Override the auto-detected mime type.
             filename:  Override the base name of the given pathname.
        """
        plist = [pycurl.FORM_FILE, pathname]
        if mimetype:
            plist.append(pycurl.FORM_CONTENTTYPE)
            plist.append(mimetype)
        if filename:
            plist.append(pycurl.FORM_FILENAME)
            plist.append(filename)
        if fieldname in self:
            dict.__setitem__(self, fieldname, self[fieldname] + tuple(plist))
        else:
            dict.__setitem__(self, fieldname, tuple(plist)) 
Example #2
Source File: smgr_upload_image.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def send_REST_request(ip, port, payload, file_name,
                      kickstart='', kickseed=''):
    try:
        response = StringIO()
        headers = ["Content-Type:application/json"]
        url = "http://%s:%s/image/upload" %(
            ip, port)
        conn = pycurl.Curl()
        conn.setopt(pycurl.URL, url)
        conn.setopt(pycurl.POST, 1)
        payload["file"] = (pycurl.FORM_FILE, file_name)
        if kickstart:
            payload["kickstart"] = (pycurl.FORM_FILE, kickstart)
        if kickseed:
            payload["kickseed"] = (pycurl.FORM_FILE, kickseed)
        conn.setopt(pycurl.HTTPPOST, payload.items())
        conn.setopt(pycurl.CUSTOMREQUEST, "PUT")
        conn.setopt(pycurl.WRITEFUNCTION, response.write)
        conn.perform()
        return response.getvalue()
    except:
        return None 
Example #3
Source File: hub.py    From robot with MIT License 6 votes vote down vote up
def upload_file(self, path):
        """ 上传文件

        :param path: 文件路径
        """
        img_host = "http://dimg.vim-cn.com/"
        curl, buff = self.generate_curl(img_host)
        curl.setopt(pycurl.POST, 1)
        curl.setopt(pycurl.HTTPPOST, [('name', (pycurl.FORM_FILE, path)), ])
        try:
            curl.perform()
            ret = buff.getvalue()
            curl.close()
            buff.close()
        except:
            logger.warn(u"上传图片错误", exc_info=True)
            return u"[图片获取失败]"
        return ret 
Example #4
Source File: packagemanagerservicejson.py    From pyaem with MIT License 6 votes vote down vote up
def upload_package(self, group_name, package_name, package_version, file_path, **kwargs):

        file_name = '{0}-{1}.zip'.format(package_name, package_version)

        params = {
            'cmd': 'upload',
            'package': (pycurl.FORM_FILE, '{0}/{1}'.format(file_path.rstrip('/'), file_name))
        }

        opts = {
            'file_name': file_name
        }

        url = '{0}/crx/packmgr/service/.json/'.format(self.url)
        params = dict(params.items() + kwargs.items())
        _handlers = self.handlers
        opts = dict(self.kwargs.items() + opts.items())

        return bag.upload_file(url, params, _handlers, **opts) 
Example #5
Source File: packagemanagerservicehtml.py    From pyaem with MIT License 6 votes vote down vote up
def upload_package(self, group_name, package_name, package_version, file_path, **kwargs):

        file_name = '{0}-{1}.zip'.format(package_name, package_version)

        params = {
            'cmd': 'upload',
            'package': (pycurl.FORM_FILE, '{0}/{1}'.format(file_path, file_name))
        }

        opts = {
            'file_name': file_name
        }

        url = '{0}/crx/packmgr/service/script.html/'.format(self.url)
        params = dict(params.items() + kwargs.items())
        _handlers = self.handlers
        opts = dict(self.kwargs.items() + opts.items())

        return bag.upload_file(url, params, _handlers, **opts) 
Example #6
Source File: webconsole.py    From pyaem with MIT License 5 votes vote down vote up
def install_bundle(self, bundle_name, bundle_version, file_path, **kwargs):

        def _handler_ok_install(response, **kwargs):

            message = 'Bundle {0} installed'.format(kwargs['bundle_name'])
            result = res.PyAemResult(response)
            result.success(message)
            return result

        file_name = '{0}-{1}.jar'.format(bundle_name, bundle_version)

        params = {
            'action': 'install',
            'bundlefile': (pycurl.FORM_FILE, '{0}/{1}'.format(file_path.rstrip('/'), file_name))
        }

        _handlers = {
            200: _handler_ok_install,
            201: _handler_ok_install
        }

        opts = {
            'bundle_name': bundle_name
        }

        url = '{0}/system/console/bundles'.format(self.url)
        params = dict(params.items() + kwargs.items())
        _handlers = dict(self.handlers.items() + _handlers.items())
        opts = dict(self.kwargs.items() + opts.items())

        return bag.upload_file(url, params, _handlers, **opts) 
Example #7
Source File: smgr_upload_image.py    From contrail-server-manager with Apache License 2.0 4 votes vote down vote up
def take_action(self, parsed_args):
        try:
            self.smgr_ip = self.smgr_port = None
            smgr_dict = self.app.get_smgr_config()

            if smgr_dict["smgr_ip"]:
                self.smgr_ip = smgr_dict["smgr_ip"]
            else:
                self.app.report_missing_config("smgr_ip")
            if smgr_dict["smgr_port"]:
                self.smgr_port = smgr_dict["smgr_port"]
            else:
                self.app.report_missing_config("smgr_port")
        except Exception as e:
            sys.exit("Exception: %s : Error getting smgr config" % e.message)

        try:
            image_id = getattr(parsed_args, "id", None)
            image_version = getattr(parsed_args, "version", None)
            image_type = getattr(parsed_args, "type", None)
            image_category = getattr(parsed_args, "category", None)
            openstack_sku = ''
            if getattr(parsed_args, "openstack_sku", None):
                openstack_sku = getattr(parsed_args, "openstack_sku", None)
            kickstart = kickseed = ''
            if getattr(parsed_args, "kickstart", None):
                kickstart = getattr(parsed_args, "kickstart", None)
            # end args.kickstart
            if getattr(parsed_args, "kickseed", None):
                kickseed = getattr(parsed_args, "kickseed", None)
            # end args.kickseed
            file_name = getattr(parsed_args, "file_name", None)
            payload = dict()
            payload['id'] = image_id
            payload['version'] = image_version
            payload['type'] = image_type
            payload['category'] = image_category
            payload["file"] = (pycurl.FORM_FILE, file_name)
            if openstack_sku:
                payload["openstack_sku"] = openstack_sku
            if kickstart:
                payload["kickstart"] = (pycurl.FORM_FILE, kickstart)
            if kickseed:
                payload["kickseed"] = (pycurl.FORM_FILE, kickseed)
            for param in payload:
                if not payload[param]:
                    self.app.stdout.write("\nMissing mandatory parameter: " + str(param) + "\n")
                    sys.exit(0)
            if image_id:
                resp = smgrutils.send_REST_request(self.smgr_ip, self.smgr_port, obj="image/upload",
                                                   payload=payload, method="PUT")
                self.app.stdout.write("\n" + str(smgrutils.print_rest_response(resp)) + "\n")
        except Exception as e:
            sys.exit("Exception: %s : Error uploading image" % e.message)