Upload Nginx site configuration from a template.
18258
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True):
    """"""
    
    template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf']
    site_available = u'/etc/nginx/sites-available/%s' % site_name
    upload_template(template_name, site_available, context=context, use_sudo=True)
    if enable:
        enable_site(site_name)
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!')
166425
private function loadingConfig()
    {
        if ($_SERVER['HTTP_HOST'] == SERVER_DEVELOP) {
            if (!is_file(SYSTEM_ROOT . '/config/config.local.php'))
                @copy(SYSTEM_ROOT . '/config/config.sample.php', SYSTEM_ROOT . '/config/config.local.php');
            require_once('config/config.local.php');
        } else {
            if (!is_file(SYSTEM_ROOT . '/config/config.php'))
                @copy(SYSTEM_ROOT . '/config/config.sample.php', SYSTEM_ROOT . '/config/config.php');
            require_once('config/config.php');
        }
    }
1197673
def load_from_config(self, config):
        """"""
        self.site = config.get("id", False)
        self.uri_base = config.get("uri_base", False)
        self.uris_to_crawl = self.crawlpage.get_uris(
            base_uri=self.uri_base,
            filter_list=config.get("crawl_uri_filters", None)
        )
        self.is_consume_page = self.crawlpage.has_selector(
            config.get("consume_selector", False)
        )
828218
def setup(app):
    """"""
    app.add_config_value(
        'site_url',
        default=None,
        rebuild=False
    )
    try:
        app.add_config_value(
            'html_baseurl',
            default=None,
            rebuild=False
        )
    except:
        pass

    app.connect('html-page-context', add_html_link)
    app.connect('build-finished', create_sitemap)
    app.sitemap_links = []
    app.locales = []
437575
def _setup(app, *, schema,  title=None, app_key=APP_KEY, db=None):
    """"""

    admin = web.Application(loop=app.loop)
    app[app_key] = admin
    loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ])
    aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)

    if title:
        schema.title = title

    resources = [
        init(db, info['table'], url=info['url'])
        for init, info in schema.resources
    ]

    admin_handler = AdminOnRestHandler(
        admin,
        resources=resources,
        loop=app.loop,
        schema=schema,
    )

    admin['admin_handler'] = admin_handler
    setup_admin_on_rest_handlers(admin, admin_handler)

    return admin
482717
def enable_site(site_name):
    """"""

    site_available = u'/etc/nginx/sites-available/%s' % site_name
    site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name
    if files.exists(site_available):
        sudo(u'ln -s -f %s %s' % (site_available, site_enabled))
        restart_service(u'nginx')
    else:
        abort(u'%s site configuration is not available' % site_name)
249781
def build():
    
    test_files()
    with open('content.rst') as f:
        content = publish_parts(f.read(), writer_name='html')
        title = content['title']
        body =  content['html_body'].replace('\n',' ')

    with open('template.jinja', 'r') as f:
        loader = FileSystemLoader(getcwd())
        env= Environment(loader=loader)
        template = env.get_template('template.jinja')
        page =  template.render(title=title,
                                content=body)

    with open('index.html', 'w') as f:
        f.write(page)
442739
def install_template(username, repo):
    """"""
    print("Installing template from " + username + "/" + repo)

    dpath = os.path.join(cwd, "templates")
    getunzipped(username, repo, dpath)
100399
def setup(provider=None):
    
    site = init(provider)
    if not site:
        site = yaml.safe_load(_read_file(DEPLOY_YAML))

    provider_class = PROVIDERS[site['provider']]
    provider_class.init(site)
1293791
private String createConfigForSite(CmsSite site, String templateContent) {

        StringTemplate config = new StringTemplate(templateContent);

        // system info
        String webappPath = OpenCms.getSystemInfo().getWebApplicationRfsPath();
        config.setAttribute("DOCUMENT_ROOT", webappPath.substring(0, webappPath.length() - 1));
        config.setAttribute("WEBAPP_NAME", OpenCms.getSystemInfo().getWebApplicationName());
        config.setAttribute("CONTEXT_PATH", OpenCms.getSystemInfo().getContextPath());
        config.setAttribute("SERVLET_PATH", OpenCms.getSystemInfo().getServletPath());
        config.setAttribute("DEFAULT_ENCODING", OpenCms.getSystemInfo().getDefaultEncoding());
        config.setAttribute("CONFIG_FILENAME", generateWebserverConfigName(site.getSiteMatcher(), "_"));
        config.setAttribute("LOGGING_DIRECTORY", m_loggingDir);

        // site info
        config.setAttribute("SERVER_URL", site.getUrl());
        config.setAttribute("SERVER_PROTOCOL", site.getSiteMatcher().getServerProtocol());
        config.setAttribute("SERVER_NAME", site.getSiteMatcher().getServerName());
        config.setAttribute("SERVER_PORT", site.getSiteMatcher().getServerPort());
        config.setAttribute("SERVER_NAME_WITH_PORT", generateWebserverConfigName(site.getSiteMatcher(), ":"));
        config.setAttribute("SITE_TITLE", site.getTitle());
        if (site.getErrorPage() != null) {
            config.setAttribute("ERROR_PAGE", site.getErrorPage());
        }

        // alias info
        if ((site.getAliases() != null) && !site.getAliases().isEmpty()) {
            config.setAttribute("ALIAS_DIRECTIVE", "ServerAlias");
            for (CmsSiteMatcher alias : site.getAliases()) {
                config.setAttribute("SERVER_ALIASES", generateWebserverConfigName(alias, ":") + " ");
            }
        }

        // secure info
        if (site.hasSecureServer()) {
            if (site.getSecureUrl() != null) {
                config.setAttribute("SECURE_URL", site.getSecureUrl());
            }
            if (site.getSecureServer() != null) {
                config.setAttribute("SECURE_SRV_WITH_PORT", generateWebserverConfigName(site.getSecureServer(), ":"));
                config.setAttribute("SECURE_SERVER_NAME", site.getSecureServer().getServerName());
                config.setAttribute("SECURE_SERVER_PORT", site.getSecureServer().getServerPort());
                config.setAttribute("SECURE_SERVER_PROTOCOL", site.getSecureServer().getServerProtocol());
            }
        }
        return config.toString();
    }
1019182
def _create_config(self):
        """"""
        configinfo = {'creation_date': [ datetime.datetime.now().date().isoformat()],
                      'author': [self.site.site_config['default_author']],
                      'status': [u'draft'],
                      'lang': [u''],
                      'tags': [u''],
                      'title': [self._title],
                      'slug': [self._slug],
                      'theme': [u''],
                      'template': [u''],
                      'page_id': [uuid.uuid4().hex]
                      }  # when theme and template are empty, the generator uses the defaults. Thus, initially
                                          # they should be empty, to allow for global changes just by changing the site config files.
        return configinfo
1240003
def setup_website_module(self, command):
        """"""
        name = self.options.get('name') if self.options.get('name') else self.options.get('path')  # noqa pylint: disable=line-too-long
        ensure_valid_environment_config(
            name,
            self.options.get('environments',
                             {}).get(self.context.env_name,
                                     {}))
        module_dir = tempfile.mkdtemp()
        LOGGER.info("staticsite: Generating CloudFormation configuration for "
                    "module %s in %s",
                    name,
                    module_dir)

        # Default parameter name matches build_staticsite hook
        hash_param = self.options.get('options', {}).get('source_hashing', {}).get('parameter') if self.options.get('options', {}).get('source_hashing', {}).get('parameter') else "${namespace}-%s-hash" % name # noqa pylint: disable=line-too-long
        build_staticsite_args = self.options.copy()
        if not build_staticsite_args.get('options'):
            build_staticsite_args['options'] = {}
        build_staticsite_args['artifact_bucket_rxref_lookup'] = "%s-dependencies::ArtifactsBucketName" % name  # noqa pylint: disable=line-too-long
        build_staticsite_args['options']['namespace'] = '${namespace}'
        build_staticsite_args['options']['name'] = name
        build_staticsite_args['options']['path'] = os.path.join(
            os.path.realpath(self.context.env_root),
            self.path
        )

        with open(os.path.join(module_dir, '01-dependencies.yaml'), 'w') as output_stream:  # noqa
            yaml.dump(
                {'namespace': '${namespace}',
                 'stacker_bucket': '',
                 'stacks': {
                     "%s-dependencies" % name: {
                         'class_path': 'runway.blueprints.staticsite.dependencies.Dependencies'}},  # noqa pylint: disable=line-too-long
                 'pre_destroy': [
                     {'path': 'runway.hooks.cleanup_s3.purge_bucket',
                      'required': True,
                      'args': {
                          'bucket_rxref_lookup': "%s-dependencies::%s" % (name, i)  # noqa
                      }} for i in ['AWSLogBucketName', 'ArtifactsBucketName']
                 ]},
                output_stream,
                default_flow_style=False
            )
        site_stack_variables = {
            'Aliases': '${default staticsite_aliases::undefined}',
            'RewriteDirectoryIndex': '${default staticsite_rewrite_directory_index::undefined}',  # noqa pylint: disable=line-too-long
            'WAFWebACL': '${default staticsite_web_acl::undefined}'
        }
        if self.options.get('environments',
                            {}).get(self.context.env_name,
                                    {}).get('staticsite_enable_cf_logging',
                                            True):
            site_stack_variables['LogBucketName'] = "${rxref %s-dependencies::AWSLogBucketName}" % name  # noqa pylint: disable=line-too-long
        if self.options.get('environments',
                            {}).get(self.context.env_name,
                                    {}).get('staticsite_acmcert_ssm_param'):
            site_stack_variables['AcmCertificateArn'] = '${ssmstore ${staticsite_acmcert_ssm_param}}'  # noqa pylint: disable=line-too-long
        else:
            site_stack_variables['AcmCertificateArn'] = '${default staticsite_acmcert_arn::undefined}'  # noqa pylint: disable=line-too-long
        # If staticsite_lambda_function_associations defined, add to stack
        # config
        if self.options.get('environments',
                            {}).get(self.context.env_name,
                                    {}).get('staticsite_lambda_function_associations'):  # noqa
            site_stack_variables['lambda_function_associations'] = self.options.get(  # noqa
                'environments',
                {}
            ).get(self.context.env_name,
                  {}).get('staticsite_lambda_function_associations')
            self.options.get('environments',
                             {}).get(self.context.env_name,
                                     {}).pop('staticsite_lambda_function_associations')  # noqa
        with open(os.path.join(module_dir, '02-staticsite.yaml'), 'w') as output_stream:  # noqa
            yaml.dump(
                {'namespace': '${namespace}',
                 'stacker_bucket': '',
                 'pre_build': [
                     {'path': 'runway.hooks.staticsite.build_staticsite.build',
                      'required': True,
                      'data_key': 'staticsite',
                      'args': build_staticsite_args}
                 ],
                 'stacks': {
                     name: {
                         'class_path': 'runway.blueprints.staticsite.staticsite.StaticSite',  # noqa
                         'variables': site_stack_variables}},
                 'post_build': [
                     {'path': 'runway.hooks.staticsite.upload_staticsite.sync',
                      'required': True,
                      'args': {
                          'bucket_output_lookup': '%s::BucketName' % name,
                          'distributionid_output_lookup': '%s::CFDistributionId' % name,  # noqa
                          'distributiondomain_output_lookup': '%s::CFDistributionDomainName' % name}}  # noqa pylint: disable=line-too-long
                 ],
                 'pre_destroy': [
                     {'path': 'runway.hooks.cleanup_s3.purge_bucket',
                      'required': True,
                      'args': {
                          'bucket_rxref_lookup': "%s::BucketName" % name
                      }}
                 ],
                 'post_destroy': [
                     {'path': 'runway.hooks.cleanup_ssm.delete_param',
                      'args': {
                          'parameter_name': hash_param
                      }}
                 ]},
                output_stream,
                default_flow_style=False
            )

        cfn = CloudFormation(
            self.context,
            module_dir,
            {i: self.options[i] for i in self.options if i != 'class_path'}
        )
        getattr(cfn, command)()
1017783
def create_config_files(directory):
    
    # get the config file template
    template_url = ("https://securenetconnection.com/vpnconfig/"
                    "openvpn-template.ovpn")
    resp = requests.get(template_url)
    resp.raise_for_status()
    template = resp.content

    # get the available servers and create a config file for each server
    server_url = ("https://securenetconnection.com/vpnconfig/"
                  "servers-cli.php")
    resp = requests.get(server_url)
    resp.raise_for_status()
    servers = resp.content.split("\n")

    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(os.path.join(directory, "servers.txt"), 'w') as f:
        f.write(resp.content)

    for server_line in servers:
        if server_line.strip() == "":
            continue
        server_line = server_line.split("|")
        try:
            ip, desc, country, udp_sup, tcp_sup = server_line
        except ValueError:
            ip, desc, country, udp_sup, tcp_sup, no_rand = server_line
        with open(os.path.join(directory, ip + ".ovpn"), 'w') as file_o:
            file_o.write(template)
            # create tcp if available, else udp
            tcp_sup = tcp_sup.strip()
            if tcp_sup:
                port, proto = 443, "tcp"
            else:
                port, proto = 53, "udp"
            file_o.write("remote {0} {1}\n".format(ip, port))
            file_o.write("proto {0}\n".format(proto))
            # add automatic dns server update
            file_o.write("up /etc/openvpn/update-resolv-conf\n")
            file_o.write("down /etc/openvpn/update-resolv-conf\n")
418657
function ( conf ) {
    serverConfig = sqsUtil.copy( conf.server );

    serverConfig.siteurl = serverConfig.siteurl.replace( rSlash, "" );
    serverConfig.port = (serverConfig.port || 5050);
    serverConfig.webroot = process.cwd();
    serverConfig.protocol = serverConfig.siteurl.match( rProtocol )[ 0 ];
    serverConfig.siteData = {};

    // Set config for middleware
    sqsWare.set( "siteurl", serverConfig.siteurl );

    if ( serverConfig.password ) {
        sqsWare.set( "sitepassword", serverConfig.password );
    }

    if ( serverConfig.sandbox ) {
        sqsWare.set( "sandboxmode", true );
    }

    if ( serverConfig.fulldata !== undefined ) {
        sqsWare.set( "fulldata", serverConfig.fulldata );
    }

    sqsTemplate.setConfig( "server", serverConfig );
}
838462
def sync_db():
    
    with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
        venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
        sites = _get_django_sites()
        site_ids = sites.keys()
        site_ids.sort()
        for site in site_ids:
            for settings_file in _sitesettings_files():
                site_settings = '.'.join([env.project_package_name,'sitesettings',settings_file.replace('.py','')])
                if env.verbosity:
                    print " * django-admin.py syncdb --noinput --settings=%s"% site_settings
                output = sudo(' '.join(['source',venv,'&&',"django-admin.py syncdb --noinput --settings=%s"% site_settings]),
                              user='site_%s'% site)
                if env.verbosity:
                    print output
1132223
def template(client, src, dest, paths, opt):
    """"""
    key_map = cli_hash(opt.key_map)
    obj = {}
    for path in paths:
        response = client.read(path)
        if not response:
            raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
        if is_aws(response['data']) and 'sts' not in path:
            renew_secret(client, response, opt)

        for s_k, s_v in response['data'].items():
            o_key = s_k
            if s_k in key_map:
                o_key = key_map[s_k]

            k_name = secret_key_name(path, o_key, opt) \
                .lower() \
                .replace('-', '_')
            obj[k_name] = s_v

    template_obj = blend_vars(obj, opt)
    output = render(grok_template_file(src),
                    template_obj)
    write_raw_file(output, abspath(dest))