예제 #1
0
    def __init__(self, config, engine=None):
        self.config = convert_to_attr_dict(config)

        # Connect to the database
        if engine is None:
            engine = sqlalchemy.create_engine(self.config.database.url)

        self.engine = engine

        # Create our Store instance and associate our store modules with it
        self.models = AttributeDict()
        for name, mod_path in six.iteritems(self.model_names):
            mod_name, klass = mod_path.rsplit(":", 1)
            mod = importlib.import_module(mod_name)
            self.models[name] = getattr(mod, klass)(self.metadata, self.engine)

        # Setup our URL routing
        url_rules = []
        for name in self.url_names:
            mod = importlib.import_module(name)
            url_rules.extend(getattr(mod, "__urls__"))
        self.urls = Map(url_rules)

        # Setup our Jinja2 Environment
        self.templates = jinja2.Environment(
            auto_reload=self.config.debug,
            loader=jinja2.PrefixLoader({
                "legacy": jinja2.PackageLoader("warehouse.legacy"),
            }),
        )
예제 #2
0
    def __init__(self, config, engine=None, redis=None):
        self.config = convert_to_attr_dict(config)

        self.metadata = db.metadata

        # configure logging
        logging.config.dictConfig(self.config.logging)

        # Connect to the database
        if engine is None and self.config.get("database", {}).get("url"):
            engine = sqlalchemy.create_engine(self.config.database.url)
        self.engine = engine

        # Create our redis connection
        if redis is None and self.config.get("redis", {}).get("url"):
            redis = redispy.StrictRedis.from_url(self.config.redis.url)
        self.redis = redis

        # Create our Store instance and associate our store modules with it
        self.db = AttributeDict()
        for name, klass in self.db_classes.items():
            self.db[name] = klass(
                self,
                self.metadata,
                self.engine,
                self.redis,
            )

        # Create our Search Index instance and associate our mappings with it
        self.search = Index(self.db, self.config.search)
        self.search.register(ProjectMapping)

        # Set up our URL routing
        self.urls = urls.urls

        # Initialize our Translations engine
        self.trans = babel.support.NullTranslations()

        # Setup our Jinja2 Environment
        self.templates = jinja2.Environment(
            autoescape=True,
            auto_reload=self.config.debug,
            extensions=[
                "jinja2.ext.i18n",
            ],
            loader=jinja2.PackageLoader("warehouse"),
        )

        # Install Babel
        self.templates.filters.update({
            "package_type_display": packaging_helpers.package_type_display,
            "format_number": babel.numbers.format_number,
            "format_decimal": babel.numbers.format_decimal,
            "format_percent": babel.numbers.format_percent,
            "format_date": babel.dates.format_date,
            "format_datetime": babel.dates.format_datetime,
            "format_time": babel.dates.format_time,
        })

        # Install our translations
        self.templates.install_gettext_translations(self.trans, newstyle=True)

        # Add our Powered By Middleware
        self.wsgi_app = PoweredBy(self.wsgi_app, "Warehouse {} ({})".format(
            warehouse.__version__,
            warehouse.__build__,
        ))

        # Add our Content Security Policy Middleware
        img_src = ["'self'"]
        if self.config.camo:
            camo_parsed = urllib_parse.urlparse(self.config.camo.url)
            img_src += [
                "{}://{}".format(camo_parsed.scheme, camo_parsed.netloc),
                "https://secure.gravatar.com",
            ]
        else:
            img_src += ["*"]

        self.wsgi_app = guard.ContentSecurityPolicy(
            self.wsgi_app,
            {
                "default-src": ["'self'"],
                "font-src": ["'self'", "data:"],
                "img-src": img_src,
                "style-src": ["'self'", "cloud.typography.com"],
            },
        )

        if "sentry" in self.config:
            self.wsgi_app = Sentry(self.wsgi_app, Client(**self.config.sentry))

        # Serve the static files that are packaged as part of Warehouse
        self.wsgi_app = WhiteNoise(
            self.wsgi_app,
            root=os.path.abspath(
                os.path.join(
                    os.path.dirname(warehouse.__file__), "static", "compiled",
                ),
            ),
            prefix="/static/",
            max_age=31557600,
        )
예제 #3
0
def test_convert_to_attribute_dict():
    adict = convert_to_attr_dict({"a": {"b": 1, "c": 2}})

    assert adict.a == {"b": 1, "c": 2}
    assert adict.a.b == 1
    assert adict.a.c == 2
예제 #4
0
    def __init__(self, config, engine=None, redis_class=redis.StrictRedis):
        self.config = convert_to_attr_dict(config)

        self.metadata = db.metadata

        # configure logging
        logging.config.dictConfig(self.config.logging)

        # Connect to the database
        if engine is None and self.config.get("database", {}).get("url"):
            engine = sqlalchemy.create_engine(self.config.database.url)
        self.engine = engine

        # Create our redis connections
        self.redises = {
            key: redis_class.from_url(url)
            for key, url in self.config.redis.items()
        }

        # Create our Store instance and associate our store modules with it
        self.db = AttributeDict()
        for name, klass in self.db_classes.items():
            self.db[name] = klass(
                self,
                self.metadata,
                self.engine,
                self.redises["downloads"],
            )

        # Create our Search Index instance and associate our mappings with it
        self.search = Index(self.db, self.config.search)
        self.search.register(ProjectMapping)

        # Set up our URL routing
        self.urls = urls.urls

        # Initialize our Translations engine
        self.translations = babel.support.NullTranslations()

        # Setup our Jinja2 Environment
        self.templates = jinja2.Environment(
            autoescape=True,
            auto_reload=self.config.debug,
            extensions=[
                "jinja2.ext.i18n",
            ],
            loader=jinja2.PackageLoader("warehouse"),
        )

        # Install Babel
        self.templates.filters.update({
            "package_type_display": packaging_helpers.package_type_display,
            "format_number": babel.numbers.format_number,
            "format_decimal": babel.numbers.format_decimal,
            "format_percent": babel.numbers.format_percent,
            "format_date": babel.dates.format_date,
            "format_datetime": babel.dates.format_datetime,
            "format_time": babel.dates.format_time,
        })

        # Install our translations
        self.templates.install_gettext_translations(
            self.translations,
            newstyle=True,
        )

        # Setup our password hasher
        self.passlib = passlib.context.CryptContext(
            schemes=[
                "bcrypt_sha256",
                "bcrypt",
                "django_bcrypt",
                "unix_disabled",
            ],
            default="bcrypt_sha256",
            deprecated=["auto"],
        )

        # Setup our session storage
        self.session_store = RedisSessionStore(
            self.redises["sessions"],
            session_class=Session,
        )

        # Add our Content Security Policy Middleware
        img_src = ["'self'"]
        if self.config.camo:
            camo_parsed = urllib.parse.urlparse(self.config.camo.url)
            img_src += [
                "{}://{}".format(camo_parsed.scheme, camo_parsed.netloc),
                "https://secure.gravatar.com",
            ]
        else:
            img_src += ["*"]

        self.wsgi_app = guard.ContentSecurityPolicy(
            self.wsgi_app,
            {
                "default-src": ["'self'"],
                "font-src": ["'self'", "data:"],
                "img-src": img_src,
                "style-src": ["'self'", "cloud.typography.com"],
            },
        )

        if "sentry" in self.config:
            self.wsgi_app = Sentry(self.wsgi_app, Client(**self.config.sentry))

        # Serve the static files that are packaged as part of Warehouse
        self.wsgi_app = WhiteNoise(
            self.wsgi_app,
            root=self.static_dir,
            prefix=self.static_path,
            max_age=31557600,
        )

        # Add our Powered By Middleware
        self.wsgi_app = HeaderRewriterFix(
            self.wsgi_app,
            add_headers=[
                (
                    "X-Powered-By",
                    "Warehouse {__version__} ({__build__})".format(
                        __version__=warehouse.__version__,
                        __build__=warehouse.__build__,
                    ),
                ),
            ],
        )
예제 #5
0
    def __init__(self, config, engine=None, redis=None):
        self.config = convert_to_attr_dict(config)

        # Connect to the database
        if engine is None and self.config.get("database", {}).get("url"):
            engine = sqlalchemy.create_engine(self.config.database.url)
        self.engine = engine

        # Create our redis connection
        if redis is None and self.config.get("redis", {}).get("url"):
            redis = redispy.StrictRedis.from_url(self.config.redis.url)
        self.redis = redis

        # Create our Store instance and associate our store modules with it
        self.models = AttributeDict()
        for name, mod_path in self.model_names.items():
            mod_name, klass = mod_path.rsplit(":", 1)
            mod = importlib.import_module(mod_name)
            self.models[name] = getattr(mod, klass)(
                self,
                self.metadata,
                self.engine,
                self.redis,
            )

        # Create our Search Index instance and associate our mappings with it
        self.search = Index(self.models, self.config.search)
        self.search.register(ProjectMapping)

        # Set up our URL routing
        self.urls = urls.urls

        # Initialize our Translations engine
        self.trans = babel.support.NullTranslations()

        # Setup our Jinja2 Environment
        self.templates = jinja2.Environment(
            autoescape=True,
            auto_reload=self.config.debug,
            extensions=[
                "jinja2.ext.i18n",
            ],
            loader=jinja2.PackageLoader("warehouse"),
        )

        # Install Babel
        self.templates.filters.update({
            "package_type_display": packaging_helpers.package_type_display,
            "format_number": babel.numbers.format_number,
            "format_decimal": babel.numbers.format_decimal,
            "format_percent": babel.numbers.format_percent,
            "format_date": babel.dates.format_date,
            "format_datetime": babel.dates.format_datetime,
            "format_time": babel.dates.format_time,
        })

        # Install our translations
        self.templates.install_gettext_translations(self.trans, newstyle=True)

        # Add our Powered By Middleware
        self.wsgi_app = PoweredBy(self.wsgi_app, "Warehouse {} ({})".format(
            warehouse.__version__,
            warehouse.__build__,
        ))

        # Add our Content Security Policy Middleware
        if not self.config.theme_debug:
            self.wsgi_app = guard.ContentSecurityPolicy(
                self.wsgi_app,
                self.config.security.csp,
            )

        if "sentry" in self.config:
            self.wsgi_app = Sentry(self.wsgi_app, Client(**self.config.sentry))

        # Serve the static files that are packaged as part of Warehouse
        self.wsgi_app = SharedDataMiddleware(
            self.wsgi_app,
            {
                "/static/": os.path.abspath(
                    os.path.join(
                        os.path.dirname(warehouse.__file__),
                        "static",
                    ),
                ),
            },
        )

        # configure logging
        logging.config.dictConfig(self.config.logging)
예제 #6
0
def test_convert_to_attribute_dict():
    adict = convert_to_attr_dict({"a": {"b": 1, "c": 2}})

    assert adict.a == {"b": 1, "c": 2}
    assert adict.a.b == 1
    assert adict.a.c == 2