本文整理汇总了Python中unipath.FSPath.child方法的典型用法代码示例。如果您正苦于以下问题:Python FSPath.child方法的具体用法?Python FSPath.child怎么用?Python FSPath.child使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unipath.FSPath
的用法示例。
在下文中一共展示了FSPath.child方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: document
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def document(request, lang, version, url):
if lang != 'en' or version != 'dev': raise Http404()
docroot = Path(settings.DOCS_PICKLE_ROOT)
# First look for <bits>/index.fpickle, then for <bits>.fpickle
bits = url.strip('/').split('/') + ['index.fpickle']
doc = docroot.child(*bits)
if not doc.exists():
bits = bits[:-2] + ['%s.fpickle' % bits[-2]]
doc = docroot.child(*bits)
if not doc.exists():
raise Http404("'%s' does not exist" % doc)
bits[-1] = bits[-1].replace('.fpickle', '')
template_names = [
'docs/%s.html' % '-'.join([b for b in bits if b]),
'docs/doc.html'
]
return render_to_response(template_names, RequestContext(request, {
'doc': pickle.load(open(doc, 'rb')),
'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')),
'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()),
'home': urlresolvers.reverse('document-index', kwargs={'lang':lang, 'version':version}),
'search': urlresolvers.reverse('document-search', kwargs={'lang':lang, 'version':version}),
'redirect_from': request.GET.get('from', None),
}))
示例2: handle_noargs
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def handle_noargs(self, **kwargs):
try:
verbose = int(kwargs['verbosity']) > 0
except (KeyError, TypeError, ValueError):
verbose = True
for release in DocumentRelease.objects.all():
if verbose:
print "Updating %s..." % release
destdir = Path(settings.DOCS_BUILD_ROOT).child(release.lang, release.version)
if not destdir.exists():
destdir.mkdir(parents=True)
# Make an SCM checkout/update into the destination directory.
# Do this dynamically in case we add other SCM later.
getattr(self, 'update_%s' % release.scm)(release.scm_url, destdir)
# Make the directory for the JSON files - sphinx-build doesn't
# do it for us, apparently.
json_build_dir = destdir.child('_build', 'json')
if not json_build_dir.exists():
json_build_dir.mkdir(parents=True)
# "Shell out" (not exactly, but basically) to sphinx-build.
sphinx.cmdline.main(['sphinx-build',
'-b', 'json', # Use the JSON builder
'-q', # Be vewy qwiet
destdir, # Source file directory
json_build_dir, # Destination directory
])
示例3: handle_noargs
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def handle_noargs(self, **options):
project_dir = Path(__file__).absolute().ancestor(4)
data_file = project_dir.child("static", "js", "station_polys.json")
with open(data_file, "r") as f:
data = json.loads(f.read())
for station_id, coords in data.items():
station = Station.objects.get(id=station_id)
station.polygon = coords
station.save()
示例4: run_benchmarks
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def run_benchmarks(control, benchmark_dir, benchmarks, trials, record_dir=None, profile_dir=None):
if benchmarks:
print "Running benchmarks: %s" % " ".join(benchmarks)
else:
print "Running all benchmarks"
if record_dir:
record_dir = Path(record_dir).expand().absolute()
if not record_dir.exists():
raise ValueError('Recording directory "%s" does not exist' % record_dir)
print "Recording data to '%s'" % record_dir
control_label = get_django_version(control, vcs=None)
branch_info = ""
print "Benchmarking: Django %s (in %s%s)" % (control_label, branch_info, control)
print " Control: %s" % cpython
print " Experiment: %s" % pypy
print
control_env = {'PYTHONPATH': '.:%s:%s' % (Path(control).absolute(), Path(benchmark_dir))}
for benchmark in discover_benchmarks(benchmark_dir):
if not benchmarks or benchmark.name in benchmarks:
print "Running '%s' benchmark ..." % benchmark.name
settings_mod = '%s.settings' % benchmark.name
control_env['DJANGO_SETTINGS_MODULE'] = settings_mod
experiment_env = control_env.copy()
if profile_dir is not None:
control_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "cpython-%s" % benchmark.name)
experiment_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "pypy-%s" % benchmark.name)
try:
control_data = run_benchmark(benchmark, trials, control_env, cpython)
experiment_data = run_benchmark(benchmark, trials, experiment_env, pypy)
except SkipBenchmark, reason:
print "Skipped: %s\n" % reason
continue
options = argparse.Namespace(
track_memory = False,
diff_instrumentation = False,
benchmark_name = benchmark.name,
disable_timelines = True,
)
result = perf.CompareBenchmarkData(control_data, experiment_data, options)
if record_dir:
record_benchmark_results(
dest = record_dir.child('%s.json' % benchmark.name),
name = benchmark.name,
result = result,
control = 'cpython',
experiment = 'pypy',
control_data = control_data,
experiment_data = experiment_data,
)
print format_benchmark_result(result, len(control_data.runtimes))
print
示例5: search
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def search(request, lang, version):
if lang != 'en' or version != 'dev': raise Http404()
docroot = Path(settings.DOCS_PICKLE_ROOT)
# Remove the 'cof' GET variable from the query string so that the page
# linked to by the Javascript fallback doesn't think its inside an iframe.
mutable_get = request.GET.copy()
if 'cof' in mutable_get:
del mutable_get['cof']
return render_to_response('docs/search.html', RequestContext(request, {
'query': request.GET.get('q'),
'query_string': mutable_get.urlencode(),
'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')),
'home': urlresolvers.reverse('document-index', kwargs={'lang':lang, 'version':version}),
'search': urlresolvers.reverse('document-search', kwargs={'lang':lang, 'version':version}),
}))
示例6: env_or_default
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
import os
import dj_database_url
from unipath import FSPath as Path
def env_or_default(NAME, default):
return os.environ.get(NAME, default)
PROJECT_ROOT = Path(__file__).ancestor(3)
PACKAGE_ROOT = PROJECT_ROOT.child('djangocon')
BASE_DIR = PACKAGE_ROOT
DEBUG = bool(int(os.environ.get("DEBUG", "1")))
DATABASES = {
"default": dj_database_url.config(default="postgres://localhost/djangocon2016")
}
ALLOWED_HOSTS = [
os.environ.get("GONDOR_INSTANCE_DOMAIN"),
"2016.djangocon.us",
"www.djangocon.us",
"localhost',"
]
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
示例7: Path
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
# -*- coding: utf-8 -*-
from unipath import FSPath as Path
PROJECT_ROOT = Path(__file__).absolute().ancestor(2)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": PROJECT_ROOT.child("dev.db"),
"USER": "",
"PASSWORD": "",
"HOST": "",
"PORT": "",
}
}
# -- django-celery
REDIS_CONNECT_RETRY = True
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 0
BROKER_HOST = REDIS_HOST
BROKER_PORT = REDIS_PORT
BROKER_VHOST = REDIS_DB
示例8: str
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = PROJECT_DIR.child('static_root')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
# Additional locations of static files
STATICFILES_DIRS = (
str(PROJECT_DIR.child('static')),
)
示例9: Path
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
# -*- coding: utf-8 -*-
import sys
from unipath import FSPath as Path
PROJECT_ROOT = Path(__file__).absolute().ancestor(2)
sys.path.insert(0, PROJECT_ROOT.child("apps"))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ("Your Name", "[email protected]"),
)
MANAGERS = ADMINS
TIME_ZONE = None
LANGUAGE_CODE = "en-us"
SITE_ID = 1
USE_I18N = True
USE_L10N = True
STATIC_ROOT = PROJECT_ROOT.child("static")
STATIC_URL = "/static/"
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
示例10: str
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
######################################
# Media/Static
######################################
MEDIA_ROOT = PROJECT_DIR.parent.child('data')
MEDIA_URL = '/media/'
STATIC_ROOT = PROJECT_DIR.child('static_root')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
str(PROJECT_DIR.child('static')),
)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
######################################
示例11: Path
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
from unipath import FSPath as Path
BASE = Path(__file__).parent
DEBUG = TEMPLATE_DEBUG = platform.node() != 'jacobian.org'
MANAGERS = ADMINS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE.child('nn.db'),
}
}
MIDDLEWARE_CLASSES = []
SITE_ID = 1
SECRET_KEY = 'LOCAL' if DEBUG else open('/home/web/sekrit.txt').read().strip()
ROOT_URLCONF = 'djangome.urls'
INSTALLED_APPS = ['djangome', 'gunicorn']
TEMPLATE_DIRS = [BASE.child('templates')]
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
示例12: Path
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
import os
import platform
from unipath import FSPath as Path
### Utilities
# The full path to the repository root.
BASE = Path(__file__).absolute().ancestor(2)
# Far too clever trick to know if we're running on the deployment server.
PRODUCTION = ('DJANGOPROJECT_DEBUG' not in os.environ)
# It's a secret to everybody
with open(BASE.child('secrets.json')) as handle:
SECRETS = json.load(handle)
### Django settings
ADMINS = (
('Adrian Holovaty', '[email protected]'),
('Jacob Kaplan-Moss', '[email protected]'),
)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': SECRETS.get('memcached_host', '127.0.0.1:11211'),
} if PRODUCTION else {
示例13: CLI
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
class CLI(object):
"""
Usage:
chucks library <name>
chucks module <name>
chucks course <name>
chucks build [<course>...]
chucks deploy
chucks clean
"""
def __init__(self, stdout=None, stderr=None, libpath=None):
self.out = stdout or sys.stdout
self.err = stderr or sys.stderr
self.library = Library(libpath) if libpath else None
self.support_path = Path(__file__).parent.child('support')
self._modules = {}
def run(self, *argv):
commands = [line.split()[1] for line in CLI.__doc__.strip().split('\n')[1:]]
arguments = docopt.docopt(CLI.__doc__, argv=argv, version='Chucks 1.0')
for command in commands:
if arguments[command]:
try:
getattr(self, 'do_' + command)(arguments)
except CLIError as e:
self.err.write(e.message)
self.rv = 1
self.rv = 0
return self.rv
def do_library(self, arguments):
"""
Create a new library.
"""
# FIXME: author, copyright should be flags and/or interactive prompts.
library = Library(Path(arguments['<name>']).absolute())
library.create()
def do_module(self, arguments):
"""
Create a new module.
"""
mod = Module(self.library.module_path.child(arguments['<name>']))
mod.create()
def do_course(self, arguments):
"""
Create a new course.
"""
# FIXME: title, modules from flags/prompt
course = Course(self.library.course_path.child('%s.yaml' % arguments['<name>']))
course.create(modules=[str(d.name) for d in self.library.module_path.listdir(filter=DIRS)])
def do_build(self, arguments):
# If no course arguments are given, build all the courses.
if arguments['<course>']:
try:
courses = [self.library.courses[c] for c in arguments['<course>']]
except KeyError:
raise CLIError("No such course:", c)
else:
courses = self.library.courses.values()
for course in courses:
self.out.write(u'Building %s\n' % course.title)
# Make the dest directory.
dest = self.library.build_path.child(course.slug)
if dest.exists():
dest.rmtree()
dest.mkdir(parents=True)
# Create the sphinx support directories (_static, _templates) by
# merging directories from the internal chucks-support directory
# and from the library's theme if it exists. This has to happen
# before building the handounts and Sphinx docs because both those
# steps uses these components.
for subdir in ('_static', '_templates'):
chucksdir = self.support_path.child(subdir)
themedir = self.library.theme_path.child(subdir)
sources = [d for d in (chucksdir, themedir) if d.exists()]
if not dest.child(subdir).exists():
dest.child(subdir).mkdir()
fileutils.merge_trees(sources, dest.child(subdir))
# Write out an auth.json for the deployment step. This should
# probably actually become part of the deployment step at some point.
if hasattr(course, 'auth'):
json.dump(course.auth, open(dest.child('auth.json'), 'w'))
# Handouts have to go first: Sphinx links to the handouts.
self._build_handouts(course)
self._build_sphinx(course)
# Copy over any extra files to be downloaded. FIXME: This is a nasty
# hack. Inject these into toc.html as download links?
for fname in getattr(course, 'downloads', []):
p = Path(fname)
if p.isabsolute():
#.........这里部分代码省略.........
示例14:
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
'PASSWORD': SECRETS.get('db_password', ''),
},
'trac': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'code.djangoproject',
'USER': 'code.djangoproject',
'HOST': SECRETS.get('trac_db_host', ''),
'PASSWORD': SECRETS.get('trac_db_password', ''),
}
}
DATABASE_ROUTERS = ['tracdb.db_router.TracRouter']
DEFAULT_FROM_EMAIL = "[email protected]"
FIXTURE_DIRS = [PROJECT_PACKAGE.child('fixtures')]
INSTALLED_APPS = [
'accounts',
'aggregator',
'blog',
'cla',
'contact',
'dashboard',
'docs.apps.DocsConfig',
'legacy',
'releases',
'svntogit',
'tracdb',
'fundraising',
示例15: test_module_create
# 需要导入模块: from unipath import FSPath [as 别名]
# 或者: from unipath.FSPath import child [as 别名]
def test_module_create(tmpdir):
p = Path(str(tmpdir))
m = Module(p)
m.create()
assert ls(p) == ['exercises', 'module.yaml']
assert yaml.safe_load(open(p.child('module.yaml'))) == {'title': p.name.replace('_', ' ').title()}