本文整理汇总了Python中mezzanine.utils.importing.path_for_import函数的典型用法代码示例。如果您正苦于以下问题:Python path_for_import函数的具体用法?Python path_for_import怎么用?Python path_for_import使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了path_for_import函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_pep8_for_package
def run_pep8_for_package(package_name):
"""
If pep8 is installed, run it across the given package name
returning any warnings or errors found.
"""
import pep8
package_path = path_for_import(package_name)
pep8.process_options(["-r", package_path])
class Checker(pep8.Checker):
"""
Subclass pep8's Checker to hook into error reporting.
"""
def report_error(self, line_number, offset, text, check):
"""
Store pairs of line numbers and errors.
"""
self.errors.append((line_number, text.split(" ", 1)[1]))
def check_all(self, *args, **kwargs):
"""
Assign the errors attribute and return it after running.
"""
self.errors = []
super(Checker, self).check_all(*args, **kwargs)
return self.errors
def pep8_checker(path):
for line_number, text in Checker(path).check_all():
yield "%s:%s: %s" % (path, line_number, text)
return _run_checker_for_package(pep8_checker, package_name)
示例2: main
def main(package="mezzanine"):
"""
This is the main test function called via ``python setup.py test``.
It's responsible for hacking the ``project_template`` dir into
an actual project to test against.
"""
from mezzanine.utils.importing import path_for_import
os.environ["DJANGO_SETTINGS_MODULE"] = "project_template.test_settings"
package_path = path_for_import(package)
project_path = os.path.join(package_path, "project_template")
local_settings_path = os.path.join(project_path, "local_settings.py")
test_settings_path = os.path.join(project_path, "test_settings.py")
sys.path.insert(0, package_path)
sys.path.insert(0, project_path)
if not os.path.exists(test_settings_path):
shutil.copy(local_settings_path + ".template", test_settings_path)
with open(test_settings_path, "r") as f:
local_settings = f.read()
with open(test_settings_path, "w") as f:
test_reqs_str = """
from project_template import settings
globals().update(settings.__dict__)
INSTALLED_APPS = list(settings.INSTALLED_APPS) + ["mezzanine.accounts"]
"""
if django.VERSION >= (1, 7):
test_reqs_str += "import django\ndjango.setup()"
f.write(test_reqs_str + local_settings)
atexit.register(lambda: os.remove(test_settings_path))
from django.core.management.commands import test
sys.exit(test.Command().execute(verbosity=1))
示例3: main
def main(package="mezzanine"):
"""
This is the main test function called via ``python setup.py test``.
It's responsible for hacking the ``project_template`` dir into
an actual project to test against.
"""
from mezzanine.utils.importing import path_for_import
package_path = path_for_import(package)
project_path = os.path.join(package_path, "project_template")
os.environ["DJANGO_SETTINGS_MODULE"] = "project_name.test_settings"
project_app_path = os.path.join(project_path, "project_name")
local_settings_path = os.path.join(project_app_path, "local_settings.py")
test_settings_path = os.path.join(project_app_path, "test_settings.py")
sys.path.insert(0, package_path)
sys.path.insert(0, project_path)
if not os.path.exists(test_settings_path):
shutil.copy(local_settings_path + ".template", test_settings_path)
with open(test_settings_path, "r") as f:
local_settings = f.read()
with open(test_settings_path, "w") as f:
test_settings = """
from . import settings
globals().update(i for i in settings.__dict__.items() if i[0].isupper())
# Require the mezzanine.accounts app. We use settings.INSTALLED_APPS here so
# the syntax test doesn't complain about an undefined name.
if "mezzanine.accounts" not in settings.INSTALLED_APPS:
INSTALLED_APPS = list(settings.INSTALLED_APPS) + ["mezzanine.accounts"]
# Use the MD5 password hasher by default for quicker test runs.
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
"""
f.write(test_settings + local_settings)
def cleanup_test_settings():
import os # Outer scope sometimes unavailable in atexit functions.
for fn in [test_settings_path, test_settings_path + "c"]:
try:
os.remove(fn)
except OSError:
pass
atexit.register(cleanup_test_settings)
django.setup()
from django.core.management.commands import test
sys.exit(test.Command().execute(verbosity=1))
示例4: handle_label
def handle_label(self, theme_name, **options):
"""
Copy the templates and media files for the given theme package into
the current project.
"""
try:
theme_path = path_for_import(theme_name)
except ImportError:
raise CommandError("Could not import the theme: %s" % theme_name)
copy_paths = (
(os.path.join(theme_path, "templates"),
settings.TEMPLATE_DIRS[-1]),
(os.path.join(theme_path, "media"),
settings.MEDIA_ROOT),
)
if options.get("interactive"):
confirm = raw_input("""
Theme installation may overwrite existing template and media files.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """)
if confirm != "yes":
raise CommandError("Theme installation cancelled.")
for (path_from, path_to) in copy_paths:
if os.path.exists(path_from):
copy_tree(path_from, path_to)
示例5: main
def main(package="mezzanine"):
"""
This is the main test function called via ``python setup.py test``.
It's responsible for hacking the ``project_template`` dir into
an actual project to test against.
"""
from mezzanine.utils.importing import path_for_import
os.environ["DJANGO_SETTINGS_MODULE"] = "project_template.settings"
package_path = path_for_import(package)
project_path = os.path.join(package_path, "project_template")
local_settings_path = os.path.join(project_path, "local_settings.py")
sys.path.insert(0, package_path)
sys.path.insert(0, project_path)
if not os.path.exists(local_settings_path):
shutil.copy(local_settings_path + ".template", local_settings_path)
from django.conf import settings
apps = list(settings.INSTALLED_APPS)
if "mezzanine.accounts" not in apps:
apps += ["mezzanine.accounts"]
with open(local_settings_path, "a") as f:
f.write("INSTALLED_APPS = %s" % apps)
atexit.register(lambda: os.remove(local_settings_path))
from django.core.management.commands import test
sys.exit(test.Command().execute(verbosity=1))
示例6: _run_checker_for_package
def _run_checker_for_package(checker, package_name, extra_ignore=None):
"""
Runs the checker function across every Python module in the
given package.
"""
ignore_strings = IGNORE_ERRORS
if extra_ignore:
ignore_strings += extra_ignore
package_path = path_for_import(package_name)
for (root, dirs, files) in os.walk(package_path):
for f in files:
# Ignore migrations.
directory = root.split(os.sep)[-1]
# Using native_str here avoids the dreaded UnicodeDecodeError
# on Py2 with filenames with high-bit characters when
# unicode_literals in effect:
ext = native_str(".py")
if (f == "local_settings.py" or not f.endswith(ext)
or directory == "migrations"):
continue
for warning in checker(os.path.join(root, f)):
for ignore in ignore_strings:
if ignore in warning:
break
else:
yield warning.replace(package_path, package_name, 1)
示例7: run_pyflakes_for_package
def run_pyflakes_for_package(package_name, extra_ignore=None):
"""
If pyflakes is installed, run it across the given package name
returning any warnings found.
"""
ignore_strings = PYFLAKES_IGNORE
if extra_ignore:
ignore_strings += extra_ignore
try:
from pyflakes.checker import Checker
except ImportError:
return []
warnings = []
for (root, dirs, files) in os.walk(path_for_import(package_name)):
for f in files:
# Ignore migrations.
directory = root.split(os.sep)[-1]
if not f.endswith(".py") or directory == "migrations":
continue
path = os.path.join(root, f)
with open(path, "U") as source_file:
source = source_file.read()
try:
compile(source, f, "exec")
except (SyntaxError, IndentationError), value:
info = (path, value.lineno, value.args[0])
warnings.append("Invalid syntax in %s:%d: %s" % info)
result = Checker(parse(source), path)
for warning in result.messages:
message = unicode(warning)
for ignore in ignore_strings:
if ignore in message:
break
else:
warnings.append(message)
示例8: _run_checker_for_package
def _run_checker_for_package(checker, package_name):
"""
Runs the checker function across every Python module in the
given package.
"""
package_path = path_for_import(package_name)
for (root, dirs, files) in os.walk(package_path):
for f in files:
# Ignore migrations.
directory = root.split(os.sep)[-1]
if not f.endswith(".py") or directory == "migrations":
continue
for warning in checker(os.path.join(root, f)):
yield warning.replace(package_path, package_name, 1)
示例9: build_deploy_docs
def build_deploy_docs(docs_path):
try:
from fabric.main import load_fabfile
except ImportError:
warn("Couldn't build fabfile.rst, fabric not installed")
return
project_template_path = path_for_import("mezzanine.project_template")
commands = load_fabfile(os.path.join(project_template_path, "fabfile"))[1]
lines = []
for name in sorted(commands.keys()):
doc = commands[name].__doc__.strip().split("\n")[0]
lines.append(" * ``fab %s`` - %s" % (name, doc))
with open(os.path.join(docs_path, "fabfile.rst"), "w") as f:
f.write("\n".join(lines))
示例10: serve_with_theme
def serve_with_theme(request, path):
"""
Mimics ``django.views.static.serve`` for serving files from
``MEDIA_ROOT`` during development, first checking for the file
in the theme defined by the ``THEME`` setting if specified.
"""
theme = getattr(settings, "THEME")
if theme:
theme_root = os.path.join(path_for_import(theme), "media")
try:
return serve(request, path, document_root=theme_root)
except Http404:
pass
return serve(request, path, document_root=settings.MEDIA_ROOT)
示例11: copy_test_to_media
def copy_test_to_media(module, name):
"""
Copies a file from Mezzanine's test data path to MEDIA_ROOT.
Used in tests and demo fixtures.
"""
mezzanine_path = path_for_import(module)
test_path = os.path.join(mezzanine_path, "static", "test", name)
to_path = os.path.join(settings.MEDIA_ROOT, name)
to_dir = os.path.dirname(to_path)
if not os.path.exists(to_dir):
os.makedirs(to_dir)
if os.path.isdir(test_path):
copy = copytree
else:
copy = copyfile
copy(test_path, to_path)
示例12: runtests
def runtests():
import os, sys, shutil, atexit
from mezzanine.utils.importing import path_for_import
os.environ["DJANGO_SETTINGS_MODULE"] = "project_template.settings"
mezz_path = path_for_import("mezzanine")
sys.path.insert(0, mezz_path)
project_path = os.path.join(mezz_path, "project_template")
local_settings_path = os.path.join(project_path, "local_settings.py")
if not os.path.exists(local_settings_path):
shutil.copy(local_settings_path + ".template", local_settings_path)
atexit.register(lambda: os.remove(local_settings_path))
from django.core.management.commands import test
sys.exit(test.Command().execute(verbosity=1))
示例13: runtests
def runtests():
import os, sys, shutil, atexit
from mezzanine.utils.importing import path_for_import
os.environ["DJANGO_SETTINGS_MODULE"] = "project_template.settings"
mezz_path = path_for_import("mezzanine")
project_path = os.path.join(mezz_path, "project_template")
local_settings_path = os.path.join(project_path, "local_settings.py")
sys.path.insert(0, mezz_path)
sys.path.insert(0, project_path)
if not os.path.exists(local_settings_path):
shutil.copy(local_settings_path + ".template", local_settings_path)
with open(local_settings_path, "a") as f:
f.write("""
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.redirects",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.sitemaps",
"django.contrib.staticfiles",
"mezzanine.boot",
"mezzanine.conf",
"mezzanine.core",
"mezzanine.generic",
"mezzanine.blog",
"mezzanine.forms",
"mezzanine.pages",
"mezzanine.galleries",
"mezzanine.twitter",
"mezzanine.accounts",
"mezzanine.mobile",
)
""")
atexit.register(lambda: os.remove(local_settings_path))
from django.core.management.commands import test
sys.exit(test.Command().execute(verbosity=1))
示例14: _run_checker_for_package
def _run_checker_for_package(checker, package_name, extra_ignore=None):
"""
Runs the checker function across every Python module in the
given package.
"""
ignore_strings = IGNORE_ERRORS
if extra_ignore:
ignore_strings += extra_ignore
package_path = path_for_import(package_name)
for (root, dirs, files) in os.walk(str(package_path)):
for f in files:
if f == "local_settings.py" or not f.endswith(".py") or root.split(os.sep)[-1] in ["migrations"]:
# Ignore
continue
for warning in checker(os.path.join(root, f)):
for ignore in ignore_strings:
if ignore in warning:
break
else:
yield warning.replace(package_path, package_name, 1)
示例15: set_dynamic_settings
def set_dynamic_settings(s):
"""
Called at the end of the project's settings module and is passed its
globals dict for updating with some final tweaks for settings that
generally aren't specified but can be given some better defaults based on
other settings that have been specified. Broken out into its own
function so that the code need not be replicated in the settings modules
of other project-based apps that leverage Mezzanine's settings module.
"""
s["TEMPLATE_DEBUG"] = s["DEBUG"]
add_to_builtins("mezzanine.template.loader_tags")
# Define some settings based on management command being run.
management_command = sys.argv[1] if len(sys.argv) > 1 else ""
# Some kind of testing is running via test or testserver
s["TESTING"] = management_command.startswith("test")
# Some kind of development server is running via runserver or runserver_plus
s["DEV_SERVER"] = management_command.startswith("runserver")
# Change INSTALLED_APPS to a list for easier manipulation.
s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])
# Setup for optional apps.
if not s["TESTING"]:
for app in s.get("OPTIONAL_APPS", []):
if app not in s["INSTALLED_APPS"]:
try:
__import__(app)
except ImportError:
pass
else:
s["INSTALLED_APPS"].append(app)
if "debug_toolbar" in s["INSTALLED_APPS"]:
debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
if debug_mw not in s["MIDDLEWARE_CLASSES"]:
s["MIDDLEWARE_CLASSES"] = tuple(s["MIDDLEWARE_CLASSES"])
s["MIDDLEWARE_CLASSES"] += (debug_mw,)
if s.get("PACKAGE_NAME_FILEBROWSER") in s["INSTALLED_APPS"]:
s["FILEBROWSER_URL_FILEBROWSER_MEDIA"] = "/filebrowser/media/"
fb_path = path_for_import(s["PACKAGE_NAME_FILEBROWSER"])
fb_media_path = os.path.join(fb_path, "media", "filebrowser")
s["FILEBROWSER_PATH_FILEBROWSER_MEDIA"] = fb_media_path
grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
s["GRAPPELLI_INSTALLED"] = grappelli_name in s["INSTALLED_APPS"]
if s["GRAPPELLI_INSTALLED"]:
# Ensure Grappelli is after Mezzanine in app order so that
# admin templates are loaded in the correct order.
s["INSTALLED_APPS"].remove(grappelli_name)
s["INSTALLED_APPS"].append(grappelli_name)
s["GRAPPELLI_ADMIN_HEADLINE"] = "Mezzanine"
s["GRAPPELLI_ADMIN_TITLE"] = "Mezzanine"
grappelli_path = path_for_import(s["PACKAGE_NAME_GRAPPELLI"])
s["GRAPPELLI_MEDIA_PATH"] = os.path.join(grappelli_path, "media")
# Adopted from django.core.management.commands.runserver
# Easiest way so far to actually get all the media for Grappelli
# working with the dev server is to hard-code the host:port to
# ADMIN_MEDIA_PREFIX, so here we check for a custom host:port
# before doing this.
if len(sys.argv) >= 2 and sys.argv[1] == "runserver":
addrport = ""
if len(sys.argv) > 2:
addrport = sys.argv[2]
if not addrport:
addr, port = "", "8000"
else:
try:
addr, port = addrport.split(":")
except ValueError:
addr, port = "", addrport
if not addr:
addr = "127.0.0.1"
parts = (addr, port, s["ADMIN_MEDIA_PREFIX"])
s["ADMIN_MEDIA_PREFIX"] = "http://%s:%s%s" % parts
# Ensure admin is last in the app order so that admin templates
# are loaded in the correct order.
if "django.contrib.admin" in s["INSTALLED_APPS"]:
s["INSTALLED_APPS"].remove("django.contrib.admin")
s["INSTALLED_APPS"].append("django.contrib.admin")
# Change INSTALLED_APPS back to a tuple.
s["INSTALLED_APPS"] = tuple(s["INSTALLED_APPS"])
# Caching.
if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if not
mw.endswith("UpdateCacheMiddleware") or
mw.endswith("FetchFromCacheMiddleware")]
# Some settings tweaks for different DB engines.
backend_path = "django.db.backends."
backend_shortnames = (
"postgresql_psycopg2",
"postgresql",
"mysql",
"sqlite3",
"oracle",
)
for (key, db) in s["DATABASES"].items():
if db["ENGINE"] in backend_shortnames:
s["DATABASES"][key]["ENGINE"] = backend_path + db["ENGINE"]
shortname = db["ENGINE"].split(".")[-1]
#.........这里部分代码省略.........