Request a new package file upload (for creating packages).
197932
def request_file_upload(owner, repo, filepath, md5_checksum=None):
    """"""
    client = get_files_api()
    md5_checksum = md5_checksum or calculate_file_md5(filepath)

    with catch_raise_api_exception():
        data, _, headers = client.files_create_with_http_info(
            owner=owner,
            repo=repo,
            data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum},
        )

    # pylint: disable=no-member
    # Pylint detects the returned value as a tuple
    ratelimits.maybe_rate_limit(client, headers)
    return data.identifier, data.upload_url, data.upload_fields
802798
def _req_files_add(self, pid, cname):
        
        url = self.web_api_url + '/add'
        data = locals()
        del data['self']
        req = Request(method='POST', url=url, data=data)
        res = self.http.send(req)
        if res.state:
            return res.content
        else:
            raise RequestFailure('Failed to access files API.')
171095
def upload(self,project, inputtemplate, sourcefile, **kwargs):
        """"""
        return self.addinputfile(project, inputtemplate,sourcefile, **kwargs)
7211
def upload(self, *args, **kwargs):
    """"""
    for job in self.jobs:
      job.upload(*args, **kwargs)
141912
def upload_release(self):
        """"""
        self.before_upload_release()

        with settings(user=self.user):
            with app_bundle():
                local_bundle = env.local_bundle
                env.bundle = '/tmp/' + os.path.basename(local_bundle)
                file_upload(env.bundle, local_bundle)

            # Extract the bundle into a release folder
            current_release_link = self.releases_dir + '/current'
            previous_release_link = self.releases_dir + '/previous'
            release_dir = self.releases_dir + '/' + env.release

            dir_ensure(release_dir)
            with cd(release_dir):
                run('tar -xvf ' + env.bundle)

            # Delete the remote bundle
            run('rm ' + env.bundle)

            # Remove previous release link
            if file_exists(previous_release_link):
                run('rm ' + previous_release_link)

            # Move current to previous
            if file_exists(current_release_link):
                run('mv %s %s' % (current_release_link, previous_release_link))

            # Link the current release
            file_link(release_dir, self.releases_dir + "/current")

            # Install app dependencies
            with cd(current_release_link):
                with prefix('workon ' + self.name):
                    run('pip install -r requirements.txt')

        self.after_upload_release()
1211629
def upload(ctx, check, sdist, dry_run):
    """"""
    if check in get_valid_checks():
        check_dir = os.path.join(get_root(), check)
    else:
        check_dir = resolve_path(check)
        if not dir_exists(check_dir):
            abort('`{}` is not an Agent-based Integration or Python package'.format(check))

        check = basepath(check_dir)

    # retrieve credentials
    pypi_config = ctx.obj.get('pypi', {})
    username = pypi_config.get('user') or os.getenv('TWINE_USERNAME')
    password = pypi_config.get('pass') or os.getenv('TWINE_PASSWORD')
    if not (username and password):
        abort('This requires pypi.user and pypi.pass configuration. Please see `ddev config -h`.')

    auth_env_vars = {'TWINE_USERNAME': username, 'TWINE_PASSWORD': password}
    echo_waiting('Building and publishing `{}` to PyPI...'.format(check))

    with chdir(check_dir, env_vars=auth_env_vars):
        result = build_package(check_dir, sdist)
        if result.code != 0:
            abort(result.stdout, result.code)
        echo_waiting('Uploading the package...')
        if not dry_run:
            result = run_command('twine upload --skip-existing dist{}*'.format(os.path.sep))
            if result.code != 0:
                abort(code=result.code)

    echo_success('Success!')
828070
def make_request(endpoint, **kwargs):
        """"""
        data = kwargs.get('json', [])
        package = kwargs.get('package', None)
        method = kwargs.get('method', 'GET')

        function = getattr(requests, method.lower())

        try:
            if package:
                response = function(endpoint, data=data,
                                    files={'file': package})
            else:
                response = function(endpoint, json=data)
        except requests.exceptions.ConnectionError:
            LOG.error("Couldn't connect to NApps server %s.", endpoint)
            sys.exit(1)

        return response
1203966
def upload_package(context):
    """"""

    if not context.dry_run and build_distributions(context):
        upload_args = 'twine upload '
        upload_args += ' '.join(Path('dist').files())
        if context.pypi:
            upload_args += ' -r %s' % context.pypi

        upload_result = shell.dry_run(upload_args, context.dry_run)
        if not context.dry_run and not upload_result:
            raise Exception('Error uploading: %s' % upload_result)
        else:
            log.info(
                'Successfully uploaded %s:%s', context.module_name, context.new_version
            )
    else:
        log.info('Dry run, skipping package upload')
1066872
def upload(
    ctx, files, max_threads, prompt, forward, reverse, tags, metadata, project_id, coerce_ascii
):
    """"""

    appendables = {}
    if tags:
        appendables["tags"] = []
        for tag in tags:
            appendables["tags"].append(tag)

    if metadata:
        appendables["metadata"] = {}
        for metadata_kv in metadata:
            split_metadata = metadata_kv.split("=", 1)
            if len(split_metadata) > 1:
                metadata_value = split_metadata[1]
                appendables["metadata"][split_metadata[0]] = metadata_value

    appendables = validate_appendables(appendables, ctx.obj["API"])

    if (forward or reverse) and not (forward and reverse):
        click.echo("You must specify both forward and reverse files", err=True)
        ctx.exit(1)

    if forward and reverse:
        if len(files) > 0:
            click.echo(
                "You may not pass a FILES argument when using the "
                " --forward and --reverse options.",
                err=True,
            )
            ctx.exit(1)
        files = [(forward, reverse)]
    elif len(files) == 0:
        click.echo(ctx.get_help())
        return
    else:
        files = list(files)

        # "intelligently" find paired files and tuple them
        paired_files = []
        single_files = set(files)

        for filename in files:
            # convert "read 1" filenames into "read 2" and check that they exist; if they do
            # upload the files as a pair, autointerleaving them
            pair = re.sub("[._][Rr]1[._]", lambda x: x.group().replace("1", "2"), filename)

            # we don't necessary need the R2 to have been passed in; we infer it anyways
            if pair != filename and os.path.exists(pair):
                if not prompt and pair not in single_files:
                    # if we're not prompting, don't automatically pull in files
                    # not in the list the user passed in
                    continue

                paired_files.append((filename, pair))

                if pair in single_files:
                    single_files.remove(pair)

                single_files.remove(filename)

        auto_pair = True

        if prompt and len(paired_files) > 0:
            pair_list = ""
            for p in paired_files:
                pair_list += "\n  {}  &  {}".format(os.path.basename(p[0]), os.path.basename(p[1]))

            answer = click.confirm(
                "It appears there are paired files:{}\nInterleave them after upload?".format(
                    pair_list
                ),
                default="Y",
            )

            if not answer:
                auto_pair = False

        if auto_pair:
            files = paired_files + list(single_files)

    total_size = sum(
        [
            (_file_size(x[0], uncompressed=True) + _file_size(x[1], uncompressed=True))
            if isinstance(x, tuple)
            else _file_size(x, uncompressed=False)
            for x in files
        ]
    )

    upload_kwargs = {
        "metadata": appendables["valid_metadata"],
        "tags": appendables["valid_tags"],
        "project": project_id,
        "coerce_ascii": coerce_ascii,
        "progressbar": progressbar(length=total_size, label="Uploading..."),
    }

    run_via_threadpool(
        ctx.obj["API"].Samples.upload,
        files,
        upload_kwargs,
        max_threads=max_threads,
        graceful_exit=False,
    )
304992
def upgradeUpload(self, file):
        """"""
        files = {'upfile': open(file, 'rb')}
        return self.__post_files('/upgrade/upload',
                                 files=files)
925017
def upload(file_path, dataset=None, public=False):
    """"""

    config = ApiConfig()
    client = ApiClient(config.host, config.app_id, config.app_secret)
    return client.upload(file_path, dataset, public)
632419
def prepare_files(self, finder, force_root_egg_info=False, bundle=False):
        """"""
        unnamed = list(self.unnamed_requirements)
        reqs = list(self.requirements.values())
        while reqs or unnamed:
            if unnamed:
                req_to_install = unnamed.pop(0)
            else:
                req_to_install = reqs.pop(0)
            req_version = None
            install = True
            best_installed = False
            if not self.ignore_installed and not req_to_install.editable:
                req_to_install.check_if_exists()
                if req_to_install.satisfied_by:
                    if self.upgrade:
                        if not self.force_reinstall:
                            try:
                                url, req_version = finder.find_requirement(
                                    req_to_install, self.upgrade)
                            except BestVersionAlreadyInstalled:
                                best_installed = True
                                install = False
                            else:
                                # Avoid the need to call find_requirement again
                                req_to_install.url = url.url

                        if not best_installed:
                            req_to_install.conflicts_with = req_to_install.satisfied_by
                            req_to_install.satisfied_by = None
                    else:
                        install = False
                if req_to_install.satisfied_by:
                    if best_installed:
                        logger.notify('Requirement already up-to-date: %s'
                                      % req_to_install)
                    else:
                        logger.notify('Requirement already satisfied '
                                      '(use --upgrade to upgrade): %s'
                                      % req_to_install)
            if req_to_install.editable:
                logger.notify('Obtaining %s' % req_to_install)
            elif install:
                if req_to_install.url and req_to_install.url.lower().startswith('file:'):
                    logger.notify('Unpacking %s' % display_path(url_to_path(req_to_install.url)))
                else:
                    logger.notify('Downloading/unpacking %s' % req_to_install)
            logger.indent += 2
            try:
                is_bundle = False
                if req_to_install.editable:
                    if req_to_install.source_dir is None:
                        location = req_to_install.build_location(self.src_dir)
                        req_to_install.source_dir = location
                    else:
                        location = req_to_install.source_dir
                    if not os.path.exists(self.build_dir):
                        _make_build_dir(self.build_dir)
                    req_to_install.update_editable(not self.is_download)
                    if self.is_download:
                        req_to_install.run_egg_info()
                        req_to_install.archive(self.download_dir)
                    else:
                        req_to_install.run_egg_info()
                elif install:
                    ##@@ if filesystem packages are not marked
                    ##editable in a req, a non deterministic error
                    ##occurs when the script attempts to unpack the
                    ##build directory

                    location = req_to_install.build_location(self.build_dir, not self.is_download)
                    ## FIXME: is the existance of the checkout good enough to use it?  I don't think so.
                    unpack = True
                    if not os.path.exists(os.path.join(location, 'setup.py')):
                        ## FIXME: this won't upgrade when there's an existing package unpacked in `location`
                        if req_to_install.url is None:
                            url, req_version = finder.find_requirement(req_to_install, upgrade=self.upgrade)
                        else:
                            ## FIXME: should req_to_install.url already be a link?
                            url = Link(req_to_install.url)
                            assert url
                        if url:
                            try:
                                self.unpack_url(req_to_install, req_version, url, location, self.is_download)
                            except HTTPError:
                                e = sys.exc_info()[1]
                                logger.fatal('Could not install requirement %s because of error %s'
                                             % (req_to_install, e))
                                raise InstallationError(
                                    'Could not install requirement %s because of HTTP error %s for URL %s'
                                    % (req_to_install, e, url))
                        else:
                            unpack = False
                    if unpack:
                        is_bundle = req_to_install.is_bundle
                        url = None
                        if is_bundle:
                            req_to_install.move_bundle_files(self.build_dir, self.src_dir)
                            for subreq in req_to_install.bundle_requirements():
                                reqs.append(subreq)
                                self.add_requirement(subreq)
                        elif self.is_download:
                            req_to_install.source_dir = location
                            if url and url.scheme in vcs.all_schemes:
                                req_to_install.run_egg_info()
                                req_to_install.archive(self.download_dir)
                        else:
                            req_to_install.source_dir = location
                            req_to_install.run_egg_info()
                            if force_root_egg_info:
                                # We need to run this to make sure that the .egg-info/
                                # directory is created for packing in the bundle
                                req_to_install.run_egg_info(force_root_egg_info=True)
                            req_to_install.assert_source_matches_version()
                            #@@ sketchy way of identifying packages not grabbed from an index
                            if bundle and req_to_install.url:
                                self.copy_to_build_dir(req_to_install)
                                install = False
                        # req_to_install.req is only avail after unpack for URL pkgs
                        # repeat check_if_exists to uninstall-on-upgrade (#14)
                        req_to_install.check_if_exists()
                        if req_to_install.satisfied_by:
                            if self.upgrade or self.ignore_installed:
                                req_to_install.conflicts_with = req_to_install.satisfied_by
                                req_to_install.satisfied_by = None
                            else:
                                install = False
                if not is_bundle and not self.is_download:
                    ## FIXME: shouldn't be globally added:
                    finder.add_dependency_links(req_to_install.dependency_links)
                    if (req_to_install.extras):
                        logger.notify("Installing extra requirements: %r" % ','.join(req_to_install.extras))
                    if not self.ignore_dependencies:
                        for req in req_to_install.requirements(req_to_install.extras):
                            try:
                                name = pkg_resources.Requirement.parse(req).project_name
                            except ValueError:
                                e = sys.exc_info()[1]
                                ## FIXME: proper warning
                                logger.error('Invalid requirement: %r (%s) in requirement %s' % (req, e, req_to_install))
                                continue
                            if self.has_requirement(name):
                                ## FIXME: check for conflict
                                continue
                            subreq = InstallRequirement(req, req_to_install)
                            reqs.append(subreq)
                            self.add_requirement(subreq)
                    if req_to_install.name not in self.requirements:
                        self.requirements[req_to_install.name] = req_to_install
                else:
                    self.reqs_to_cleanup.append(req_to_install)
                if install:
                    self.successfully_downloaded.append(req_to_install)
                    if bundle and (req_to_install.url and req_to_install.url.startswith('file:///')):
                        self.copy_to_build_dir(req_to_install)
            finally:
                logger.indent -= 2
928059
def create_package_version(requirement):
    """"""
    try:
        PackageVersion(requirement=requirement).save()
        logger.info("Package '%s' added.", requirement.name)  # noqa
    except IntegrityError:
        logger.info("Package '%s' already exists.", requirement.name)
553661
def submit_task(rel_path, cache_string, buffer):
    """"""
    global upload_queue
    global upload_thread
    upload_queue.put((rel_path, cache_string, buffer))

    if upload_thread is None or not upload_thread.is_alive():
        upload_thread = UploaderThread()
        upload_thread.start()
1009710
def post_download(project, filename, name=None, description=""):
    """"""
    if name is None:
        name = os.path.basename(filename)
    with open(filename, 'rb') as f:
        filedata = f.read()

    url = "https://api.github.com/repos/{project}/downloads".format(project=project)

    payload = json.dumps(dict(name=name, size=len(filedata),
                    description=description))
    response = requests.post(url, data=payload, headers=make_auth_header())
    response.raise_for_status()
    reply = json.loads(response.content)
    s3_url = reply['s3_url']

    fields = dict(
        key=reply['path'],
        acl=reply['acl'],
        success_action_status=201,
        Filename=reply['name'],
        AWSAccessKeyId=reply['accesskeyid'],
        Policy=reply['policy'],
        Signature=reply['signature'],
        file=(reply['name'], filedata),
    )
    fields['Content-Type'] = reply['mime_type']
    data, content_type = encode_multipart_formdata(fields)
    s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type})
    return s3r
980187
function uploadPackage()
    {

        if ( !eZHTTPFile::canFetch( 'PackageBinaryFile' ) )
        {
            $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init',
                                      'No package selected for upload' ) . '.';
            return;
        }

        $file = eZHTTPFile::fetch( 'PackageBinaryFile' );
        if ( !$file )
        {
            $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init',
                                      'Failed fetching upload package file' );
            return;
        }

        $packageFilename = $file->attribute( 'filename' );
        $packageName = $file->attribute( 'original_filename' );
        if ( preg_match( "#^(.+)-[0-9](\.[0-9]+)-[0-9].ezpkg$#", $packageName, $matches ) )
            $packageName = $matches[1];
        $packageName = preg_replace( array( "#[^a-zA-Z0-9]+#",
                                            "#_+#",
                                            "#(^_)|(_$)#" ),
                                     array( '_',
                                            '_',
                                            '' ), $packageName );
        $package = eZPackage::import( $packageFilename, $packageName, false );

        if ( is_object( $package ) )
        {
            // package successfully imported
            return;
        }
        elseif ( $package == eZPackage::STATUS_ALREADY_EXISTS )
        {
            eZDebug::writeWarning( "Package '$packageName' already exists." );
        }
        else
        {
            $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init',
                                  'Uploaded file is not an eZ Publish package' );
        }
    }
885577
def upload(client, source_dir):
    """"""
    print('')
    print('upload inappproducs')
    print('---------------------')

    products_folder = os.path.join(source_dir, 'products')
    product_files = filter(os.path.isfile, list_dir_abspath(products_folder))

    current_product_skus = map(lambda product: product['sku'], client.list_inappproducts())
    print(current_product_skus)
    for product_file in product_files:
        with open(product_file) as product_file:
            product = json.load(product_file)
        #check if the product is new
        sku = product['sku']
        product['packageName'] = client.package_name
        print(sku)
        if sku in current_product_skus:
            print("update product {0}".format(sku))
            client.update_inappproduct(product, sku)
        else:
            print("create product {0}".format(sku))
            client.insert_inappproduct(product)