Python fabric.api.env 模块,get() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用fabric.api.env.get()

项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def setup_env(deployment_name):
    deployment = DEPLOYMENTS.get(deployment_name)


    if deployment is None:
        exit_with_error('Deployment "%s" not found.' % deployment_name)

    if 'kc_virtualenv_name' in deployment:
        deployment['virtualenv_name'] = deployment['kc_virtualenv_name']

    env.update(deployment)

    check_key_filename(deployment_name)

    env.virtualenv = os.path.join('/home', 'ubuntu', '.virtualenvs',
                                  env.kc_virtualenv_name, 'bin', 'activate')

    env.pip_requirements_file = os.path.join(env.kc_path,
                                             'requirements/base.pip')
    env.template_dir = 'onadata/libs/custom_template'
    env.template_repo = os.path.join(env.home, 'kobocat-template')
项目:vultr_fabric    作者:jmunsch    | 项目源码 | 文件源码
def install():
    env.hosts = get_hosts()

    page_content = '''
    <p class="c2"><span class="c0 c6">How I learned to print out money with a plug-and-play crypto mining rig.<br><br></span><span>Heard of crypto? Yeah, me too. <br><br>In the last 3 months the growth of the new cryptocurrency crypto has been mind-boggling, at over 200% since the beginning of the year. I jumped on the bandwagon like most people, purchasing currency hand-over fist for my inevitable paydays. <br><br>Back in the beginning of the Bitcoin surge, I dabbled with equipment called &ldquo;mining rigs&rdquo; for the purpose of farming coins that I knew would increase in value.<br><br>For those who aren&rsquo;t familiar, all cryptocurrencies work as a decentralized currency because &ldquo;miners&rdquo; validate each transaction. You may of heard of the &ldquo;blockchain&rdquo; which is essentially the worldwide ledger of the currency. When Joe pays Jane in crypto, a miner somewhere is crunching numbers to ensure the transaction goes through properly. These miners are rewarded with currency for their efforts, and so many people turn to mining for solid income. <br><br>The equipment used to mine, &ldquo;mining rigs&rdquo; are typically computers that are configured to validate transactions as efficiently as possible, to maximize profits. <br><br>With crypto, this usually requires a computer setup with multiple graphics cards (GPUs), and a motherboard to support them. Mining software is installed on the machine to do the work, and viola, you are printing out money, a lot of money given the current price of crypto.<br><br>While these setups can be time consuming and difficult to configure, many companies are doing the hard work for you, and selling their pre-configured rigs for you to buy and plug in. Your only cost is the equipment, and the power bill. <br><br>This time around, I didn&rsquo;t want to go through the pain of setting one up myself, so I purchased one direct from one of the better-known teams over at cryptoMiningRigs.com.</span><span><br><br>Their main rig &ldquo;The Motherload&rdquo; uses Nvidia 1070 GPUs, which while being some of the pricier GPUs, offer pretty solid power/profit ratios. Their entry unit costs $5999.99, which may seem steep, but once I crunched some numbers I found my average profits per month with this unit (at the </span><span class="c4">current</span><span>&nbsp;price of crypto mind you) to be </span><span class="c0">$1000USD/mo+.</span><span><br><br>If I account for the rising price of crypto, I can assume my investment pays for itself in less than 5 months. Sign me up!<br><br>After I ordered the unit I received it in about 2 weeks, packaged attractively and securely, despite it&rsquo;s more open-air design. These rigs do not have cases like normal PCs, as they generate a lot of heat.<br><br>After plugging it in and following the included instructions, I was up and running in less than an hour. That&rsquo;s a hellova lot less time than it took when I built it myself years ago.<br><br>I&rsquo;ve had their product running for 2 weeks solid now, with absolutely no issue. The recent surge of crypto, already has my mouth salivating as to what this machine could produce for me over the next few months. I&rsquo;m considering buying 1-2 more, to be honest. <br><br>If you want the easy way in guys, this is it. Pre-built rigs are the way to go if you want the quickest and easiest way to get right into the action of crypto mining. For more info, head on over to </span><span class="c7"><a class="c3" href="https://cryptominingrigs.com/">www.cryptominingrigs.com</a></span><span>&nbsp;and get on this gravy train!<br><br></span><span><br><br></span><span class="c6 c0"><br></span><span class="c5"><br><br></span></p>
    '''
    year = "2017"
    month = "05"
    day = "14"
    page_title = "crypto-mining-rig.html"

    with settings(user='root'):
        execute(apt_get)
        execute(place_main_css)
        execute(place_main_index_html)
        execute(place_page,
                page_content=page_content,
                year=year,
                month=month,
                day=day,
                page_title=page_title)
项目:lambda-chef-node-cleanup    作者:awslabs    | 项目源码 | 文件源码
def __call__(self):
        query = self.query
        environment = self.environment
        if environment is _default_environment:
            environment = env.get('chef_environment', DEFAULT_ENVIRONMENT)
        if environment:
            query += ' AND chef_environment:%s' % environment
        for row in Search('node', query, api=self.api):
            if row:
                if callable(self.hostname_attr):
                    val = self.hostname_attr(row.object)
                    if val:
                        yield val
                else:
                    for attr in self.hostname_attr:
                        try:
                            val =  row.object.attributes.get_dotted(attr)
                            if val: # Don't ever give out '' or None, since it will error anyway
                                yield val
                                break
                        except KeyError:
                            pass # Move on to the next
                    else:
                        raise ChefError('Cannot find a usable hostname attribute for node %s', row.object)
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def setup_env(deployment_name):
    deployment = DEPLOYMENTS.get(deployment_name)

    if deployment is None:
        exit_with_error('Deployment "%s" not found.' % deployment_name)

    env.update(deployment)

    check_key_filename(deployment_name)

    env.virtualenv = os.path.join('/home', 'ubuntu', '.virtualenvs',
                                  env.project, 'bin', 'activate')

    env.code_src = os.path.join(env.home, env.project)
    env.pip_requirements_file = os.path.join(env.code_src,
                                             'requirements/base.pip')
    env.template_dir = 'formshare/libs/custom_template'
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def deploy_template(env):
    if env.get('template'):
        run("mkdir -p %s" % env.template_repo)
        run("ls -al %s" % env.template_repo)
        run("rm -rf %s" % env.template_repo)
        if env.get('template_branch'):
            run("git clone -b %s %s %s" %
                (env.get('template_branch'), env.get('template'), env.template_repo))
        else:
            run("git clone %s %s" % (env.get('template'), env.template_repo))
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def get_last_successfully_built_commit(branch):
    ''' Returns the hash of the latest successfully built commit
    on the given branch according to Travis CI. '''

    API_ENDPOINT='https://api.travis-ci.org/'
    REPO_SLUG='kobotoolbox/kobocat'
    COMMON_HEADERS={'accept': 'application/vnd.travis-ci.2+json'}

    ''' Travis only lets us specify `number`, `after_number`, and `event_type`.
    It'd be great to filter by state and branch, but it seems we can't
    (http://docs.travis-ci.com/api/?http#builds). '''

    request = requests.get(
        '{}repos/{}/builds'.format(API_ENDPOINT, REPO_SLUG),
        headers=COMMON_HEADERS
    )
    if request.status_code != 200:
        raise Exception('Travis returned unexpected code {}.'.format(
            request.status_code
        ))
    response = json.loads(request.text)

    builds = response['builds']
    commits = {commit['id']: commit for commit in response['commits']}

    for build in builds:
        if build['state'] != 'passed' or build['pull_request']:
            # No interest in non-passing builds or PRs
            continue
        commit = commits[build['commit_id']]
        if commit['branch'] == branch:
            # Assumes the builds are in descending chronological order
            if re.match('^[0-9a-f]+$', commit['sha']) is None:
                raise Exception('Travis returned the invalid SHA {}.'.format(
                    commit['sha']))
            return commit['sha']

    raise Exception("Couldn't find a passing build for the branch {}. "
        "This could be due to pagination, in which case this code "
        "must be made more robust!".format(branch))
项目:vultr_fabric    作者:jmunsch    | 项目源码 | 文件源码
def get_hosts():
    hosts = []
    for subid, server_info in vultr.list_deployed_servers().items():
        if 'miningrigs' in server_info.get('label'):
            server_info.get('default_password'),
            hosts.append(server_info.get('main_ip'))
    return hosts
项目:vultr_fabric    作者:jmunsch    | 项目源码 | 文件源码
def place_main_index_html():
    def template_index(index_html):
        host_string = env.get('host')
        okay = zip(configs.get('index_replace'), configs.get(host_string).get('index_replace_formats'))
        for item, replacer in okay:
            print(item, replacer.format(host_string))
            index_html = index_html.replace(item, replacer.format(host_string))
        index_html = StringIO(unicode(index_html))
        return index_html
    with open('./boiler/index.html') as f:
        index_html = f.read()
    put(template_index(index_html), '/usr/share/nginx/html/index.html')
项目:vultr_fabric    作者:jmunsch    | 项目源码 | 文件源码
def place_main_css():
    def get_main_css(main_css, rgb):
        (r, g, b) = tuple([int(x) for x in rgb.split()])
        rgb_orig = 'rgb({}, {}, {})'.format(r, g, b)
        rgb_lighter = 'rgb({}, {}, {})'.format(r+20, g+20, b+20)
        main_css = main_css.replace('#f16529', unicode(rgb_orig))
        main_css = main_css.replace('#e44d26', unicode(rgb_lighter))
        main_css = StringIO(main_css)
        return main_css
    with open('./boiler/css/main.css') as f:
        main_css = f.read()
    put(get_main_css(main_css, configs.get(env.get('host')).get('main_css')), '/usr/share/nginx/html/css/main.css')
项目:vultr_fabric    作者:jmunsch    | 项目源码 | 文件源码
def apt_get():
    sudo('apt-get update && apt-get install -y nginx')
项目:fapistrano    作者:liwushuo    | 项目源码 | 文件源码
def check_stage_and_role():
    stage = env.get('stage')
    role = env.get('role')

    # raise error when env/role not set both
    if not stage or not role:
        abort('stage or role not set!')
项目:fapistrano    作者:liwushuo    | 项目源码 | 文件源码
def apply_configurations_to_env(conf):
    for env_item in conf:
        env_value = conf.get(env_item)
        setattr(env, env_item, env_value)
项目:fapistrano    作者:liwushuo    | 项目源码 | 文件源码
def apply_yaml_to_env(confs, operation):

    from .signal import clear
    clear()

    plugins = confs.get(operation + '_plugins') or confs.get('plugins') or []

    for plugin in plugins:
        mod = import_module(plugin)
        mod.init()

    for key, value in confs.items():
        setattr(env, key, value)
项目:djangocon-2016-demo    作者:hadjango    | 项目源码 | 文件源码
def build_venv(name):
    old_build_name = env.get('build_name')
    env['build_name'] = name
    build_dir = "/code/deploy/builds/%s" % name
    with cd("%s" % build_dir):
        docker_exec("[ -f bin/pip ] || virtualenv . --never-download")
        with path(os.path.join(build_dir, 'bin'), behavior='prepend'):
            yield
    env['build_name'] = old_build_name
项目:lambda-chef-node-cleanup    作者:awslabs    | 项目源码 | 文件源码
def chef_environment(name, api=None):
    """A Fabric task to set the current Chef environment context.

    This task works alongside :func:`~chef.fabric.chef_roledefs` to set the
    Chef environment to be used in future role queries.

    Example::

        from chef.fabric import chef_environment, chef_roledefs
        env.roledefs = chef_roledefs()

    .. code-block:: bash

        $ fab env:production deploy

    The task can be configured slightly via Fabric ``env`` values.

    ``env.chef_environment_task_alias`` sets the task alias, defaulting to "env".
    This value must be set **before** :mod:`chef.fabric` is imported.

    ``env.chef_environment_validate`` sets if :class:`~chef.Environment` names
    should be validated before use. Defaults to True.

    .. versionadded:: 0.2
    """
    if env.get('chef_environment_validate', True):
        api = _api(api)
        chef_env = Environment(name, api=api)
        if not chef_env.exists:
            raise ChefError('Unknown Chef environment: %s' % name)
    env['chef_environment'] = name
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def deploy_template(env):
    if env.get('template'):
        run("git remote add template %s || true" % env.template)
        run("git fetch template")
        run("git reset HEAD %s && rm -rf %s" % (env.template_dir,
                                                env.template_dir))
        run("git read-tree --prefix=%s -u template/master"
            % env.template_dir)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def deploy_ref(deployment_name, ref):
    setup_env(deployment_name)
    with cd(env.kc_path):
        run("git fetch origin")
        # Make sure we're not moving to an older codebase
        git_output = run('git rev-list {}..HEAD --count 2>&1'.format(ref))
        if int(git_output) > 0:
            raise Exception("The server's HEAD is already in front of the "
                "commit to be deployed.")
        # We want to check out a specific commit, but this does leave the HEAD
        # detached. Perhaps consider using `git reset`.
        run('git checkout {}'.format(ref))
        # Report if the working directory is unclean.
        git_output = run('git status --porcelain')
        if len(git_output):
            run('git status')
            print('WARNING: The working directory is unclean. See above.')

        deploy_template(env)

        run('find . -name "*.pyc" -exec rm -rf {} \;')
        run('find . -type d -empty -delete')

    # numpy pip install from requirements file fails
    with kobo_workon(env.kc_virtualenv_name):
        run("pip install numpy")
        run("pip install --upgrade -r %s" % env.pip_requirements_file)

    formpack_path = os.path.join(env.home, 'formpack')
    formpack_branch = env.get('formpack_branch', False)
    run("[ -d {fp} ] || git clone https://github.com/kobotoolbox/formpack.git "
        "{fp}".format(fp=formpack_path))

    with cd(formpack_path):
        with kobo_workon(env.kc_virtualenv_name):
            if formpack_branch:
                run("git checkout {b} && git pull origin {b}"
                    .format(b=formpack_branch))
            run("python setup.py develop")

    with cd(os.path.join(env.kc_path, "onadata", "static")):
        run("date > LAST_UPDATE.txt")

    with cd(env.kc_path):
        with kobo_workon(env.kc_virtualenv_name):
            run("python manage.py syncdb")
            run("python manage.py migrate")
            run("python manage.py collectstatic --noinput")

    run("sudo restart kc_celeryd")
    run("sudo restart uwsgi")
项目:djangocon-2016-demo    作者:hadjango    | 项目源码 | 文件源码
def _prefix_env_vars(command, local=False):
    """
    Prefixes ``command`` with any shell environment vars, e.g. ``PATH=foo ``.

    Currently, this only applies the PATH updating implemented in
    `~fabric.context_managers.path` and environment variables from
    `~fabric.context_managers.shell_env`.

    Will switch to using Windows style 'SET' commands when invoked by
    ``local()`` and on a Windows localhost.
    """
    env_vars = {}

    # path(): local shell env var update, appending/prepending/replacing $PATH
    path = env.path
    if path:
        if env.path_behavior == 'append':
            path = '$PATH:\"%s\"' % path
        elif env.path_behavior == 'prepend':
            path = '\"%s\":$PATH' % path
        elif env.path_behavior == 'replace':
            path = '\"%s\"' % path

        env_vars['PATH'] = path

    # shell_env()
    env_vars.update(env.get('docker_shell_env'))

    if env_vars:
        set_cmd, exp_cmd = '', ''
        if win32 and local:
            set_cmd = 'SET '
        else:
            exp_cmd = 'export '

        exports = ' '.join(
            '%s%s="%s"' % (set_cmd, k, v if k == 'PATH' else _shell_escape(v))
            for k, v in env_vars.iteritems()
        )
        shell_env_str = '%s%s && ' % (exp_cmd, exports)
    else:
        shell_env_str = ''

    return "%s%s" % (shell_env_str, command)