Example #1
0
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)
Example #2
0
    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)
Example #3
0
 def handle_label(self, theme_name, **options):
     """
     Create a new Django app and copy all available templates into it.
     """
     super(Command, self).handle_label(theme_name, **options)
     # Build a unique list of template names from ``INSTALLED_APPS`` and 
     # ``TEMPLATE_DIRS`` then determine which template files they belong
     # to and copy them to the theme/templates directory.
     templates = set()
     for app in settings.INSTALLED_APPS:
         if app.startswith("django.") or app in settings.OPTIONAL_APPS:
             continue
         templates_path = os.path.join(path_for_import(app), "templates")
         for (root, dirs, files) in os.walk(templates_path):
             for f in files:
                 template = os.path.join(root, f)[len(templates_path):]
                 if not template.startswith("/admin/"):
                     templates.add(template.lstrip("/"))
     templates_path = os.path.join(theme_name, "templates")
     os.mkdir(templates_path)
     for template in templates:
         path_from = unicode(template_path(template))
         path_to = os.path.join(templates_path, template)
         try:
             os.makedirs(os.path.dirname(path_to))
         except OSError:
             pass
         copy(path_from, path_to)
     copytree(settings.MEDIA_ROOT, os.path.join(theme_name, "media"))
Example #4
0
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)
Example #5
0
def create_project():
    """
    Copies the contents of the project_template directory to a new directory
    specified as an argument to the command line.
    """

    parser = OptionParser(usage="usage: %prog [options] project_name")
    parser.add_option("-a", "--alternate", dest="alt", metavar="PACKAGE", 
        help="Alternate package to use, containing a project_template")
    parser.add_option("-s", "--source", dest="copy_source", default=False,
        action="store_true", help="Copy package source to new project")
    parser.add_option("-t", "--templates", dest="copy_templates", default=True,
        action="store_false", help="Copy templates to the project [default]")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("project_name must be specified")
    project_name = args[0]
    if project_name.startswith("-"):
        parser.error("project_name cannot start with '-'")
    project_path = os.path.join(os.getcwd(), project_name)

    # Ensure the given directory name doesn't clash with an existing Python
    # package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error("'%s' conflicts with the name of an existing "
            "Python module and cannot be used as a project name. "
            "Please try another name." % project_name)
    
    # Create the list of packages to build from - at this stage it should 
    # only be one or two names, mezzanine plus an alternate package.
    packages = ["mezzanine"]
    if options.alt:
        packages.append(options.alt)
    for package_name in packages:
        try:
            __import__(package_name)
        except ImportError:
            parser.error("Could not import package '%s'" % package_name) 

    # Build the project up copying over the project_template from each of 
    # the packages.
    for package_name in packages:
        package_path = path_for_import(package_name)
        if options.copy_source:
            copy_tree(package_path, os.path.join(project_path, package_name))
        copy_tree(os.path.join(package_path, "project_template"), project_path)
        move(os.path.join(project_path, "local_settings.py.template"),
            os.path.join(project_path, "local_settings.py"))
        if options.copy_templates:
            template_path = os.path.join(project_path, "templates")
            for app_dir in os.listdir(package_path):
                template_dir = os.path.join(package_path, app_dir, "templates")
                if os.path.isdir(template_dir):
                    copy_tree(template_dir, template_path)

    # Generate a unique SECREY_KEY for the project's setttings module.
    settings_path = os.path.join(os.getcwd(), project_name, "settings.py")
    with open(settings_path, "r") as f:
        data = f.read()
    with open(settings_path, "w") as f:
        secret_key = "%s%s%s" % (uuid4(), uuid4(), uuid4())
        f.write(data.replace("%(SECRET_KEY)s", secret_key))

    # Clean up pyc files.
    for (root, dirs, files) in os.walk(project_path, False):
        for f in files:
            if f.endswith(".pyc"):
                os.remove(os.path.join(root, f))
Example #6
0
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")
    
    # Set ADMIN_MEDIA_PREFIX for Grappelli.
    if s.get("PACKAGE_NAME_GRAPPELLI") in s["INSTALLED_APPS"]:
        # 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"
            s["ADMIN_MEDIA_PREFIX"] = "http://%s:%s%s" % (addr, port, 
                                                  s["ADMIN_MEDIA_PREFIX"])

    # 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]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume it's 
            # in the project directory and add the path to it.
            s["DATABASES"][key]["NAME"] = os.path.join(
                                     s.get("_project_path", ""), db["NAME"])
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
        elif shortname.startswith("postgresql") and not s.get("TIME_ZONE", 1):
            # Specifying a blank time zone to fall back to the system's 
            # time zone will break table creation in Postgres so remove it.
            del s["TIME_ZONE"]

    # If a theme is defined then add its template path to the template dirs.
    theme = s.get("THEME")
    if theme:
        theme_templates = os.path.join(path_for_import(theme), "templates")
        s["TEMPLATE_DIRS"] = [theme_templates] + list(s["TEMPLATE_DIRS"])
        
    # Remaining code is for Django 1.1 support.
    if VERSION >= (1, 2, 0):
        return
    # Add the dummy csrf_token template tag to builtins and remove 
    # Django's CsrfViewMiddleware.
    add_to_builtins("mezzanine.core.templatetags.dummy_csrf")
    s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if 
                        mw != "django.middleware.csrf.CsrfViewMiddleware"]
    # Use the single DB settings.
    old_db_settings_mapping = {
        "ENGINE": "DATABASE_ENGINE",
        "HOST": "DATABASE_HOST",
        "NAME": "DATABASE_NAME",
        "OPTIONS": "DATABASE_OPTIONS",
        "PASSWORD": "******",
        "PORT": "DATABASE_PORT",
        "USER": "******",
        "TEST_CHARSET": "TEST_DATABASE_CHARSET",
        "TEST_COLLATION": "TEST_DATABASE_COLLATION",
        "TEST_NAME": "TEST_DATABASE_NAME",
    }
    for (new_name, old_name) in old_db_settings_mapping.items():
        value = s["DATABASES"]["default"].get(new_name)
        if value is not None:
            if new_name == "ENGINE" and value.startswith(backend_path):
                value = value.replace(backend_path, "", 1)
            s[old_name] = value
    
    # Revert to some old names.
    processors = list(s["TEMPLATE_CONTEXT_PROCESSORS"])
    for (i, processor) in enumerate(processors):
        if processor == "django.contrib.auth.context_processors.auth":
            processors[i] = "django.core.context_processors.auth"
    s["TEMPLATE_CONTEXT_PROCESSORS"] = processors
    loaders = list(s["TEMPLATE_LOADERS"])
    for (i, loader) in enumerate(loaders):
        if loader.startswith("django.") and loader.endswith(".Loader"):
            loaders[i] = loader.replace(".Loader", ".load_template_source", 1)
    s["TEMPLATE_LOADERS"] = loaders
Example #7
0
from django.conf.urls.defaults import *
from django.contrib import admin

from mezzanine.conf import settings
from mezzanine.utils.path import path_for_import


admin.autodiscover()

urlpatterns = patterns("",
    ("^admin/", include(admin.site.urls)),
    ("^", include("mezzanine.urls")),
)

if getattr(settings, "DEV_SERVER", False):
    media_root = settings.MEDIA_ROOT
    theme = getattr(settings, "THEME")
    if theme:
        media_root = path_for_import(theme)
    urlpatterns += patterns("",
        ("^%s/(?P<path>.*)$" % settings.MEDIA_URL.strip("/"),
            "django.views.static.serve", {"document_root": media_root}),
        ("^favicon.ico$", 
            "django.views.static.serve", {"document_root": media_root, 
                                          "path": "img/favicon.ico"}),
    )
Example #8
0
#!/usr/bin/env python

# When project_template is used as the actual project during Mezzanine
# development, insert the development path into sys.path so that the
# development version of Mezzanine is used rather than the installed version.
import os
import sys
project_path = os.path.dirname(os.path.abspath(__file__))
project_dir = project_path.split(os.sep)[-1]
if project_dir == "project_template":
    dev_path = os.path.abspath(os.path.join(project_path, "..", ".."))
    if dev_path not in sys.path:
        sys.path.insert(0, dev_path)
    from mezzanine.utils.path import path_for_import
    mezzanine_path = path_for_import("mezzanine")
    assert os.path.abspath(os.path.join(mezzanine_path, "..")) == dev_path

from django.core.management import execute_manager
try:
    import settings  # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the "
        "directory containing %r. It appears you've customized things.\n"
        "You'll have to run django-admin.py, passing it your settings module.\n"
        "(If the file settings.py does indeed exist, it's causing an "
        "ImportError somehow.)\n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
    execute_manager(settings)
Example #9
0
        else:
            INSTALLED_APPS += (app,)
INSTALLED_APPS = sorted(list(INSTALLED_APPS), reverse=True)

# Optional app settings.
from mezzanine.utils.path import path_for_import
from mezzanine.utils.conf import set_dynamic_settings

if "debug_toolbar" in INSTALLED_APPS:
    DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False}
    MIDDLEWARE_CLASSES += ("debug_toolbar.middleware.DebugToolbarMiddleware",)
if PACKAGE_NAME_GRAPPELLI in INSTALLED_APPS:
    GRAPPELLI_ADMIN_HEADLINE = "Mezzanine"
    GRAPPELLI_ADMIN_TITLE = "Mezzanine"
    GRAPPELLI_MEDIA_PATH = os.path.join(
                             path_for_import(PACKAGE_NAME_GRAPPELLI), "media")
if PACKAGE_NAME_FILEBROWSER in INSTALLED_APPS:
    FILEBROWSER_URL_FILEBROWSER_MEDIA = "/filebrowser/media/"
    FILEBROWSER_PATH_FILEBROWSER_MEDIA = os.path.join(
            path_for_import(PACKAGE_NAME_FILEBROWSER), "media", "filebrowser")

# Caching.
CACHE_BACKEND = ""
CACHE_TIMEOUT = CACHE_MIDDLEWARE_SECONDS = 0
try:
    import cmemcache
except ImportError:
    try:
        import memcache
    except ImportError:
        CACHE_BACKEND = "locmem:///"