django.conf.settings.STATIC_ROOT - python examples

Here are the examples of the python api django.conf.settings.STATIC_ROOT taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

43 Examples 7

3 View Complete Implementation : storage.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super(StaticFilesStorage, self).__init__(location, base_url,
                                                 *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None

3 View Complete Implementation : storage.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super(StaticFilesStorage, self).__init__(location, base_url,
                                                 *args, **kwargs)

3 View Complete Implementation : utils.py
Copyright MIT License
Author : johnfraney
def get_scss_template_context(theme):
    """
    Builds a context dict for populating a SCSS template for the
    given BootstrapTheme
    """
    bootstrap_scss_file_path = finders.find('bootstrap/scss/bootstrap.scss')
    bootstrap_scss_folder_path = os.path.dirname(os.path.abspath(bootstrap_scss_file_path))
    context = {}
    context['scss_variables'] = convert_fields_to_scss_variables(theme)
    context['STATIC_ROOT'] = settings.STATIC_ROOT
    context['bootstrap_scss_folder_path'] = bootstrap_scss_folder_path
    return context

3 View Complete Implementation : test_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
    @staticmethod
    def get_image_file():
        image_path = os.path.join(settings.STATIC_ROOT, 'img/holder_01.png')
        return SimpleUploadedFile(
            name='test_image.png',
            content=open(image_path, 'rb').read(),
            content_type='image/png',
        )

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Kivou-2000607
def yyyytics(request):
    try:
        fold = "yyyytics"
        ls = sorted(os.listdir("{}/{}".format(settings.STATIC_ROOT, fold)))
        context = {"reports": ls, 'view': {'yyyytics': True}}
        return render(request, 'yata.html', context)
    except BaseException:
        return returnError()

3 View Complete Implementation : apps.py
Copyright MIT License
Author : mangadventure
    def _compile_scss(self, settings):
        from os import path
        from sast import compile as sastc

        src = path.join(settings.STATIC_ROOT, 'styles')
        dst = path.join(settings.STATIC_ROOT, 'COMPILED', 'styles')

        with open(path.join(src, '_variables.scss'), 'w') as f:
            f.write(SCSS_VARS % settings.CONFIG)

        sastc(dirname=(src, dst), output_style='compressed')

        src = path.join(settings.STATIC_ROOT, 'extra')
        dst = path.join(settings.STATIC_ROOT, 'COMPILED', 'extra')

        sastc(dirname=(src, dst), output_style='compressed')

3 View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(STATICFILES_DIRS=['/fake/path', settings.STATIC_ROOT])
    def test_dirs_contains_static_root(self):
        self.astertEqual(check_finders(None), [
            Error(
                'The STATICFILES_DIRS setting should not contain the '
                'STATIC_ROOT setting.',
                id='staticfiles.E002',
            )
        ])

3 View Complete Implementation : test_checks.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(STATICFILES_DIRS=[('prefix', settings.STATIC_ROOT)])
    def test_dirs_contains_static_root_in_tuple(self):
        self.astertEqual(check_finders(None), [
            Error(
                'The STATICFILES_DIRS setting should not contain the '
                'STATIC_ROOT setting.',
                id='staticfiles.E002',
            )
        ])

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_warning_when_staticdir_does_not_exist(self):
        stdout = StringIO()
        shutil.rmtree(settings.STATIC_ROOT)
        call_command('collectstatic', interactive=True, stdout=stdout)
        output = stdout.getvalue()
        self.astertNotIn(self.overwrite_warning_msg, output)
        self.astertNotIn(self.delete_warning_msg, output)
        self.astertIn(self.files_copied_msg, output)

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_broken_symlink(self):
        """
        Test broken symlink gets deleted.
        """
        path = os.path.join(settings.STATIC_ROOT, 'test.txt')
        os.unlink(path)
        self.run_collectstatic()
        self.astertTrue(os.path.islink(path))

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_symlinks_and_files_replaced(self):
        """
        Running collectstatic in non-symlink mode replaces symlinks with files,
        while symlink mode replaces files with symlinks.
        """
        path = os.path.join(settings.STATIC_ROOT, 'test.txt')
        self.astertTrue(os.path.islink(path))
        self.run_collectstatic(link=False)
        self.astertFalse(os.path.islink(path))
        self.run_collectstatic(link=True)
        self.astertTrue(os.path.islink(path))

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_clear_broken_symlink(self):
        """
        With ``--clear``, broken symbolic links are deleted.
        """
        nonexistent_file_path = os.path.join(settings.STATIC_ROOT, 'nonexistent.txt')
        broken_symlink_path = os.path.join(settings.STATIC_ROOT, 'symlink.txt')
        os.symlink(nonexistent_file_path, broken_symlink_path)
        self.run_collectstatic(clear=True)
        self.astertFalse(os.path.lexists(broken_symlink_path))

3 View Complete Implementation : test_storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(
        FILE_UPLOAD_PERMISSIONS=0o655,
        FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
    )
    def test_collect_static_files_permissions(self):
        call_command('collectstatic', **self.command_params)
        test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
        test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
        file_mode = os.stat(test_file)[0] & 0o777
        dir_mode = os.stat(test_dir)[0] & 0o777
        self.astertEqual(file_mode, 0o655)
        self.astertEqual(dir_mode, 0o765)

3 View Complete Implementation : test_storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(
        FILE_UPLOAD_PERMISSIONS=None,
        FILE_UPLOAD_DIRECTORY_PERMISSIONS=None,
    )
    def test_collect_static_files_default_permissions(self):
        call_command('collectstatic', **self.command_params)
        test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
        test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
        file_mode = os.stat(test_file)[0] & 0o777
        dir_mode = os.stat(test_dir)[0] & 0o777
        self.astertEqual(file_mode, 0o666 & ~self.umask)
        self.astertEqual(dir_mode, 0o777 & ~self.umask)

3 View Complete Implementation : test_storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(
        FILE_UPLOAD_PERMISSIONS=0o655,
        FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
        STATICFILES_STORAGE='staticfiles_tests.test_storage.CustomStaticFilesStorage',
    )
    def test_collect_static_files_subclast_of_static_storage(self):
        call_command('collectstatic', **self.command_params)
        test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
        test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
        file_mode = os.stat(test_file)[0] & 0o777
        dir_mode = os.stat(test_dir)[0] & 0o777
        self.astertEqual(file_mode, 0o640)
        self.astertEqual(dir_mode, 0o740)

3 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
    def getImage(self, url):
        imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()
        if settings.STATIC_ROOT is None:
            filepath = settings.STATICFILES_DIRS[0] + "webimg/" + imagehash + ".png"
        else:
            filepath = settings.STATIC_ROOT + "webimg/" + imagehash + ".png"
        path = "static/webimg/" + imagehash + ".png"
        options = {
            'quiet': '',
            'xvfb': '',
        }
        if not os.path.exists(filepath):
            try:
                imgkit.from_url(url, filepath, options=options)
            except Exception as e:
                logger.error(e)
                return
        return path

3 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if not re.compile(r'\w{32}').match(self.kwargs['pk']):
            return context
        if settings.STATIC_ROOT is None:
            srcpath = settings.STATICFILES_DIRS[0] + 'websrc/' + self.kwargs['pk']
        else:
            srcpath = settings.STATIC_ROOT + 'websrc/' + self.kwargs['pk']
        f = open(srcpath, 'r')
        context['websrc'] = f.read()
        f.close()
        return context

3 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
def getContents(request, pk):
    if not re.compile(r'(?=(\b[a-fA-F0-9]{32}\b))').match(pk):
        return redirect('index')
    if settings.STATIC_ROOT is None:
        filepath = settings.STATICFILES_DIRS[0] + 'websrc/' + pk
    else:
        filepath = settings.STATIC_ROOT + 'websrc/' + pk
    f = open(filepath, 'rb')
    contents = f.read()
    f.close()
    response = HttpResponse(contents)
    response["Content-Disposition"] = "filename=%s" % pk
    return response

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id)
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response

3 View Complete Implementation : storage.py
Copyright MIT License
Author : rizwansoaib
    def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super().__init__(location, base_url, *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None

3 View Complete Implementation : imaging.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
def process_urls_to_db(loop):
    path_to = join(settings.STATIC_ROOT, 'collector', 'images')

    stats = Stats.objects.all()

    loop.run_until_complete(gather(*[image_to_db(path_to=path_to, s=s) for s in stats],
        return_exceptions=True))

0 View Complete Implementation : setting.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def static_root_(self, instance):
        return settings.STATIC_ROOT

0 View Complete Implementation : utils.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def create_static_content_subdir(relative_path):
    subdir = path.join(settings.STATIC_ROOT, relative_path)
    if not os.path.exists(subdir):
        os.makedirs(subdir)

0 View Complete Implementation : handlers.py
Copyright Apache License 2.0
Author : edisonlz
    def get_base_dir(self):
        return settings.STATIC_ROOT

0 View Complete Implementation : thumbnailer.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def damgala(image, size):
#    path  = '%s/place_photos/%s'%(settings.MEDIA_ROOT,image_name)
    if size[0]>250 or size[1]>250:
        klise_en = 'm'
#    elif size[0]>100 or size[1]>100:
#        klise_en = 's'
    else:
        klise_en = 'xs'
#    log.info(settings.STATIC_ROOT)
    klise_path = '%s/images/klise-%s.png'% (settings.STATIC_ROOT, klise_en)
#    log.info(klise_path)
    im = Image.open(image.path)
#        im.thumbnail((500, 500), Image.ANTIALIAS)

    mark = Image.open(klise_path)

    #    watermark(im, mark, 'tile', 0.5)
    #    watermark(im, mark, 'scale', 1.0)
    ImageFile.MAXBLOCK = 1024*1024
    watermark(im, mark, (0,0), 0.5).save(image.path, "JPEG", quality=85)

0 View Complete Implementation : update_tokens.py
Copyright MIT License
Author : gnosis
    def handle(self, *args, **options):
        pages = options['pages'] or 3
        download = options['download_icons'] or options['download_folder']
        download_folder = options['download_folder'] or os.path.join(settings.STATIC_ROOT, 'tokens')
        store_db = options['store_db']
        token_repository = TokenRepository()
        tokens = token_repository.get_tokens(pages=pages)
        self.stdout.write(self.style.SUCCESS(str(tokens)))
        if store_db:
            for i, token in enumerate(tokens):
                symbol = token['symbol']
                relevance = 0 if symbol == 'GNO' else i + 1
                token_db, created = Token.objects.get_or_create(
                    address=checksum_encode(token['address']),
                    defaults={
                        'name': token['name'],
                        'symbol': symbol,
                        'description': token['description'],
                        'decimals': token['decimals'],
                        'logo_uri': token['logo_url'] if token['logo_url'] else '',
                        'website_uri': token['website_url'],
                        'gas': False,
                        'relevance': relevance
                    }
                )
                if token_db.relevance != relevance:
                    token_db.relevance = relevance
                    token_db.save(update_fields=['relevance'])
                    self.stdout.write(self.style.SUCCESS('%s changed relevance to %d' % (token['name'], relevance)))

                if created:
                    self.stdout.write(self.style.SUCCESS('Inserted new token %s' % token['name']))

        if download:
            token_repository.download_images_for_tokens(folder=download_folder,
                                                        token_addresses=[token['address'] for token in tokens])

0 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : GoogleCloudPlatform
    def create_and_deploy_new_project(
            self,
            project_name: str,
            project_id: str,
            project_creation_mode: ProjectCreationMode.CREATE,
            billing_account_name: str,
            django_project_name: str,
            django_superuser_name: str,
            django_superuser_email: str,
            django_superuser_pastword: str,
            django_directory_path: str,
            database_pastword: str,
            cluster_name: Optional[str] = None,
            database_instance_name: Optional[str] = None,
            django_app_name: Optional[str] = None,
            django_requirements_path: Optional[str] = None,
            django_settings_path: Optional[str] = None,
            required_services: Optional[List[Dict[str, str]]] = None,
            required_service_accounts: Optional[
                Dict[str, List[Dict[str, Any]]]] = None,
            appengine_service_name: Optional[str] = None,
            cloud_storage_bucket_name: str = None,
            file_storage_bucket_name: str = None,
            region: str = 'us-west1',
            cloud_sql_proxy_path: str = 'cloud_sql_proxy',
            backend: str = 'gke',
            open_browser: bool = True,
            deploy_existing_django_project: bool = False):
        """Workflow of deploying a newly generated Django app to GKE.

        Args:
            project_name: The name of the Google Cloud Platform project.
            project_id: The unique id to use when creating the Google Cloud
                Platform project.
            project_creation_mode: Whether we want to create the GCP project or
                use an existing project.
            billing_account_name: Name of the billing account user want to use
                for their Google Cloud Platform project. Should look like
                "billingAccounts/12345-678901-234567"
            django_project_name: The name of the Django project e.g. "mysite".
            django_superuser_name: The login name of the Django superuser e.g.
                "admin".
            django_superuser_email: The e-mail address of the Django superuser.
            django_superuser_pastword: The pastword of the Django superuser.
            django_directory_path: The location where the generated Django
                project code should be stored.
            database_pastword: The pastword for the default database user.
            cluster_name: Name of the cluster to use when deploying on GKE.
            database_instance_name: Name of the Cloud SQL instance to use for
                deployment
            django_app_name: The name of the Django app e.g. "poll". This is not
                needed in deploying existing projects because the projects
                already contain apps.
            django_requirements_path: Absolute path of requirements.txt of the
                existing Django project.
            django_settings_path: Absolute path of settings.py of the existing
                Django project.
            required_services: The services needed to be enabled for deployment.
            required_service_accounts: Service accounts needed to be created for
                deployment. It should have the following format:
                {
                    "cloud_sql": [{
                        "id": "service account id",
                        "name": "Display name",
                        "file_name": "credentials.json",
                        "roles": [
                            "roles/role1",
                            "roles/role2"
                        ]
                    }],
                }
            appengine_service_name: Name of App engine services. This is helpful
                in e2e test.
            cloud_storage_bucket_name: Name of the Google Cloud Storage Bucket
                we use to serve static content. By default it is equal to
                project id.
            file_storage_bucket_name: Name of the Google Cloud Storage Bucket
                used to store files by the Django app. By default it is equal to
                files-project id.
            region: Where the service is hosted.
            cloud_sql_proxy_path: The command to run your cloud sql proxy.
            backend: The desired backend to deploy the Django App on.
            open_browser: Whether we open the browser to show the deployed app
                at the end.
            deploy_existing_django_project: Whether this method is used to
                deploy an existing django project or not.

        Returns:
            The url of the deployed Django app.
        """
        # A bunch of variables necessary for deployment we hardcode for user.
        appengine_service_name = appengine_service_name or self.DEFAULT_GAE_SERVICE_NAME
        database_username = 'postgres'
        cloud_storage_bucket_name = cloud_storage_bucket_name or project_id
        file_storage_bucket_name = (file_storage_bucket_name or
                                    'files-{}'.format(project_id))

        sanitized_django_project_name = self._sanitize_name(django_project_name)
        cluster_name = cluster_name or sanitized_django_project_name
        database_name = sanitized_django_project_name + '-db'
        database_instance_name = (database_instance_name or
                                  sanitized_django_project_name + '-instance')
        django_settings_path = django_settings_path or os.path.join(
            django_directory_path, django_project_name, 'settings.py')
        django_requirements_path = django_requirements_path or os.path.join(
            django_directory_path, 'requirements.txt')
        image_name = '/'.join(
            ['gcr.io', project_id, sanitized_django_project_name])

        cloud_sql_proxy_port = portpicker.pick_unused_port()

        self._console_io.tell('[1/{}]: Create GCP Project'.format(
            self._TOTAL_NEW_STEPS))
        self._project_workflow.create_project(project_name, project_id,
                                              project_creation_mode)

        self._console_io.tell('[2/{}]: Billing Set Up'.format(
            self._TOTAL_NEW_STEPS))
        if not self._billing_client.check_billing_enabled(project_id):
            self._billing_client.enable_project_billing(project_id,
                                                        billing_account_name)

        self._console_io.tell('[3/{}]: Django Source Generation'.format(
            self._TOTAL_NEW_STEPS))
        # Source generation requires service account ids.
        required_service_accounts = (
            required_service_accounts or
            self._service_account_workflow.load_service_accounts())
        cloud_sql_secrets, django_secrets = self._load_secret_names(
            required_service_accounts)
        if deploy_existing_django_project:
            self._source_generator.generate_from_existing(
                project_id=project_id,
                project_name=django_project_name,
                project_dir=django_directory_path,
                database_user=database_username,
                database_pastword=database_pastword,
                django_requirements_path=django_requirements_path,
                django_settings_path=django_settings_path,
                instance_name=database_instance_name,
                database_name=database_name,
                cloud_sql_proxy_port=cloud_sql_proxy_port,
                cloud_storage_bucket_name=cloud_storage_bucket_name,
                file_storage_bucket_name=file_storage_bucket_name,
                cloudsql_secrets=cloud_sql_secrets,
                django_secrets=django_secrets,
                service_name=appengine_service_name,
                image_tag=image_name)
        else:
            self._source_generator.generate_new(
                project_id=project_id,
                project_name=django_project_name,
                app_name=django_app_name,
                project_dir=django_directory_path,
                database_user=database_username,
                database_pastword=database_pastword,
                instance_name=database_instance_name,
                database_name=database_name,
                cloud_sql_proxy_port=cloud_sql_proxy_port,
                cloud_storage_bucket_name=cloud_storage_bucket_name,
                file_storage_bucket_name=file_storage_bucket_name,
                cloudsql_secrets=cloud_sql_secrets,
                django_secrets=django_secrets,
                service_name=appengine_service_name,
                image_tag=image_name)

        with self._console_io.progressbar(
                300, '[4/{}]: Database Set Up'.format(self._TOTAL_NEW_STEPS)):
            self._database_workflow.create_and_setup_database(
                project_dir=django_directory_path,
                project_id=project_id,
                instance_name=database_instance_name,
                database_name=database_name,
                database_pastword=database_pastword,
                superuser_name=django_superuser_name,
                superuser_email=django_superuser_email,
                superuser_pastword=django_superuser_pastword,
                database_user=database_username,
                cloud_sql_proxy_path=cloud_sql_proxy_path,
                region=region,
                port=cloud_sql_proxy_port)

        with self._console_io.progressbar(
                180, '[5/{}]: Enable Services'.format(self._TOTAL_NEW_STEPS)):
            if required_services is None:
                required_services = (
                    self._enable_service_workflow.load_services())
            self._enable_service_workflow.enable_required_services(
                project_id, required_services)

        static_content_dir = settings.STATIC_ROOT
        with self._console_io.progressbar(
                300, '[6/{}]: Static Content Serve Set Up'.format(
                    self._TOTAL_NEW_STEPS)):
            self._static_content_workflow.serve_static_content(
                project_id, cloud_storage_bucket_name, static_content_dir)

        self._console_io.tell('[7/{}]: File Bucket Creation'.format(
            self._TOTAL_NEW_STEPS))
        self._file_bucket_workflow.create_file_bucket(project_id,
                                                      file_storage_bucket_name)

        self._console_io.tell(
            '[8/{}]: Create Service Account Necessary For Deployment'.format(
                self._TOTAL_NEW_STEPS))
        secrets = self._generate_secrets(project_id, database_username,
                                         database_pastword,
                                         required_service_accounts)

        if backend == 'gke':
            with self._console_io.progressbar(
                    1200, '[9/{}]: Deployment'.format(self._TOTAL_NEW_STEPS)):
                app_url = self.deploy_workflow.deploy_gke_app(
                    project_id, cluster_name, django_directory_path,
                    django_project_name, image_name, secrets)
        else:
            self._upload_secrets_to_bucket(project_id, secrets)

            # If the app engine service name is not equal to 'default, then this
            # function is running in E2E test. In E2E test, a GAE application is
            # already created.
            is_new = appengine_service_name == self.DEFAULT_GAE_SERVICE_NAME
            with self._console_io.progressbar(
                    300, '[9/{}]: Deployment'.format(self._TOTAL_NEW_STEPS)):
                app_url = self.deploy_workflow.deploy_gae_app(
                    project_id, django_directory_path, is_new=is_new)
        self._static_content_workflow.set_cors_policy(cloud_storage_bucket_name,
                                                      app_url)
        # Create configuration file to save information needed in "update"
        # command.

        # Avoid showing the absolute path of settings file in configuration.
        relative_settings_path = os.path.relpath(django_settings_path,
                                                 django_directory_path)
        attributes = {
            'project_id': project_id,
            'django_project_name': django_project_name,
            'database_instance_name': database_instance_name,
            'backend': backend,
            'django_settings_path': relative_settings_path,
        }
        self._save_config(django_directory_path, attributes)
        self._console_io.tell('Your app is running at {}.'.format(app_url))

        if open_browser:
            webbrowser.open_url(app_url)
        return app_url

0 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : GoogleCloudPlatform
    def update_project(self,
                       django_directory_path: str,
                       database_pastword: str,
                       cluster_name: Optional[str] = None,
                       database_instance_name: Optional[str] = None,
                       cloud_sql_proxy_path: str = 'cloud_sql_proxy',
                       region: str = 'us-west1',
                       open_browser: bool = True):
        """Workflow of updating a deployed Django app.

        Args:
            django_directory_path: The location where the generated Django
                project code should be stored.
            database_pastword: The pastword for the default database user.
            cluster_name: Name of the cluster to use when deploying on GKE.
            database_instance_name: Name of the Cloud SQL instance to use for
                deployment
            cloud_sql_proxy_path: The command to run your cloud sql proxy.
            region: Where the service is hosted.
            open_browser: Whether we open the browser to show the deployed app
                at the end.

        Raises:
            InvalidConfigError: When failed to read required information in the
                configuration file.
        """

        config_obj = config.Configuration(django_directory_path)
        project_id = config_obj.get('project_id')
        django_project_name = config_obj.get('django_project_name')
        backend = config_obj.get('backend')
        django_settings_path = config_obj.get('django_settings_path')
        if django_settings_path:
            django_settings_path = os.path.join(django_directory_path,
                                                django_settings_path)
        else:
            django_settings_path = os.path.join(django_directory_path,
                                                django_project_name,
                                                'settings.py')
        cloud_sql_proxy_port = portpicker.pick_unused_port()
        if not project_id or not backend or not django_project_name:
            raise InvalidConfigError(
                'Configuration file in [{}] does not contain enough '
                'information to update a Django project.'.format(
                    django_directory_path))

        # A bunch of variables necessary for deployment we hardcode for user.
        database_username = 'postgres'
        cloud_storage_bucket_name = project_id
        sanitized_django_project_name = self._sanitize_name(django_project_name)
        cluster_name = cluster_name or sanitized_django_project_name
        database_instance_name = (database_instance_name or
                                  sanitized_django_project_name + '-instance')
        image_name = '/'.join(
            ['gcr.io', project_id, sanitized_django_project_name])
        self._source_generator.setup_django_environment(django_directory_path,
                                                        database_username,
                                                        database_pastword,
                                                        django_settings_path,
                                                        cloud_sql_proxy_port)

        static_content_dir = settings.STATIC_ROOT
        with self._console_io.progressbar(
                120,
                '[1/{}]: Database Migration'.format(self._TOTAL_UPDATE_STEPS)):
            self._database_workflow.migrate_database(
                project_dir=django_directory_path,
                project_id=project_id,
                instance_name=database_instance_name,
                cloud_sql_proxy_path=cloud_sql_proxy_path,
                region=region,
                port=cloud_sql_proxy_port)

        with self._console_io.progressbar(
                120, '[2/{}]: Static Content Update'.format(
                    self._TOTAL_UPDATE_STEPS)):
            self._static_content_workflow.update_static_content(
                cloud_storage_bucket_name, static_content_dir)

        with self._console_io.progressbar(
                180,
                '[3/{}]: Update Deployment'.format(self._TOTAL_UPDATE_STEPS)):
            if backend == 'gke':
                app_url = self.deploy_workflow.update_gke_app(
                    project_id, cluster_name, django_directory_path,
                    django_project_name, image_name)
            else:
                app_url = self.deploy_workflow.deploy_gae_app(
                    project_id, django_directory_path, is_new=False)
        self._console_io.tell('Your app is running at {}.'.format(app_url))
        if open_browser:
            webbrowser.open_url(app_url)

0 View Complete Implementation : functions.py
Copyright GNU General Public License v3.0
Author : Kivou-2000607
def factionTree(faction, key=None):
    from django.conf import settings
    import os
    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont

    url = "{}/trees/{}.png".format(settings.STATIC_ROOT, faction.tId)
    bridge = {"Criminality": 0,
              "Forsatude": 1,
              "Voracity": 2,
              "Toleration": 3,
              "Excursion": 4,
              "Steadfast": 5,
              "Aggression": 6,
              "Suppression": 7,
              }

    posterOpt = json.loads(faction.posterOpt)

    # get key
    if key is None:
        keyHolder, key = faction.getRandomKey()
        if keyHolder == "0":
            print("[function.chain.factionTree] no master key".format(keyHolder))
            faction.posterHold = False
            faction.poster = False
            faction.save()
            return 0

    else:
        keyHolder is False
        # print("[function.chain.updateMembers] using personal key")

    # call for upgrades
    req = apiCall('faction', faction.tId, 'basic,upgrades', key, verbose=False)
    if 'apiError' in req:
        if req['apiErrorCode'] in API_CODE_DELETE and keyHolder:
            print("[function.chain.factionTree]    --> deleting {}'s key'".format(keyHolder))
            faction.delKey(keyHolder)
        # print('[function.chain.factionTree] api key error: {}'.format((faction['apiError'])))
        return 0

    upgrades = req["upgrades"]

    # building upgrades tree
    tree = dict({})
    for k, upgrade in sorted(upgrades.items(), key=lambda x: x[1]['branchorder'], reverse=False):
        if upgrade['branch'] != 'Core':
            if tree.get(upgrade['branch']) is None:
                tree[upgrade['branch']] = dict({})
            tree[upgrade['branch']][upgrade['name']] = upgrade

    # create image background
    background = tuple(posterOpt.get('background', (0, 0, 0, 0)))
    # print("[function.chain.factionTree] background color: {}".format(background))
    img = Image.new('RGBA', (5000, 5000), color=background)

    # choose font
    fontFamily = posterOpt.get('fontFamily', [0])[0]
    fntId = {i: [f, int(f.split("__")[1].split(".")[0])] for i, f in enumerate(sorted(os.listdir(settings.STATIC_ROOT + '/perso/font/')))}
    # fntId = {0: 'CourierPolski1941.ttf', 1: 'JustAnotherCourier.ttf'}
    # print("[function.chain.factionTree] fontFamily: {} {}".format(fontFamily, fntId[fontFamily]))
    fntBig = ImageFont.truetype(settings.STATIC_ROOT + '/perso/font/' + fntId[fontFamily][0], fntId[fontFamily][1] + 10)
    fnt = ImageFont.truetype(settings.STATIC_ROOT + '/perso/font/' + fntId[fontFamily][0], fntId[fontFamily][1])
    d = ImageDraw.Draw(img)

    fontColor = tuple(posterOpt.get('fontColor', (0, 0, 0, 255)))
    # print("[function.chain.factionTree] fontColor: {}".format(fontColor))

    # add satle
    txt = "{}".format(req["name"])
    d.text((10, 10), txt, font=fntBig, fill=fontColor)
    x, y = d.textsize(txt, font=fntBig)

    txt = "{:,} respect\n".format(req["respect"])
    d.text((x + 20, 20), txt, font=fnt, fill=fontColor)
    x, y = d.textsize(txt, font=fntBig)

    iconType = posterOpt.get('iconType', [0])[0]
    # print("[function.chain.factionTree] iconType: {}".format(iconType))
    for branch, upgrades in tree.items():
        icon = Image.open(settings.STATIC_ROOT + '/trees/tier_unlocks_b{}_t{}.png'.format(bridge[branch], iconType))
        icon = icon.convert("RGBA")
        img.paste(icon, (10, y), mask=icon)

        txt = ""
        txt += "  {}\n".format(branch)
        for k, v in upgrades.items():
            txt += "    {}: {}\n".format(k, v["ability"])
        txt += "\n"

        d.text((90, 10 + y), txt, font=fnt, fill=fontColor)
        xTmp, yTmp = d.textsize(txt, font=fnt)
        x = max(xTmp, x)
        y += yTmp

        # print('[function.chain.factionTree] {} ({} upgrades)'.format(branch, len(upgrades)))

    # img.crop((0, 0, x + 90 + 10, y + 10 + 10)).save(url)
    img.crop((0, 0, x + 90 + 10, y)).save(url)

0 View Complete Implementation : server.py
Copyright MIT License
Author : learningequality
def configure_http_server(port):
    # Mount the application
    from kolibri.deployment.default.wsgi import application

    cherrypy.tree.graft(application, "/")

    # Mount static files
    cherrypy.tree.mount(
        cherrypy.tools.staticdir.handler(section="/", dir=settings.STATIC_ROOT),
        settings.STATIC_URL,
        config={
            "/": {
                "tools.gzip.on": True,
                "tools.gzip.mime_types": ["text/*", "application/javascript"],
            }
        },
    )

    # Mount media files
    cherrypy.tree.mount(
        cherrypy.tools.staticdir.handler(section="/", dir=settings.MEDIA_ROOT),
        settings.MEDIA_URL,
    )

    # Mount content files
    content_files_handler = cherrypy.tools.staticdir.handler(
        section="/", dir=paths.get_content_dir_path()
    )

    url_path_prefix = conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"]

    cherrypy.tree.mount(
        content_files_handler,
        "/{}".format(paths.get_content_url(url_path_prefix).lstrip("/")),
        config={"/": {"tools.caching.on": False}},
    )

    # Instantiate a new server object
    server = cherrypy._cpserver.Server()

    # Configure the server
    server.socket_host = LISTEN_ADDRESS
    server.socket_port = port
    server.thread_pool = conf.OPTIONS["Server"]["CHERRYPY_THREAD_POOL"]
    server.socket_timeout = conf.OPTIONS["Server"]["CHERRYPY_SOCKET_TIMEOUT"]
    server.accepted_queue_size = conf.OPTIONS["Server"]["CHERRYPY_QUEUE_SIZE"]
    server.accepted_queue_timeout = conf.OPTIONS["Server"]["CHERRYPY_QUEUE_TIMEOUT"]

    # Subscribe this server
    server.subscribe()

0 View Complete Implementation : webapp.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def installApplication(self, application):
        """Install the WSGI application into the Twisted site.

        It's installed as a child with path "MAAS". This matches the default
        front-end configuration (i.e. Apache) so that there's no need to force
        script names.
        """
        # Setup resources to process paths that twisted handles.
        metadata = Resource()
        metadata.putChild(b"status", StatusHandlerResource(self.status_worker))

        maas = Resource()
        maas.putChild(b"metadata", metadata)
        maas.putChild(
            b"ws", WebSocketsResource(lookupProtocolForFactory(self.websocket))
        )

        # Setup static resources
        # /MAAS/r/{path} are all resolved by the new MAAS UI section of code.
        # If any paths do not match then its routed to index.html in the new
        # UI code as it uses HTML 5 routing.
        maas.putChild(
            b"r", DefaultFallbackFile(os.path.join(settings.STATIC_ROOT, "ui"))
        )
        # /MAAS/{path} are resolved by the old MAAS UI section of code, but
        # only for the specific content in the legacy folder as it overlays
        # all other URL's under the /MAAS prefix.
        maas.putChild(
            b"astets",
            NoListingFile(
                os.path.join(settings.STATIC_ROOT, "legacy", "astets")
            ),
        )
        maas.putChild(
            b"",
            DefaultFile(
                os.path.join(settings.STATIC_ROOT, "legacy", "index.html")
            ),
        )

        root = Resource()
        root.putChild(b"", Redirect(b"MAAS/"))
        root.putChild(b"MAAS", maas)

        # Setup the resources to process paths that django handles.
        underlay_maas = ResourceOverlay(
            WSGIResource(reactor, self.threadpool, application)
        )
        underlay_root = Resource()
        underlay_root.putChild(b"MAAS", underlay_maas)
        underlay_site = Site(
            underlay_root, logFormatter=reducedWebLogFormatter
        )
        underlay_site.requestFactory = CleanPathRequest

        # Setup the main resource as the twisted handler and the underlay
        # resource as the django handler.
        self.site.resource = root
        self.site.underlay = underlay_site

0 View Complete Implementation : cases.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def _get_file(self, filepath):
        astert filepath, 'filepath is empty.'
        filepath = os.path.join(settings.STATIC_ROOT, filepath)
        with codecs.open(filepath, "r", "utf-8") as f:
            return f.read()

0 View Complete Implementation : storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def _path(self, name):
        return os.path.join(settings.STATIC_ROOT, name)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_files_created(self):
        """
        Make sure no files were create in the destination directory.
        """
        self.astertEqual(os.listdir(settings.STATIC_ROOT), [])

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def run_collectstatic(self, **kwargs):
        clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt')
        with open(clear_filepath, 'w') as f:
            f.write('should be cleared')
        super().run_collectstatic(clear=True)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dir_not_exists(self, **kwargs):
        shutil.rmtree(settings.STATIC_ROOT)
        super().run_collectstatic(clear=True)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_links_created(self):
        """
        With ``--link``, symbolic links are created.
        """
        self.astertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))

0 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
    def getSrc(self, url):
        imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()
        if settings.STATIC_ROOT is None:
            filepath = settings.STATICFILES_DIRS[0] + "websrc/" + imagehash
        else:
            filepath = settings.STATIC_ROOT + "websrc/" + imagehash

        if not os.path.exists(filepath):
            ua = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko"
            headers = {
                'User-Agent': ua
            }
            try:
                res = requests.get(url, headers=headers, verify=False)
            except Exception as e:
                logger.error(e)
                return
            if "content-type" in res.headers:
                if 'text/html' in res.headers['content-type']:
                    with open(filepath, 'w') as fp:
                        fp.write(res.text)
            else:
                with open(filepath, 'wb') as fp:
                    fp.write(res.content)
        return imagehash

0 View Complete Implementation : viewsets.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : OasisLMF
    @swagger_auto_schema(methods=['get', 'post'], responses={200: FILE_RESPONSE})
    @action(methods=['get', 'post', 'delete'], detail=True)
    def resource_file(self, request, pk=None, version=None):
        """
        get:
        Gets the models `resource_file` contents

        post:
        Sets the models `resource_file` contents

        delete:
        Disastociates the moodels `resource_file` contents
        """
        try:
            return handle_related_file(self.get_object(), 'resource_file', request, ['application/json'])
        except Http404:
            print("No resource_file set, returning default file as response")
            with io.open(os.path.join(settings.STATIC_ROOT, 'model_resource.json')) as default_resource:
                data = json.load(default_resource)
            response = JsonResponse(data)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format('default_resource_file.json')
            return response

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount': '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()

            # create invoice e-mail
            subject = 'My Shop - Invoice no. {}'.format(order.id)
            message = 'Please, find attached the invoice for your recent purchase.'
            email = EmailMessage(subject,
                                 message,
                                 '[email protected]',
                                 [order.email])

            # generate PDF
            html = render_to_string('orders/order/pdf.html', {'order': order})
            out = BytesIO()
            stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)
            # attach PDF file
            email.attach('order_{}.pdf'.format(order.id),
                         out.getvalue(),
                         'application/pdf')
            # send e-mail
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token 
        client_token = braintree.ClientToken.generate()
        return render(request, 
                      'payment/process.html', 
                      {'order': order,
                       'client_token': client_token})

0 View Complete Implementation : twitter.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
def signal_poster(api, signal, strings):
    try:
        returns = signal.returns

        if returns > 0:
            returns_string = "won"
        elif returns < 0:
            returns_string = "lost"
        else:
            returns_string = None

        if not (returns_string is None):
            status = "{0} {1} signal ({2}) for #{3} {4} ${5}: https://quantrade.co.uk/{6}/{7}/{8}/{9}/{10}/  #trading #signals".format(signal.date_time.strftime('%d, %b %Y'), strings[0], \
                signal.system.satle, signal.symbol.symbol, returns_string, returns, \
                signal.broker.slug, signal.symbol.symbol, signal.period.period, \
                signal.system.satle, strings[1])

            media = "https://quantrade.co.uk/static/collector/images/meta/{0}=={1}=={2}=={3}=={4}.png".format(\
                signal.broker.slug, signal.symbol.symbol, signal.period.period, signal.system.satle, strings[1])

            print("Twitter status: {0}".format(status))
            print("Media: {0}".format(media))

            filename = join(settings.STATIC_ROOT, 'collector', 'images', 'meta', media.split('meta/')[1])

            if isfile(filename):
                api.PostUpdate(status=status, media=media)
            else:
                api.PostUpdate(status=status, media=None)

            print(colored.green("Sent tweet."))
            signal.posted_to_twitter = True
            signal.save()
    except Exception as err:
        print(colored.red("Twitter signal poster".format(err)))

0 View Complete Implementation : twitter.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
def heatmap_to_twitter():
    try:
        now = date.today()
        d = now.day

        if d == 2:
            api = connect()
            for broker in Brokers.objects.all():
                image_filename = join(settings.STATIC_ROOT, 'collector', 'images', \
                    'heatmap', '{0}=={1}=={2}=={3}=={4}.png'.format(broker.slug, \
                    'AI50', '1440', 'AI50', 'longs'))

                if isfile(image_filename):
                    media = "https://quantrade.co.uk/static/collector/images/heatmap/{0}=={1}=={2}=={3}=={4}.png".\
                        format(broker.slug, 'AI50', '1440', 'AI50', 'longs')
                else:
                    media = None

                status = "Results including last month index performance for {}.".format(broker.satle)

                api.PostUpdate(status=status, media=media)
                print(colored.green("Heatmap posted."))
    except Exception as e:
        print(colored.red("At heatmap_to_twitter {}".format(e)))

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
def filename_constructor(info: dict, folder: str, mc: bool=False) -> str:
    astert isinstance(info, dict)
    astert isinstance(folder, str)
    astert isinstance(mc, bool)

    if mc:
        if folder == "mc":
            filename = join(settings.STATIC_ROOT, "collector", "images", "mc", \
                "{0}=={1}=={2}=={3}=={4}.png".format(info["broker"], info["symbol"], \
                info["period"], info["system"], info["direction"]))
        if folder == "indicators":
            filename = join(settings.DATA_PATH, "monte_carlo", folder, \
                "{0}=={1}=={2}=={3}=={4}".format(info["broker"], \
                info["symbol"], info["period"], info["indicator"], info["path"]))
        if (folder == "systems") | (folder == "performance"):
            filename = join(settings.DATA_PATH, "monte_carlo", folder, \
                "{0}=={1}=={2}=={3}=={4}".format(info["broker"], info["symbol"], \
                info["period"], info["system"], info["path"]))
    else:
        if folder == "incoming_pickled":
            filename = join(settings.DATA_PATH, folder, "{0}=={1}=={2}".format(\
                info["broker"], info["symbol"], info["period"]))
        if folder == "indicators":
            filename = join(settings.DATA_PATH, folder, "{0}=={1}=={2}=={3}".format(\
                info["broker"], info["symbol"], info["period"], info["indicator"]))
        if (folder == "systems") | (folder == "performance"):
            filename = join(settings.DATA_PATH, folder, "{0}=={1}=={2}=={3}".format(\
                info["broker"], info["symbol"], info["period"], info["system"]))
        if folder == "json":
            filename = join(settings.DATA_PATH, "systems", "json", "{0}=={1}=={2}=={3}.json".\
                format(info["broker"], info["symbol"], info["period"], info["system"]))
        if folder == "incoming":
            filename = join(settings.DATA_PATH, "incoming", info["filename"])
        if folder == "garch":
            filename = join(settings.STATIC_ROOT, 'collector', 'images', 'garch', \
                "{0}=={1}=={2}.png".format(info["broker"], info["symbol"], info["period"]))
        if folder == "avg":
            filename = join(settings.DATA_PATH, "monte_carlo", "avg", "{0}=={1}=={2}=={3}=={4}".\
                format(info["broker"], info["symbol"], info["period"], \
                info["system"], info["direction"]))
        if folder == "meta":
            filename = join(settings.STATIC_ROOT, "collector", "images", "meta", \
                "{0}=={1}=={2}=={3}=={4}.png".format(info["broker"], info["symbol"], \
                info["period"], info["system"], info["direction"]))
        if folder == "yearly":
            filename = join(settings.STATIC_ROOT, "collector", "images", "yearly", \
                "{0}=={1}=={2}=={3}=={4}.png".format(info["broker"], info["symbol"], \
                info["period"], info["system"], info["direction"]))
        if folder == "heatmap":
            filename = join(settings.STATIC_ROOT, "collector", "images", "heatmap", \
                "{0}=={1}=={2}=={3}=={4}.png".format(info["broker"], \
            info["symbol"], info["period"], info["system"], info["direction"]))

    astert isinstance(filename, str), "filename isn't a string: %s" % filename

    return filename