def serve(**settings): authn_policy = AuthTktAuthenticationPolicy( 'sosecret', callback=UserManager.groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory=root_factory(settings)) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.include('pyramid_chameleon') if settings['trace']: config.include('pyramid_debugtoolbar') config.registry.settings['reload_templates'] = True config.registry.settings['directory_settings'] = dict() # load directory settings print('Load settings') DirectoryLoadSettings().load_server_settings(config.registry.settings['root_dir'], config) print('Adding routes') dir_path = r'([\w\-\_]*\/)*' file_basename = r'[\w\-\_\.]*' config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('usermanagement', '/um') fileroutes = [dict(route_name='markdown', file_extension='\.md', options=None), dict(route_name='csv', file_extension='\.csv', options=None), dict(route_name='csv_delimiter', file_extension='\.csv', options='/{delimiter}'), dict(route_name='matlab', file_extension='\.m', options=None), dict(route_name='matlabfileviewer', file_extension='\.mat', options=None), dict(route_name='matlabfileviewer_subpath', file_extension='\.mat', options='/{subkeypath}'), dict(route_name='jsonviewer', file_extension='\.json', options=None), dict(route_name='jsonviewer_plain', file_extension='\.json', options='/json')] for fileroute in fileroutes: options = '' if fileroute['options'] is None else fileroute['options'] options = options if options.startswith('/') or options == '' else '/' + options filepath = '/{file:' + dir_path + file_basename + fileroute['file_extension'] + '}' config.add_route(fileroute['route_name'], filepath + options) config.add_route('directory', '/{dir:' + dir_path + '}') config.add_route('static', '/_static/*subpath') config.add_route('files', '/*subpath', permission='authenticatedusers') print('Add views') here = lambda p: os.path.join(os.path.abspath(os.path.dirname(__file__)), p) static = static_view(here('static'), use_subpath=True) files = static_view( os.path.abspath(config.registry.settings['root_dir']), use_subpath=True) config.add_view(static, route_name='static') config.add_view(files, route_name='files', permission='authenticatedusers') config.scan() app = config.make_wsgi_app() print('Creating server') server = make_server('127.0.0.1', settings['port'], app) print('Start serving on port {}'.format(settings['port'])) server.serve_forever()
def versioning_static_view(context, request): # if the first element in the subpath is the version number, strip # it out of the subpath (see views/api.py static_url) subpath = request.subpath if subpath and version_match(subpath[0]): request.subpath = subpath[1:] return static_view(context, request)
def make_app(global_settings, **settings): """Set up and return the WSGI application.""" config = Configurator(settings=settings) # Third-party includes config.include('pyramid_chameleon') # Routes and views for static and home page config.add_static_view('static', 'static') config.add_route('search', '/') config.add_view('.views.search', route_name='search', renderer='templates/search.pt') # OpenSearch config.add_route('opensearch', '/opensearch.xml') config.add_view('.views.opensearch', route_name='opensearch') # Upload endpoint config.add_route('doc_upload', '/upload') config.add_view('.views.doc_upload', route_name='doc_upload') # A catch-all route that serves documentation from the root of # Dokang. uploaded_docs_dir = settings.get('dokang.uploaded_docs.dir') static_doc_view = static_view(uploaded_docs_dir, use_subpath=True) config.add_route('catch_all_doc_view', '/*subpath') config.add_view(static_doc_view, route_name='catch_all_doc_view') return config.make_wsgi_app()
def _create_static_view(self): settings = get_settings() cache_max_age = int(settings.get(self.PUBLIC_CACHE_MAX_AGE, self.DEFAULT_CACHE_MAX_AGE)) return static_view(settings.get(self.PUBLIC_DIR), cache_max_age=cache_max_age, use_subpath=True)
def _static_routes(config): from pyramid.static import static_view config.add_route('catchall_static', '/*subpath') config.add_view( route_name='catchall_static', view=static_view('steam_matchup:static/angular', use_subpath=True), )
def includeme(config): # Process settings to remove storage wording. # Read version from package.json package_json = json.load(open(os.path.join(HERE, 'package.json'))) admin_version = package_json['dependencies']['kinto-admin'] # Expose capability. config.add_api_capability( 'admin', version=admin_version, description='Serves the admin console.', url='https://github.com/Kinto/kinto-admin/', ) config.add_route('admin_home', '/admin/') config.add_view(admin_home_view, route_name='admin_home') build_dir = static_view('kinto.plugins.admin:build', use_subpath=True) config.add_route('catchall_static', '/admin/*subpath') config.add_view(build_dir, route_name='catchall_static') # Setup redirect without trailing slash. def admin_redirect_view(request): raise HTTPTemporaryRedirect(request.path + '/') config.add_route('admin_redirect', '/admin') config.add_view(admin_redirect_view, route_name='admin_redirect')
class TestStaticAppNoSubpath(unittest.TestCase): staticapp = static_view(os.path.join(here, 'fixtures'), use_subpath=False) def _makeRequest(self, extra): from pyramid.request import Request from io import BytesIO kw = { 'PATH_INFO': '', 'SCRIPT_NAME': '', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '80', 'REQUEST_METHOD': 'GET', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': BytesIO() } kw.update(extra) request = Request(kw) return request def test_basic(self): request = self._makeRequest({'PATH_INFO': '/minimal.pt'}) context = DummyContext() result = self.staticapp(context, request) self.assertEqual(result.status, '200 OK') _assertBody(result.body, os.path.join(here, 'fixtures/minimal.pt'))
def includeme(config): # Process settings to remove storage wording. # Read version from package.json package_json = json.load(open(os.path.join(HERE, "package.json"))) admin_version = package_json["dependencies"]["kinto-admin"] # Expose capability. config.add_api_capability( "admin", version=admin_version, description="Serves the admin console.", url="https://github.com/Kinto/kinto-admin/", ) config.add_route("admin_home", "/admin/") config.add_view(admin_home_view, route_name="admin_home") build_dir = static_view("kinto.plugins.admin:build", use_subpath=True) config.add_route("catchall_static", "/admin/*subpath") config.add_view(build_dir, route_name="catchall_static") # Setup redirect without trailing slash. def admin_redirect_view(request): raise HTTPTemporaryRedirect(request.path + "/") config.add_route("admin_redirect", "/admin") config.add_view(admin_redirect_view, route_name="admin_redirect")
def includeme(config): # Process settings to remove storage wording. # Read version from package.json package_json = json.load(open(os.path.join(HERE, "package.json"))) admin_version = package_json["dependencies"]["kinto-admin"] # Expose capability. config.add_api_capability( "admin", version=admin_version, description="Serves the admin console.", url="https://github.com/Kinto/kinto-admin/", ) config.add_route('admin_home', '/admin/') config.add_view(admin_home_view, route_name="admin_home") build_dir = static_view('kinto.plugins.admin:build', use_subpath=True) config.add_route('catchall_static', '/admin/*subpath') config.add_view(build_dir, route_name="catchall_static") # Setup redirect without trailing slash. def admin_redirect_view(request): raise HTTPTemporaryRedirect(request.path + '/') config.add_route('admin_redirect', '/admin') config.add_view(admin_redirect_view, route_name="admin_redirect")
def _create_static_view(self): registry = get_current_registry() cache_max_age = int(registry.settings.get(self.PUBLIC_CACHE_MAX_AGE, self.DEFAULT_CACHE_MAX_AGE)) return static_view(registry.settings.get(self.PUBLIC_DIR), cache_max_age=cache_max_age, use_subpath=True)
def _create_static_view(self): settings = get_settings() cache_max_age = int( settings.get(self.PUBLIC_CACHE_MAX_AGE, self.DEFAULT_CACHE_MAX_AGE)) return static_view(settings.get(self.PUBLIC_DIR), cache_max_age=cache_max_age, use_subpath=True)
def view(context, request): user = _authenticated_user(request) if not user: return Forbidden() request_ = request.copy() request_.path_info = os.path.join(*request.traversed) sv = static_view(user.name, package_name='mudwyrm_users') return sv(context, request_)
def includeme(config): config.scan("cliquet.tests.testapp.views") # Add an example route with trailing slash (here to serve static files). # This is only used to test 404 redirection in ``test_views_errors.py`` static = static_view('cliquet:tests/testapp/static', use_subpath=True) config.add_route('catchall_static', '/static/*subpath') config.add_view(static, route_name="catchall_static")
def response(self): log = logging.getLogger("files") settings = self.request.registry.settings url = self.request.url if settings.get("server.defaultfile"): static = static_view(root_dir=settings["server.directory"], use_subpath=True, index=settings.get("server.defaultfile")) else: static = static_view(root_dir=settings["server.directory"], use_subpath=True) try: file = static(self.context, self.request) except HTTPNotFound, e: if settings.get("server.log_notfound", "true").lower()=="true": log.info(self.request.url+" => Status: 404 Not found") raise
def configure_resource_directory(self, plugin_name, resourc_edir): app = sys.modules[__name__] resources_view = static_view(resourc_edir, use_subpath=True) view_name = '%s_resources' % plugin_name.replace('.', '_') setattr(app, view_name, resources_view) view_path = 'cone.app.%s' % view_name resource_base = '++resource++%s' % plugin_name self.config.add_view(view_path, name=resource_base) return resource_base
def configure_resource_directory(self, plugin_name, resourc_edir): import cone.app resources_view = static_view(resourc_edir, use_subpath=True) view_name = '%s_resources' % plugin_name.replace('.', '_') setattr(cone.app, view_name, resources_view) view_path = 'cone.app.%s' % view_name resource_base = '++resource++%s' % plugin_name self.config.add_view(view_path, name=resource_base) return resource_base
def includeme(config): config.scan("tests.core.testapp.views") # Add an example route with trailing slash (here to serve static files). # This is only used to test 404 redirection in ``test_views_errors.py`` abs_path = os.path.join(here, 'static') static = static_view(abs_path, use_subpath=True) config.add_route('catchall_static', '/static/*subpath') config.add_view(static, route_name="catchall_static")
def add_static_views(self, *routes, **kwargs): permission = kwargs.get('permission', Everyone) cache_max_age = kwargs.get('cache_max_age', Everyone) for route_name, path, pattern in routes: self.add_view( route_name=route_name, view=static_view(path, cache_max_age=cache_max_age, use_subpath=True), permission=permission) self.add_routes((route_name, pattern))
def includeme(config): assets_view = _add_cors_header(static_view('h:../build', cache_max_age=None, use_subpath=True)) config.add_view(view=assets_view, route_name='assets') config.add_route('assets', '/assets/*subpath') assets_env = Environment('/assets', 'h/assets.ini', 'build/manifest.json') config.add_request_method( lambda r: assets_env, name='assets_env', reify=True)
def includeme(config): # Process settings to remove storage wording. # Expose capability. config.add_api_capability( "admin", version="1.5.1", description="Serves the admin console.", url="https://github.com/Kinto/kinto-admin/", ) build_dir = static_view('kinto_admin:build', use_subpath=True) config.add_route('catchall_static', '/admin/*subpath') config.add_view(build_dir, route_name="catchall_static")
def add_apidocjs_view(self, pattern='documentation', cache_max_age=86400, resource_name='apidocjs'): static_func = static_view('%s:%s/' % (self.package_name, resource_name), package_name=self.package_name, use_subpath=True, cache_max_age=int(cache_max_age)) self.add_route(resource_name, pattern='%s*subpath' % pattern) self.add_view(route_name=resource_name, view=static_func, permission=INES_POLICY)
def add_apidocjs_view( self, pattern='documentation', cache_max_age=86400, resource_name='apidocjs'): static_func = static_view( '%s:%s/' % (self.package_name, resource_name), package_name=self.package_name, use_subpath=True, cache_max_age=int(cache_max_age)) self.add_route(resource_name, pattern='%s*subpath' % pattern) self.add_view( route_name=resource_name, view=static_func, permission=INES_POLICY)
def add_static_route(config, package, subdir, cache_max_age=3600, **add_route_args): """Add a route and view to serve static files from a directory. I create a catchall route that serves all URLs from a directory of static files if the corresponding file exists. Subdirectories are also handled. For example, the URL "/robots.txt" corresponds to file "PACKAGE/SUBDIR/robots.txt", and "/images/header/logo.png" corresponds to "PACKAGE/SUBDIR/images/header/logo.png". If the file doesn't exist, the route won't match the URL, and Pyramid will continue to the next route or traversal. The route name is 'static', which must not conflict with your application's other routes. This serves URLs from the "static" directory in package "myapp". Arguments: * ``config``: a ``pyramid.config.Configurator`` instance. * ``package``: the name of the Python package containing the static files. * ``subdir``: the subdirectory in the package that contains the files. This should be a relative directory with '/' separators regardless of platform. * ``cache_max_age``: influences the ``Expires`` and ``Max-Age`` response headers returned by the view (default is 3600 seconds or five minutes). * ``**add_route_args``: additional arguments to ``config.add_route``. 'name' defaults to "static" but can be overridden. (Every route in your application must have a unique name.) 'pattern' and 'view' may not be specified and will raise TypeError if they are. """ for bad_arg in ["pattern", "view"]: if bad_arg in add_route_args: raise TypeError("keyword arg '%s' is not allowed") name = add_route_args.pop("name", "static") pattern = "/*subpath" asset = "%s:%s" % (package, subdir) view = static_view(asset, cache_max_age) custom_preds = add_route_args.pop("custom_predicates", []) preds = [StaticViewPredicate(package, subdir)] preds.extend(custom_preds) config.add_route(name, pattern, custom_predicates=preds, **add_route_args) config.add_view(view, route_name=name)
def add_static_route(config, package, subdir, cache_max_age=3600, permission=None, **add_route_args): """Add a route and view to serve static files from a directory. I create a catchall route that serves all URLs from a directory of static files if the corresponding file exists. Subdirectories are also handled. For example, the URL "/robots.txt" corresponds to file "PACKAGE/SUBDIR/robots.txt", and "/images/header/logo.png" corresponds to "PACKAGE/SUBDIR/images/header/logo.png". If the file doesn't exist, the route won't match the URL, and Pyramid will continue to the next route or traversal. The route name is 'static', which must not conflict with your application's other routes. This serves URLs from the "static" directory in package "myapp". Arguments: * ``config``: a ``pyramid.config.Configurator`` instance. * ``package``: the name of the Python package containing the static files. * ``subdir``: the subdirectory in the package that contains the files. This should be a relative directory with '/' separators regardless of platform. * ``cache_max_age``: influences the ``Expires`` and ``Max-Age`` response headers returned by the view (default is 3600 seconds or five minutes). * ``**add_route_args``: additional arguments to ``config.add_route``. 'name' defaults to "static" but can be overridden. (Every route in your application must have a unique name.) 'pattern' and 'view' may not be specified and will raise TypeError if they are. """ for bad_arg in ["pattern", "view"]: if bad_arg in add_route_args: raise TypeError("keyword arg '%s' is not allowed") name = add_route_args.pop("name", "static") pattern = "/*subpath" asset = "%s:%s" % (package, subdir) view = static_view(asset, cache_max_age) custom_preds = add_route_args.pop("custom_predicates", []) preds = [StaticViewPredicate(package, subdir)] preds.extend(custom_preds) config.add_route(name, pattern, custom_predicates=preds, **add_route_args) config.add_view(view, route_name=name, permission=permission)
def main(global_config, **settings): config = Configurator(settings=settings) config.registry.queue = Queue(connection=Redis()) def attach_objects_to_request(event): event.request.queue = config.registry.queue config.add_subscriber(attach_objects_to_request, NewRequest) config.include("cornice") config.include('pyramid_mailer') config.scan("zimit.views") static = static_view('../app', use_subpath=True, index='index.html') config.add_route('catchall_static', '/app/*subpath') config.add_view(static, route_name="catchall_static") return config.make_wsgi_app()
def main(global_config, **settings): config = Configurator(settings=settings) config.include("cornice") config.scan("alwaysdata_kinto.views") config.registry.hmac_secret = settings['hmac_secret'] config.registry.redis = { 'host': settings.get('redis.host', REDIS_HOST), 'port': int(settings.get('redis.port', REDIS_PORT)), 'db': int(settings.get('redis.db', REDIS_DB)) } # Serve the web interface build_dir = static_view('alwaysdata_kinto:build', use_subpath=True) config.add_route('catchall_static', '/*subpath') config.add_view(build_dir, route_name="catchall_static") return config.make_wsgi_app()
def includeme(config): # Process settings to remove storage wording. # Expose capability. config.add_api_capability( "admin", version="1.7.0", description="Serves the admin console.", url="https://github.com/Kinto/kinto-admin/", ) build_dir = static_view('kinto.plugins.admin:build', use_subpath=True) config.add_route('catchall_static', '/admin/*subpath') config.add_view(build_dir, route_name="catchall_static") # Setup redirect without trailing slash. def admin_redirect_view(request): raise HTTPTemporaryRedirect(request.path + '/') config.add_route('admin_redirect', '/admin') config.add_view(admin_redirect_view, route_name="admin_redirect")
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_beaker') setup_models(config) session_factory = session_factory_from_settings(settings) static_path = settings.get('static_path', 'static') config.add_static_view(static_path, settings.get('static_directory')) config.add_route('favicon.ico', 'favicon.ico') config.add_view( static_view(''.join([settings.get('static_directory'), 'favicon.ico']), index='', use_subpath=True), route_name='favicon.ico' ) config.set_session_factory(session_factory) config.include('columns.lib.view') config.include('columns.auth', route_prefix='auth') config.include(setup_admin_routes, route_prefix='admin') config.include(setup_resource_routes, route_prefix='api') #config.include(setup_app_routes, route_prefix='app') config.include('columns.blog') return config.make_wsgi_app()
def includeme_last(config): """ The static file catchall needs to be last in the view configuration. """ settings = config.registry.settings # Note: johbo: I would prefer to register a prefix for static files at some # point, e.g. move them under '_static/'. This would fully avoid that we # can have name clashes with a repository name. Imaging someone calling his # repo "css" ;-) Also having an external web server to serve out the static # files seems to be easier to set up if they have a common prefix. # # Example: config.add_static_view('_static', path='rhodecode:public') # # It might be an option to register both paths for a while and then migrate # over to the new location. # Serving static files with a catchall. if settings['static_files']: config.add_route('catchall_static', '/*subpath') config.add_view(static_view('rhodecode:public'), route_name='catchall_static')
def application(global_settings=None, content=".", **settings): loaders = [] app_settings = global_settings or {} app_settings.update(settings) handlers = {k: v for k, v in settings.items() if k.startswith("/")} if not os.path.isdir(os.path.abspath(content)): raise ValueError("path: %s does not exist" % os.path.abspath(content)) else: log.debug("setting content to %s" % os.path.abspath(content)) loaders.append(jinja2.FileSystemLoader(os.path.abspath(content))) c = config.Configurator(root_factory=FileSystemRootFactory(path=content), settings=app_settings) c.scan() c.registry["env"] = jinja2.Environment(loader=jinja2.ChoiceLoader(loaders)) c.registry["static"] = static_view(root_dir=os.path.abspath(content)) c.registry["handlers"] = {} if handlers: for url, handler in handlers.items(): _module, obj = handler.rsplit(".", 1) c.registry["handlers"][url] = getattr(__import__(_module, fromlist=obj), obj) return c.make_wsgi_app()
def includeme(config): admin_version = VERSION_FILE_PATH.read_text().strip() # Expose capability. config.add_api_capability( "admin", version=admin_version, description="Serves the admin console.", url="https://github.com/Kinto/kinto-admin/", ) config.add_route("admin_home", "/admin/") config.add_view(admin_home_view, route_name="admin_home") build_dir = static_view("kinto.plugins.admin:build", use_subpath=True) config.add_route("catchall_static", "/admin/*subpath") config.add_view(build_dir, route_name="catchall_static") # Setup redirect without trailing slash. def admin_redirect_view(request): raise HTTPTemporaryRedirect(request.path + "/") config.add_route("admin_redirect", "/admin") config.add_view(admin_redirect_view, route_name="admin_redirect")
from pyramid.response import Response from sqlalchemy import create_engine from busroutes import BusRoute from busroutes import Base from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from pyramid.renderers import render from pyramid.renderers import render_to_response from pyramid.response import Response from pyramid.request import Request from pyramid.view import view_config from server import get_session from json import loads # loads(request.body, encoding=request.charset) from pyramid.static import static_view static_view = static_view('/path/to/static/dir', use_subpath=True) @view_config(route_name='home', renderer='templates/index.pt') def home_view(request): return Response('<h1><p>Welcome</p></h1>') @view_config(route_name='bus') def form_view(request): result = render('templates/index.pt', {'start_point':'Majestic','end_point':'Uttarahalli','route':'Chamrajpet Lalbagh'}, request=request) response = Response(result) return response # @view_config(route_name='controller', renderer='app/js/controller.js')
import re from webob import Response from webob.exc import HTTPNotFound from pyramid.security import authenticated_userid from pyramid.static import static_view from pyramid.renderers import render_to_response from raisin.restyler.page import Page from raisin.restyler.box import Box from raisinpyramid import security STATIC_VIEW_OF_ICO = static_view('raisin.page:templates/static/', cache_max_age=3600) VALID_KEY = re.compile('^[A-Za-z_]*$') VALID_VALUE = re.compile('^[A-Za-z0-9-_\.\+]*$') def validate(matchdict): """Validate the matchdict""" for key, value in matchdict.items(): if not VALID_KEY.match(key): raise AttributeError if not VALID_VALUE.match(value): raise AttributeError def box_html_view(request):
'Access-Control-Allow-Origin': '*' }) return response return wrapper def _load_bundles(fp): """Read an asset bundle config from a file object.""" parser = configparser.ConfigParser() parser.readfp(fp) return {k: aslist(v) for k, v in parser.items('bundles')} # Site assets assets_view = static_view('h:../build', cache_max_age=None, use_subpath=True) assets_view = _add_cors_header(assets_view) # Client assets assets_client_view = static_view('h:../node_modules/hypothesis/build', cache_max_age=None, use_subpath=True) assets_client_view = _add_cors_header(assets_client_view) def includeme(config): auto_reload = asbool(config.registry.settings.get('h.reload_assets', False)) config.add_view(route_name='assets', view=assets_view)
def includeme(config): """Install SyncServer application into the given Pyramid configurator.""" # Set the umask so that files are created with secure permissions. # Necessary for e.g. created-on-demand sqlite database files. os.umask(0077) # Sanity-check the deployment settings and provide sensible defaults. settings = config.registry.settings public_url = settings.get("syncserver.public_url") if public_url is None: raise RuntimeError("you much configure syncserver.public_url") public_url = public_url.rstrip("/") settings["syncserver.public_url"] = public_url secret = settings.get("syncserver.secret") if secret is None: secret = os.urandom(32).encode("hex") sqluri = settings.get("syncserver.sqluri") if sqluri is None: rootdir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) sqluri = "sqlite:///" + os.path.join(rootdir, "syncserver.db") # Configure app-specific defaults based on top-level configuration. settings.pop("config", None) if "tokenserver.backend" not in settings: # Default to our simple static node-assignment backend settings["tokenserver.backend"] =\ "syncserver.staticnode.StaticNodeAssignment" settings["tokenserver.sqluri"] = sqluri settings["tokenserver.node_url"] = public_url settings["endpoints.sync-1.5"] = "{node}/storage/1.5/{uid}" if "tokenserver.monkey_patch_gevent" not in settings: # Default to no gevent monkey-patching settings["tokenserver.monkey_patch_gevent"] = False if "tokenserver.applications" not in settings: # Default to just the sync-1.5 application settings["tokenserver.applications"] = "sync-1.5" if "tokenserver.secrets.backend" not in settings: # Default to a single fixed signing secret settings["tokenserver.secrets.backend"] = "mozsvc.secrets.FixedSecrets" settings["tokenserver.secrets.secrets"] = [secret] if "tokenserver.allow_new_users" not in settings: allow_new_users = settings.get("syncserver.allow_new_users") if allow_new_users is not None: settings["tokenserver.allow_new_users"] = allow_new_users if "hawkauth.secrets.backend" not in settings: # Default to the same secrets backend as the tokenserver for key in settings.keys(): if key.startswith("tokenserver.secrets."): newkey = "hawkauth" + key[len("tokenserver"):] settings[newkey] = settings[key] if "storage.backend" not in settings: # Default to sql syncstorage backend settings["storage.backend"] = "syncstorage.storage.sql.SQLStorage" settings["storage.sqluri"] = sqluri settings["storage.create_tables"] = True if "browserid.backend" not in settings: # Default to remote verifier, with base of public_url as only audience audience = urlunparse(urlparse(public_url)._replace(path="")) settings["browserid.backend"] = "tokenserver.verifiers.RemoteVerifier" settings["browserid.audiences"] = audience if "loggers" not in settings: # Default to basic logging config. root_logger = logging.getLogger("") if not root_logger.handlers: logging.basicConfig(level=logging.INFO) # Include the relevant sub-packages. config.scan("syncserver") config.include("syncstorage", route_prefix="/storage") config.include("tokenserver", route_prefix="/token") config.include('pyramid_chameleon') # Add a top-level explaination view. # First view, available at http://localhost:6543/ def page(request): result = render('page/index.pt', {'public_url': public_url}, request=request) response = Response(result) return response config.add_route('page', '/') config.add_view(page, route_name='page') www = static_view(os.path.realpath(os.path.dirname(__file__) + "/page/"), use_subpath=True) # Documentation for Hybrid routing can be found here # http://docs.pylonsproject.org/projects/pyramid/en/1.0-branch/narr/hybrid.html#using-subpath-in-a-route-pattern config.add_route('index', '/*subpath', 'www') # subpath is a reserved word config.add_view(www, route_name='index')
from pyramid.static import static_view from pyramid.security import DENY_ALL static_view = static_view("adaero:static", use_subpath=True) # Safety net in case a view does not inherit from Root __acl__ = [DENY_ALL] class Root(object): __acl__ = [DENY_ALL] def includeme(config): """Pyramid convention that allows invocation of a function prior to server start and is found through `config.scan` in the main function""" config.add_route("catchall_static", "/*subpath") config.add_view("adaero.views.static_view", route_name="catchall_static")
def __init__(self, pyramidConfig, static_assets_peter, static_assets_project, checkUserPassword, checkUserEmail=None, sendPasswordResetEmail=None, setNewPasswordHash=None, storeRequestToken=None, retreiveRequestToken=None, deleteRequestToken=None, projectMinPermissions="view"): """ :param: pyramidConfig is the configuration to which the routes and views are added. :param: checkUserPassword is a callback, taking username and password and returning None if authentication fails or the username as it should be remembered. :param: sendResetMail callback taking username, email and reset page URL. Provision and further customization of a template is left to the callback. :param: checkUserEmail for password reset: if username and email address do not match, no reminder email is sent. :param: setNewPasswordHash takes username and new password hash. :param: storeRequestToken a persistent storage for the auth tokens. this callback takes: token, username, requestType, expiryDate :param: retreiveRequestToken :param: deleteRequestToken """ # own root object without any permission self.credentialsCheck = checkUserPassword self.static_assets_login = static_assets_peter self.static_assets_project = static_assets_project self.minPermissions = projectMinPermissions # setup routes and views # these are the API functions, serve them always # add own root factory self.checkUserEmail = checkUserEmail self.sendPasswordResetEmail = sendPasswordResetEmail self.setNewPasswordHash = setNewPasswordHash self.storeRequestToken = storeRequestToken self.retreiveRequestToken = retreiveRequestToken self.deleteRequestToken = deleteRequestToken pyramidConfig.add_route('peter.api.login', '/api/login', factory=peterResourceRoot) pyramidConfig.add_view(self.loginAPIView, route_name="peter.api.login", permission=NO_PERMISSION_REQUIRED) pyramidConfig.add_route('peter.api.logout', '/api/logout', factory=peterResourceRoot) pyramidConfig.add_view(self.logoutAPIView, route_name="peter.api.logout", permission=NO_PERMISSION_REQUIRED) pyramidConfig.add_route("peter.api.resetRequest", "/api/resetrequest", factory=peterResourceRoot) pyramidConfig.add_view(self.resetRequestView, route_name="peter.api.resetRequest", permission=NO_PERMISSION_REQUIRED) pyramidConfig.add_route("peter.api.resetPassword", "/api/resetpassword", factory=peterResourceRoot) pyramidConfig.add_view(self.resetPasswordView, route_name="peter.api.resetPassword", permission=NO_PERMISSION_REQUIRED) def convenienceLoginForward(request): return HTTPFound("/login/") # this is a convenience forward pyramidConfig.add_route("peter.loginPageRedir", "/login", factory=peterResourceRoot) pyramidConfig.add_view(convenienceLoginForward, route_name='peter.loginPageRedir') # this serves the login screen pyramidConfig.add_route("peter.loginPage", "/login/*subpath", factory=peterResourceRoot) pyramidConfig.add_view(static_view(self.static_assets_login, use_subpath=True, index="login.html"), route_name='peter.loginPage') self.projectView = static_view(root_dir=self.static_assets_project, use_subpath=True)
import os from pyramid.static import static_view from service import PROJECT_BASE_PATH # configure the catch-all static_view static_path = os.path.sep.join([PROJECT_BASE_PATH, 'docs', '_build', 'html']) static_view = static_view(static_path, use_subpath=True)
from node.behaviors import DefaultInit from node.behaviors import Nodespaces from node.behaviors import Nodify from node.behaviors import OdictStorage from node.utils import instance_property from plumber import plumbing from pyramid.security import ALL_PERMISSIONS from pyramid.security import Allow from pyramid.security import Deny from pyramid.security import Everyone from pyramid.static import static_view from zope.component import adapter from zope.interface import implementer from zope.interface import Interface static_resources = static_view('static', use_subpath=True) @plumbing(WorkflowState, WorkflowACL) class WorkflowNode(BaseNode): workflow_name = u'dummy' workflow_tsf = None @property def properties(self): props = Properties() props.in_navtree = True return props def __call__(self): pass
response = wrapped(context, request) response.headers.extend({'Access-Control-Allow-Origin': '*'}) return response return wrapper def _load_bundles(fp): """Read an asset bundle config from a file object.""" parser = configparser.ConfigParser() parser.readfp(fp) return {k: aslist(v) for k, v in parser.items('bundles')} # Site assets assets_view = static_view('h:../build', cache_max_age=None, use_subpath=True) assets_view = _add_cors_header(assets_view) # Client assets assets_client_view = static_view('h:../node_modules/hypothesis/build', cache_max_age=None, use_subpath=True) assets_client_view = _add_cors_header(assets_client_view) def includeme(config): config.add_view(route_name='assets', view=assets_view) config.add_view(route_name='assets_client', view=assets_client_view) assets_env = Environment('/assets', 'h/assets.ini', 'build/manifest.json') assets_client_env = Environment(
import os import re from pyramid.httpexceptions import HTTPFound from pyramid.url import resource_url from pyramid.static import static_view from karl.views.utils import get_user_home from karl.views.utils import get_static_url here = os.path.abspath(os.path.dirname(__file__)) # five year expires time static_view = static_view('static', cache_max_age=157680000, use_subpath=True) version_match = re.compile(r'^r-?\d+$').match # version number is "r" plus an integer (possibly negative) def versioning_static_view(context, request): # if the first element in the subpath is the version number, strip # it out of the subpath (see views/api.py static_url) subpath = request.subpath if subpath and version_match(subpath[0]): request.subpath = subpath[1:] return static_view(context, request) def site_view(context, request):
from pyramid.view import view_config from pyramid.static import static_view from .models import (DBSession, Category, Participant) static_view = static_view('../../frontend/dist', use_subpath=True) @view_config(route_name='categories', renderer='json') def categories(request): categories = DBSession.query(Category).filter_by(participant=None).all() cats = [] for category in categories: cats.append({ 'id': category.id, 'name': category.name, 'images': [img.filename for img in category.images] }) return cats @view_config(route_name='selectcategory', renderer='json') def selectcategory(request): participant_name = request.matchdict['participant'] category_id = int(request.matchdict['category']) category = DBSession.query(Category).get(category_id) if category.participant is None: participant = Participant(participant_name) participant.category = category DBSession.add(participant)
import os import re from pyramid.httpexceptions import HTTPFound from pyramid.url import resource_url from pyramid.static import static_view from karl.views.utils import get_user_home from karl.views.utils import get_static_url here = os.path.abspath(os.path.dirname(__file__)) # five year expires time static_view = static_view('static', cache_max_age=157680000, use_subpath=True) version_match = re.compile(r'^r-?\d+$').match # version number is "r" plus an integer (possibly negative) def versioning_static_view(context, request): # if the first element in the subpath is the version number, strip # it out of the subpath (see views/api.py static_url) subpath = request.subpath if subpath and version_match(subpath[0]): request.subpath = subpath[1:] return static_view(context, request) def site_view(context, request): home, extra_path = get_user_home(context, request) return HTTPFound(location=resource_url(home, request, *extra_path))
def download_static_view(context, request): request.subpath = tuple(context.path.split('/')) return static_view(get_generation_path(), use_subpath=True)
from pyramid.static import static_view private_static_view = static_view('firsttest:priv_res', use_subpath=True)
config.add_route( "fvcom.results.forecast.publish", "fvcom/results/forecast/publish/{results_date}", ) def _bloomcast_routes(config): config.add_route("bloomcast.about", "bloomcast/") config.add_route("bloomcast.spring_diatoms", "bloomcast/spring_diatoms") # Legacy routes config.add_route("bloomcast.index.html", "bloomcast.html") config.add_route("bloomcast.spring_diatoms.html", "bloomcast/spring_diatoms.html") def _about_site_routes(config): config.add_route("about.contributors", "contributors") config.add_route("about.publications", "publications") config.add_route("about.license", "license") # Legacy route config.add_route("about.contributors.html", "contributors.html") config.add_route("about.license.html", "license.html") def _figure_server(config): config.add_view("salishsea_site._figure", route_name="figure") config.add_route("figure", "/*subpath") _figure = static_view("/var/www/html/nowcast-sys/figures", use_subpath=True)
}) return response return wrapper def _load_bundles(fp): """Read an asset bundle config from a file object.""" parser = configparser.ConfigParser() parser.readfp(fp) return {k: aslist(v) for k, v in parser.items('bundles')} # Site assets assets_view = static_view('h:../build', cache_max_age=None, use_subpath=True) assets_view = _add_cors_header(assets_view) def includeme(config): auto_reload = asbool(config.registry.settings.get('h.reload_assets', False)) config.add_view(route_name='assets', view=assets_view) assets_env = Environment('/assets', 'h/assets.ini', 'build/manifest.json', auto_reload=auto_reload) # We store the environment objects on the registry so that the Jinja2
def main(global_config, **settings): settings = load_usermanager(settings) settings = load_database_settings(settings) secrethash = settings['secret'] if 'secret' in settings else 'sosecret' authn_policy = AuthTktAuthenticationPolicy(secrethash, callback=settings['usermanager'].groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory=root_factory(settings)) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.registry.settings['directory_settings'] = dict() log.info('Engine from config') config.scan('models') engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) # load directory settings log.info('Load settings') DirectoryLoadSettings().load_server_settings(config.registry.settings['root_dir'], config) log.info('Adding routes') dir_path = r'([\w\-\_]*\/)*' file_basename = r'[\w\-\_\.]*' config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('usermanagement', '/um') config.add_route('usermanagement_action', '/um/{action}/{id}') fileroutes = [dict(route_name='markdown', file_extension='\.md', options=None), dict(route_name='csv', file_extension='\.csv', options=None), dict(route_name='csv_delimiter', file_extension='\.csv', options='/{delimiter}'), dict(route_name='matlab', file_extension='\.m', options=None), dict(route_name='matlabfileviewer', file_extension='\.mat', options=None), dict(route_name='matlabfileviewer_subpath', file_extension='\.mat', options='/{subkeypath}'), dict(route_name='jsonviewer', file_extension='\.json', options=None), dict(route_name='jsonviewer_plain', file_extension='\.json', options='/json')] for fileroute in fileroutes: options = '' if fileroute['options'] is None else fileroute['options'] options = options if options.startswith('/') or options == '' else '/' + options filepath = '/{file:' + dir_path + file_basename + fileroute['file_extension'] + '}' config.add_route(fileroute['route_name'], filepath + options) config.add_route('directory', '/{dir:' + dir_path + '}') config.add_route('static', '/_static/*subpath') config.add_route('files_comment', '/{file:' + dir_path + file_basename + '}/{action:comment}', permission='authenticatedusers') config.add_route('files', '/*subpath', permission='authenticatedusers') log.info('Add views') here = lambda p: os.path.join(os.path.abspath(os.path.dirname(__file__)), p) static = static_view(here('static'), use_subpath=True) files = static_view( os.path.abspath(config.registry.settings['root_dir']), use_subpath=True) config.add_view(static, route_name='static') config.add_view(files, route_name='files', permission='authenticatedusers') config.scan() log.info('Start app') return config.make_wsgi_app()
def response(self): log = logging.getLogger("outpost.files") settings = self.request.registry.settings url = self.request.url # run pre proxy request hooked filters # if the filter returns a response and not None. The response is returned # immediately try: file = filtermanager.runPreHook(filtermanager.EmptyFileResponse(), self.request, self.url) except filtermanager.ResponseFinished as e: return e.response if file is None: df = settings.get("server.default_path") # bw 0.2.6 if df is None: df = settings.get("server.defaultfile") if df: static = static_view(root_dir=settings["files.directory"], use_subpath=True, index=df) else: static = static_view(root_dir=settings["files.directory"], use_subpath=True) file = static(self.context, self.request) alsoProvides(file, filtermanager.IFileRequest) # adjust headers #file.headers["Cache-control"] = "no-cache" #file.headers["Pragma"] = "no-cache" #file.headers["Expires"] = "0" #if "Last-Modified" in file.headers: # del file.headers["Last-Modified"] # set default mime type to text/html if len(self.request.subpath): name = self.request.subpath[-1] else: name = df # cache content type global __ct_cache__ ext = ".".join(name.split(".")[1:]) if ext in __ct_cache__: ct = __ct_cache__[ext] else: ct = guess_type( name, strict=False)[0] or settings.get("server.content_type") __ct_cache__[ext] = ct file.headers["Content-Type"] = ct file.content_type = ct file.charset = settings.get("files.charset") or "utf-8" if self.debug: server_trace = settings.get("files.trace") # bw 0.2.6 renamed setting if server_trace is None: server_trace = settings.get("server.trace") # trace in debugger if server_trace and re.search(server_trace, url): pdb.set_trace() # run post file server hooked filters file = filtermanager.runPostHook( file, self.request, self.url ) #=> Ready to filter and return the current file. Step once (n) to apply filters. return file
def item_delete(request): iid = int(request.matchdict["iid"]) del STORAGE[iid] return Response(status=204) def item_list(request): result = [_get_expanded_item(k) for k in STORAGE.keys()] return Response(body = json.dumps(result), content_type='application/json') if __name__ == '__main__': config = Configurator() # set up a static route to the frontend application config.add_route('app_route', '/app/*subpath') this_dir = os.path.split(os.path.abspath(__file__))[0] app_dir = os.path.join(this_dir, 'app') app_static = static_view(app_dir, use_subpath=True, cache_max_age=0) config.add_view(app_static, route_name='app_route') # configure the hello world route config.add_route('item_col_route', "item") config.add_route('item_entity_route', "item/{iid}") config.add_view(view=item_post, route_name="item_col_route", request_method="POST") config.add_view(view=item_get, route_name="item_entity_route", request_method="GET") config.add_view(view=item_put, route_name="item_entity_route", request_method="PUT") config.add_view(view=item_delete, route_name="item_entity_route", request_method="DELETE") config.add_view(view=item_list, route_name="item_col_route", request_method="GET") app = config.make_wsgi_app() serve(app, host='0.0.0.0', port=8080)
from cone.app.browser.layout import ProtectedContentTile from cone.example.model import ExamplePlugin from cone.tile import tile from pyramid.static import static_view static_resources = static_view('static', use_subpath=True) @tile(name='content', path='templates/example.pt', interface=ExamplePlugin, permission='login') class ExamplePluginContent(ProtectedContentTile): pass
response = wrapped(context, request) response.headers.extend({"Access-Control-Allow-Origin": "*"}) return response return wrapper def _load_bundles(fp): """Read an asset bundle config from a file object.""" parser = configparser.ConfigParser() parser.read_file(fp) return {k: aslist(v) for k, v in parser.items("bundles")} # Site assets ASSETS_VIEW = static_view("lms:../build", cache_max_age=None, use_subpath=True) ASSETS_VIEW = _add_cors_header(ASSETS_VIEW) def includeme(config): # TODO: figure out auto reload if we want it config.add_view(route_name="assets", view=ASSETS_VIEW) assets_env = Environment("/assets", "lms/assets.ini", "build/manifest.json", auto_reload=False) # We store the environment objects on the registry so that the Jinja2 # integration can be configured in app.py config.registry["assets_env"] = assets_env
# -*- coding: utf-8 -*- from pyramid.static import static_view static_view = static_view('C:/Mapfish/crdppf/crdppfportal/', use_subpath=True)
from pyramid.static import static_view index_static_view = static_view('../public') assets_static_view = static_view('../public/assets', use_subpath=True)