当前位置: 首页>>代码示例>>Python>>正文


Python settings.BASE_DIR属性代码示例

本文整理汇总了Python中django.conf.settings.BASE_DIR属性的典型用法代码示例。如果您正苦于以下问题:Python settings.BASE_DIR属性的具体用法?Python settings.BASE_DIR怎么用?Python settings.BASE_DIR使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在django.conf.settings的用法示例。


在下文中一共展示了settings.BASE_DIR属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_schema

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def validate_schema(user, name, version):
    if not version:
        fn = os.path.join(ServerSettings.yang_path(user), name + '.yang')
    else:
        fn = os.path.join(ServerSettings.yang_path(user), name + '@'+ version + '.yang')
    
    if os.path.exists(fn):
        return None 

    dirpath = os.path.join(settings.BASE_DIR, ServerSettings.yang_path(user))
    sfile = os.path.basename(fn.split('@')[0])
    if not sfile.endswith('.yang'): 
        sfile = sfile + '.yang'

    for file in os.listdir(dirpath):
        yfile = os.path.basename(file.split('@')[0])
        if not yfile.endswith('.yang'):
            yfile = yfile + '.yang'
        if sfile == yfile: 
            return '[out-of-sync]'
    return '[not-exist]' 
开发者ID:CiscoDevNet,项目名称:yang-explorer,代码行数:23,代码来源:schema.py

示例2: dependencies_graph

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def dependencies_graph(username, modules=[]):
    depfile = os.path.join(ServerSettings.yang_path(username), 'dependencies.xml')
    if not os.path.exists(depfile):
        (rc, msg) = Compiler.compile_pyimport(username, None)
        if not rc:
            return rc, msg

    dgraph = DYGraph(depfile)
    g = dgraph.digraph([m.text.split('.yang')[0] for m in modules])
    if g is None:
        return (False, """Failed to generate dependency graph, please make sure that grapviz
python package is installed !!""")

    try:
        g.render(filename=os.path.join(settings.BASE_DIR, 'static', 'graph'))
    except:
        return (False, """Failed to render dependency graph, please make sure that grapviz
binaries (http://www.graphviz.org/Download.php) are installed on
the server !!""")

    return True, g.comment 
开发者ID:CiscoDevNet,项目名称:yang-explorer,代码行数:23,代码来源:admin.py

示例3: youtube_session

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def youtube_session() -> Iterator[requests.Session]:
    """This context opens a requests session and loads the youtube cookies file."""
    session = requests.session()
    try:
        with open(
            os.path.join(settings.BASE_DIR, "config/youtube_cookies.pickle"), "rb"
        ) as f:
            session.cookies.update(pickle.load(f))
    except FileNotFoundError:
        pass

    headers = {
        "User-Agent": youtube_dl.utils.random_user_agent(),
    }
    session.headers.update(headers)
    yield session

    with open(
        os.path.join(settings.BASE_DIR, "config/youtube_cookies.pickle"), "wb"
    ) as f:
        pickle.dump(session.cookies, f) 
开发者ID:raveberry,项目名称:raveberry,代码行数:23,代码来源:youtube.py

示例4: enable_streaming

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def enable_streaming(self, _request: WSGIRequest) -> HttpResponse:
        """Enable icecast streaming."""
        icecast_exists = False
        for line in subprocess.check_output(
            "systemctl list-unit-files --full --all".split(), universal_newlines=True
        ).splitlines():
            if "icecast2.service" in line:
                icecast_exists = True
                break

        if not icecast_exists:
            return HttpResponseBadRequest("Please install icecast2")

        subprocess.call(["sudo", "/usr/local/sbin/raveberry/enable_streaming"])
        config_file = os.path.join(settings.BASE_DIR, "setup/mopidy_icecast.conf")
        self.update_mopidy_config(config_file)
        return HttpResponse() 
开发者ID:raveberry,项目名称:raveberry,代码行数:19,代码来源:system.py

示例5: start

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def start(self) -> None:
        self.current_frame = [0 for _ in range(self.bars)]
        self.growing_frame = b""
        try:
            # delete old contents of the pipe
            os.remove(self.cava_fifo_path)
        except FileNotFoundError:
            # the file does not exist
            pass
        try:
            os.mkfifo(self.cava_fifo_path)
        except FileExistsError:
            # the file already exists
            logging.info("%s already exists while starting", self.cava_fifo_path)

        self.cava_process = subprocess.Popen(
            ["cava", "-p", os.path.join(settings.BASE_DIR, "config/cava.config")],
            cwd=settings.BASE_DIR,
        )
        # cava_fifo = open(cava_fifo_path, 'r')
        self.cava_fifo = os.open(self.cava_fifo_path, os.O_RDONLY | os.O_NONBLOCK) 
开发者ID:raveberry,项目名称:raveberry,代码行数:23,代码来源:programs.py

示例6: handle

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def handle(self, *args, **options):
        """"""
        ovpn = Ovpn.objects.filter(activated=True)
        if ovpn.exists():
            self._kill_old_process()
            ovpn = ovpn[0]
            print >> sys.stdout, "Config: {0.path}".format(ovpn.file)
            auth_filepath = os.path.join(settings.BASE_DIR, "vpn{0.vpn.pk}.auth.txt".format(ovpn))
            with open(auth_filepath, "w") as auth:
                auth.write(ovpn.vpn.username + '\n')
                auth.write(ovpn.vpn.password + '\n')
            # get file content
            with open(ovpn.file.path, "r") as vpn:
                vpn_file_content = vpn.readlines()
            # change file
            for index, line in enumerate(vpn_file_content):
                if re.match(self.vpn_param + '.*', line):
                    vpn_file_content[index] = "{0.vpn_param} {1:s}\n".format(self, auth_filepath)
                    break
            # write new data
            with open(ovpn.file.path, "w") as vpn:
                vpn.write(''.join(vpn_file_content))
            # vpn activate
            sh.openvpn(ovpn.file.path, _out=sys.stdout) 
开发者ID:alexsilva,项目名称:openvpn-admin,代码行数:26,代码来源:openvpn.py

示例7: analyze

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def analyze(request):
    # pwd = settings.BASE_DIR
    pwd = settings.ROOT_PATH
    JSON_FILE = pwd + '/don/ovs/don.json'

    params = {
        'error_file': pwd + '/don/templates/don/don.error.txt',
        'test:all': True,
        'test:ping': False,
        'test:ping_count': 1,
        'test:ovs': True,
        'test:report_file': pwd + '/don/templates/don/don.report.html',
    }
    print "params ====> ", params
    analyzer.analyze(JSON_FILE, params)
    # output = analyzer.analyze(JSON_FILE, params)
    # html = '<html><body>Output: %s</body></html>' % output
    # return HttpResponse(html)
    # return HttpResponseRedirect('/static/don.report.html')
    return render(request, "don/ovs/analyze.html")
    # return render_to_response('don/ovs/analyze.html') 
开发者ID:CiscoSystems,项目名称:don,代码行数:23,代码来源:views.py

示例8: collect

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def collect(request):
    macro = {'collect_status': 'Collection failed'}
    status = 0

    BASE_DIR = settings.ROOT_PATH
    # CUR_DIR = os.getcwd()
    os.chdir(BASE_DIR + '/don/ovs')
    cmd = 'sudo python collector.py'
    for line in run_command(cmd):
        if line.startswith('STATUS:') and line.find('Writing collected info') != -1:
            status = 1
            macro['collect_status'] = \
                "Collecton successful. Click visualize to display"
    # res = collector.main()
    os.chdir(BASE_DIR)
    if status:
        messages.success(request, macro['collect_status'])
    else:
        messages.error(request, macro['collect_status'])
    resp = HttpResponse(json.dumps(macro), content_type="application/json")
    return resp 
开发者ID:CiscoSystems,项目名称:don,代码行数:23,代码来源:views.py

示例9: handle

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def handle(self, *args, **options):
        js_names = options['js_name']
        js_host = options.get('js_host')
        fake = options.get('fake', False)
        # Start handle
        fake_result = []
        for i, js_name in enumerate(js_names):
            remote_url = self.get_remote_url(settings, DJANGO_ECHARTS_SETTINGS, js_name, js_host)
            local_url = DJANGO_ECHARTS_SETTINGS.generate_local_url(js_name)
            local_path = settings.BASE_DIR + local_url.replace('/', os.sep)  # url => path
            fake_result.append((remote_url, local_path, local_url))
            if fake:
                self.stdout.write('[Info] Download Meta for [{}]'.format(js_name))
                self.stdout.write('        Remote Url: {}'.format(remote_url))
                self.stdout.write('        Local  Url: {}'.format(local_url))
                self.stdout.write('        Local Path: {}'.format(local_path))
            else:
                self.download_js_file(remote_url, local_path) 
开发者ID:kinegratii,项目名称:django-echarts,代码行数:20,代码来源:_download.py

示例10: download_files

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def download_files(self):
        print('Download Files')
        file_list = open('%s/data/files/all_files.txt' % (settings.BASE_DIR), 'w')
        s3credentials = S3Credential.objects.all()
        for s3credential in s3credentials:
            print(s3credential.name)
            for bucket_name in s3credential.buckets.splitlines():
                session = boto3.Session(
                    aws_access_key_id=s3credential.access_key,
                    aws_secret_access_key=s3credential.secret_key
                )
                s3 = session.resource('s3')
                bucket = s3.Bucket(bucket_name)
                print(bucket)
                for key in bucket.objects.all():
                    if key.size != 0:
                        file = [str(key.last_modified), str(key.size), bucket.name, key.key]
                        file_list.writelines('%s\n' % ('\t'.join(file)))
        self.stdout.write(self.style.SUCCESS('Successfully downloaded files!')) 
开发者ID:raonyguimaraes,项目名称:mendelmd,代码行数:21,代码来源:update_files.py

示例11: handle

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def handle(self, *args, **options):
        print('Hello World Import Files')
        start_time = time.time()
        print('Download Files')
        command = 'mkdir -p {}/data/files/'.format(settings.BASE_DIR)
        run(command, shell=True)
        file_list = open('%s/data/files/all_files.txt' % (settings.BASE_DIR), 'w')
        s3credentials = S3Credential.objects.all()
        for s3credential in s3credentials:
            print(s3credential.name)
            for bucket_name in s3credential.buckets.splitlines():
                session = boto3.Session(
                    aws_access_key_id=s3credential.access_key,
                    aws_secret_access_key=s3credential.secret_key
                )
                s3 = session.resource('s3')
                bucket = s3.Bucket(bucket_name)
                print(bucket)
                for key in bucket.objects.all():
                    if key.size != 0:
                        file = [str(key.last_modified), str(key.size), bucket.name, key.key]
                        file_list.writelines('%s\n' % ('\t'.join(file)))
        self.stdout.write(self.style.SUCCESS('Successfully downloaded files!'))
        elapsed_time = time.time() - start_time
        print('Importing Files Took {}'.format(elapsed_time)) 
开发者ID:raonyguimaraes,项目名称:mendelmd,代码行数:27,代码来源:download_files.py

示例12: config

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def config():
    """Database config."""
    service_name = ENVIRONMENT.get_value("DATABASE_SERVICE_NAME", default="").upper().replace("-", "_")
    if service_name:
        engine = engines.get(ENVIRONMENT.get_value("DATABASE_ENGINE"), engines["postgresql"])
    else:
        engine = engines["postgresql"]

    name = ENVIRONMENT.get_value("DATABASE_NAME", default="postgres")

    if not name and engine == engines["sqlite"]:
        name = os.path.join(settings.BASE_DIR, "db.sqlite3")

    db_config = {
        "ENGINE": engine,
        "NAME": name,
        "USER": ENVIRONMENT.get_value("DATABASE_USER", default="postgres"),
        "PASSWORD": ENVIRONMENT.get_value("DATABASE_PASSWORD", default="postgres"),
        "HOST": ENVIRONMENT.get_value(f"{service_name}_SERVICE_HOST", default="localhost"),
        "PORT": ENVIRONMENT.get_value(f"{service_name}_SERVICE_PORT", default=15432),
    }

    database_cert = ENVIRONMENT.get_value("DATABASE_SERVICE_CERT", default=None)
    return _cert_config(db_config, database_cert) 
开发者ID:project-koku,项目名称:koku,代码行数:26,代码来源:database.py

示例13: test_can_modify_uploaded_file_with_edit_post

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def test_can_modify_uploaded_file_with_edit_post(self):
        uploaded_file = SimpleUploadedFile(AttachmentModelTest.SAVED_TEST_FILE_NAME_1,
                                           open(AttachmentModelTest.UPLOAD_TEST_FILE_NAME, 'rb').read())
        Attachment.objects.create(post=self.default_post, attachment=uploaded_file)

        self.assertEqual(Attachment.objects.get(post=self.default_post).attachment.name,
                         AttachmentModelTest.SAVED_TEST_FILE_NAME_1)

        upload_file = open(os.path.join(settings.BASE_DIR, 'test_file/attachment_test_2.txt'))
        self.client.post(reverse('board:edit_post', args=[self.default_post.id]), {
            'title': 'some post title',
            'content': 'some post content',
            'attachment': upload_file,
        })

        self.assertEqual(Attachment.objects.get(post=self.default_post).attachment.name,
                         AttachmentModelTest.SAVED_TEST_FILE_NAME_2) 
开发者ID:kboard,项目名称:kboard,代码行数:19,代码来源:test_views.py

示例14: test_record_edited_attachment_if_attachment_is_modified

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def test_record_edited_attachment_if_attachment_is_modified(self):
        uploaded_file = SimpleUploadedFile(AttachmentModelTest.SAVED_TEST_FILE_NAME_1,
                                           open(AttachmentModelTest.UPLOAD_TEST_FILE_NAME, 'rb').read())
        origin_attachment = Attachment.objects.create(post=self.default_post, attachment=uploaded_file)

        upload_file = open(os.path.join(settings.BASE_DIR, 'test_file/attachment_test_2.txt'))
        self.client.post(reverse('board:edit_post', args=[self.default_post.id]), {
            'title': 'NEW POST TITLE',
            'content': 'NEW POST CONTENT',
            'attachment': upload_file,
        })

        origin_attachment.refresh_from_db()
        new_attachment = Attachment.objects.get(post=self.default_post)
        edtied_post_history = EditedPostHistory.objects.get(post=self.default_post)

        self.assertEqual(origin_attachment.post, None)
        self.assertEqual(origin_attachment.editedPostHistory, edtied_post_history)
        self.assertEqual(new_attachment.post, self.default_post)
        self.assertEqual(new_attachment.editedPostHistory, None) 
开发者ID:kboard,项目名称:kboard,代码行数:22,代码来源:test_views.py

示例15: get_filepath_to_log

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import BASE_DIR [as 别名]
def get_filepath_to_log(device_type, logfile="", device_id=None):
    # get_filepath_to_log is being broken out so that we can use it in help/other templates to display which log file
    # is being loaded
    if device_type == "brewpi":
        try:
            device = BrewPiDevice.objects.get(id=device_id)
            log_filename = 'dev-{}-{}.log'.format(str(device.circus_parameter()).lower(), logfile)
        except:
            # Unable to load the device
            raise ValueError("No brewpi device with id {}".format(device_id))

    elif device_type == "spawner":
        log_filename = 'fermentrack-processmgr.log'
    elif device_type == "fermentrack":
        log_filename = 'fermentrack-stderr.log'
    elif device_type == "ispindel":
        log_filename = 'ispindel_raw_output.log'
    elif device_type == "upgrade":
        log_filename = 'upgrade.log'
    else:
        return None

    # Once we've determined the filename from logfile and device_type, let's open it up & read it in
    logfile_path = os.path.join(settings.BASE_DIR, 'log', log_filename)
    return logfile_path 
开发者ID:thorrak,项目名称:fermentrack,代码行数:27,代码来源:clog.py


注:本文中的django.conf.settings.BASE_DIR属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。