コード例 #1
0
ファイル: controllers.py プロジェクト: iNeft/bespin
def make_app():
    from webob import Response
    import static
    static_app = static.Cling(c.static_dir)
    if c.static_override:
        from paste.cascade import Cascade
        static_app = Cascade([static.Cling(c.static_override), static_app])

    docs_app = pathpopper_middleware(static.Cling(c.docs_dir))
    code_app = pathpopper_middleware(static.Cling(c.static_dir + "/js"), 2)

    register("^/docs/code/", code_app)
    register("^/docs/", docs_app)

    for location, directory in c.static_map.items():
        topop = 1 + location.count('/')
        more_static = pathpopper_middleware(static.Cling(directory), topop)
        register("^/%s/" % location, more_static)

    app = URLRelay(default=static_app)
    app = auth_tkt.AuthTKTMiddleware(app,
                                     c.secret,
                                     secure=c.secure_cookie,
                                     include_ip=False,
                                     httponly=c.http_only_cookie,
                                     current_domain_cookie=True,
                                     wildcard_cookie=True)
    app = db_middleware(app)

    if c.log_requests_to_stdout:
        from paste.translogger import TransLogger
        app = TransLogger(app)

    app = scriptwrapper_middleware(app)
    return app
コード例 #2
0
    def __call__(self, environ, start_response):
        with tempdir() as temporary_directory:
            base_url = wsgiref.util.application_uri(environ)
            deploy(base_url, self.directory, temporary_directory)

            static_app = static.Cling(temporary_directory)
            return static_app(environ, start_response)
コード例 #3
0
ファイル: amiweb.py プロジェクト: 15831944/IslandLinks
 def _serveStaticFile(self, full_path, environ, start_response):
     """
     AmiWeb can serve a static file.
     This is done if one uses the staticHandler decorator.
     """
     cling = static.Cling('')
     file_like = cling._file_like(full_path)
     content_type = cling._guess_type(full_path)
     start_response("200 OK", [('Content-Type', content_type)])
     return cling._body(full_path, environ, file_like)
コード例 #4
0
    def __init__(self, application, base_dir=None):
        self.application = application
        if not base_dir:
            base_dir = self.get_base_dir()
        self.base_url = urlparse(self.get_base_url())

        self.cling = static.Cling(base_dir)
        self.debug_cling = DebugHandler(base_dir)

        super(Cling, self).__init__()
コード例 #5
0
ファイル: main.py プロジェクト: pacificclimate/pdp
def initialize_frontend(global_config, use_analytics=False):
    '''Frontend server with all portal pages and required resources
    '''

    docs_app = static.Cling(resource_filename('pdp', 'docs/html'))
    static_app = static.Cling(resource_filename('pdp', 'static'))

    mounts = {app.url_base: app.mk_frontend(global_config) for app in apps}
    mounts.update({
        '/pcds_map': pcds.mk_frontend(global_config),  # legacy url support
        '/css/': static.Cling(resource_filename('pdp_util', 'data')),
        '/docs': docs_app
    })

    wsgi_app = DispatcherMiddleware(static_app, mounts)

    if use_analytics:
        wsgi_app = AnalyticsMiddleware(wsgi_app, global_config['analytics'])
    return ErrorMiddleware(wsgi_app)
コード例 #6
0
ファイル: amiweb.py プロジェクト: 15831944/IslandLinks
    def addStaticPath(self, url_prefix, os_path):
        cling = static.Cling(os_path)

        def _full_path(path_info):
            path_info = path_info.replace(url_prefix, '/', 1)
            path = "%s%s" % (os_path, path_info)
            path = os.path.abspath(path)
            return path

        cling._full_path = _full_path
        self.static_handling[url_prefix] = (os_path, cling)
コード例 #7
0
    def __init__(self, env, project):
        self.env = env
        self.proxy_app = Proxy('http://localhost:%s/' % env.c.port)

        # import here to avoid circular dependencies.
        from synthesepy import web
        self.web_app = web.get_application(project=project)

        self.static_apps = []
        for base, path in env.c.static_paths:
            self.static_apps.append((base, static.Cling(path)))
コード例 #8
0
ファイル: server.py プロジェクト: repos-websockets/orbited2
 def _init_listen_rules(self): 
     self._wsgi_apps = {}
     static_path = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'static')
     for rule in self._config.rules['Listen']:
         wsgi_app = URLMap()
         wsgi_app['/static'] = static.Cling(static_path)            
         if 'ws' in rule.protocols:
             wsgi_app['/ws'] = eventlet.websocket.WebSocketWSGI(self._wsgi_websocket)
         if 'csp' in rule.protocols:
             wsgi_app['/csp'] = self._csp_sock
         self._wsgi_apps[(rule.interface, rule.port)] = wsgi_app
コード例 #9
0
ファイル: main.py プロジェクト: pacificclimate/pdp
def initialize_backend(global_config, use_analytics=False):
    '''Backend DispatcherMiddleware with all data servers
    '''
    mounts = {app.url_base: app.mk_backend(global_config) for app in apps}

    static_app = static.Cling(resource_filename('pdp', 'static'))
    wsgi_app = DispatcherMiddleware(static_app, mounts)

    if use_analytics:
        wsgi_app = AnalyticsMiddleware(wsgi_app, global_config['analytics'])
    return ErrorMiddleware(wsgi_app)
コード例 #10
0
ファイル: server.py プロジェクト: MahjongRepository/minefield
 def serve(self, host, port, debug):
     self.debug = debug
     if debug:
         import static
         static_path = os.path.join(os.path.dirname(__file__), '..',
                                    'client', 'static')
         self.static_app = static.Cling(static_path)
     self.wsgi_server = pywsgi.WSGIServer((host, port),
                                          self.serve_request,
                                          handler_class=WebSocketHandler)
     self.timer = Timer(self.beat)
     self.wsgi_server.serve_forever()
コード例 #11
0
ファイル: start.py プロジェクト: repos-websockets/orbited2
def main():
    app = URLMap()
    app['/echo'] = handle
    static_path = os.path.join(
        os.path.split(os.path.abspath(__file__))[0], 'static')
    app['/'] = static.Cling(static_path)

    # run an example app from the command line
    listener = eventlet.listen(('localhost', 8013))
    print "\nListening http://localhost:8013/ in your websocket-capable browser.\n"
    eventlet.spawn(listen_tcp)
    wsgi.server(listener, app)
コード例 #12
0
    def __init__(self, application, base_dir=None, ignore_debug=False):
        self.application = application
        self.ignore_debug = ignore_debug
        if not base_dir:
            base_dir = self.get_base_dir()
        self.base_url = urlparse(self.get_base_url())

        self.cling = static.Cling(base_dir)
        try:
            self.debug_cling = DebugHandler(application, base_dir=base_dir)
        except TypeError:
            self.debug_cling = DebugHandler(application)

        super(Cling, self).__init__()
コード例 #13
0
ファイル: server.py プロジェクト: somosazucar/Jappy
    def __call__(self, environ, start_response):
        def custom_start_response(status, headers, exc_info=None):
            headers.append(
                ('Cache-Control', 'no-cache, no-store, must-revalidate'))
            return start_response(status, headers, exc_info)

        if environ.get('PATH_INFO').count('/') > 1:
            path = environ.get(
                'PATH_INFO')[1:environ.get('PATH_INFO')[1:].index('/') + 1]
        else:
            path = ''
        if environ.get('REQUEST_METHOD') == 'PROPFIND':
            if environ.get('PATH_INFO') in ['', '/']:
                # Let's not allow listing of projects
                return Unauthorized()(environ, start_response)
            elif '/.dat' in environ.get('PATH_INFO'):
                # Let's not leak private dat keys
                return Unauthorized()(environ, start_response)
        elif environ.get('REQUEST_METHOD') == 'GET':
            # Let's redirect to static route
            filename = environ.get(
                'PATH_INFO')[environ.get('PATH_INFO').find('/') + 1:]
            if '/.dat' in environ.get('PATH_INFO'):
                # Let's not leak private dat keys
                return Unauthorized()(environ, start_response)
            if path and os.path.exists(os.path.join(workspace_dir, filename)):
                pass
            elif path:
                if filename[len(path) + 1:] != 'index.html':
                    environ['PATH_INFO'] = '/' + filename[len(path) + 1:]
                    response = static.Cling(web_app_dir)
                    return response(environ, start_response)
        elif environ.get('PATH_INFO').count('/') < 2 and \
                environ.get('REQUEST_METHOD') == 'DELETE':
            # Let's disallow removing project directories
            return Unauthorized()(environ, start_response)
        elif environ.get('PATH_INFO').count('/') < 2 and \
                environ.get('REQUEST_METHOD') == 'MKCOL':
            dirname = os.path.join(workspace_dir, environ.get('PATH_INFO'))
            if os.path.exists(dirname):
                response = Response('Already exists.')
                return response(environ, start_response)
        if path.endswith(nocache_ext):
            return self.app(environ, custom_start_response)
        else:
            return self.app(environ, start_response)
コード例 #14
0
ファイル: test_behaviors.py プロジェクト: serathius/static
 def get_app(self):
     return static.Cling('tests/data/withindex')
コード例 #15
0
ファイル: test_behaviors.py プロジェクト: serathius/static
 def setUp(self):
     self._app = static.Cling('tests/data/prezip')
     super(StaticClingWithPrezipping, self).setUp()
コード例 #16
0
ファイル: pelican.py プロジェクト: kattrali/fuller.li
import static
application = static.Cling('output/')

コード例 #17
0
        del headers['Content-Type']

    return headers


def get_user_key(service, user):
    key = user.keys.filter_by(service_alias=service.alias).first()
    if not key:
        abort(403)
    if key.is_expired():
        # Key has expired
        if key.refresh_token:
            data = service.refresh_token(key.refresh_token)
            key.update(data)
            models.db.session.add(key)
            models.db.session.commit()
        else:
            # Unable to refresh the token
            abort(403)
    return key


blog = static.Cling('blog/output')
app = DispatcherMiddleware(config.app, {
    '/blog': blog,
})

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
コード例 #18
0
 def get_app(self):
     return static.Cling('tests/data/prezip')
コード例 #19
0
import static

application = static.Cling('/app/_build')
コード例 #20
0
ファイル: core.py プロジェクト: imclab/goldenarch
"""
goldenarch.py
~~~~~~~~~~~~~

Serves crap. Fast.
"""

import os

import static

PORT = os.environ.get('PORT', 8000)
STATIC_DIR = os.environ.get('STATIC_DIR', '.')


app = static.Cling(STATIC_DIR)

def cli():
    print 'Serving crap. Fast.'

    cmd = (
        'gunicorn goldenarch:app '
        '-b "0.0.0.0:{port}" '
        '-w 16 -k gevent -t 2 '
        '--name goldenarch'
    ).format(port=PORT)

    os.system(cmd)


if __name__ == '__main__':
コード例 #21
0

def redirect(to):
    """
    Create a 301 redirect WSGI app.

    `to` may contain str.format-style formatting which'll be formatted against
    the routing arguments (wsgiorg.routing_args).
    """
    def _redirect(environ, start_response):
        args, kwargs = environ['wsgiorg.routing_args']
        start_response('301 MOVED PERMANENTLY',
                       [('Location', to.format(*args, **kwargs))])
        return []

    return _redirect


# Redirects for old doc URLs, since Cool URIs Don't Change.
app.add('/', GET=redirect('/en/2.0/index.html'))
app.add('/license/', GET=redirect('/en/2.0/license.html'))
app.add('/about/', GET=redirect('/en/2.0/frontmatter.html'))
app.add('/en/1.0/', GET=redirect('/en/2.0/index.html'))
app.add('/en/1.0/{doc:chunk}/', GET=redirect('/en/2.0/{doc}.html'))
app.add('/en/2.0/{doc:chunk}/', GET=redirect('/en/2.0/{doc}.html'))

# Serve docs at "/en/2.0" still, to leave room for the future.
# One of these days I'll actually do this, not just talk about it!
docs = static.Cling(Path(__file__).parent.child('_build', 'html'))
app.add("/en/2.0|", GET=docs)
コード例 #22
0
import os
import static

datadir = os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'json')
application = static.Cling(datadir)
コード例 #23
0
import os
import static

application = static.Cling('/app/build/html')
コード例 #24
0
ファイル: app.py プロジェクト: BEASTMODE2629/via
    template_params = environ.get("pywb.template_params", {})
    template_params["h_embed_url"] = embed_url
    environ["pywb.template_params"] = template_params

    return pywb.apps.wayback.application(environ, start_response)


application = RequestHeaderSanitiser(app)
application = ResponseHeaderSanitiser(application)
application = Blocker(
    application,
    checkmate_host=os.environ["CHECKMATE_URL"],
    api_key=os.environ["CHECKMATE_API_KEY"],
)
application = UserAgentDecorator(application, "Hypothesis-Via")
application = ConfigExtractor(application)
application = wsgi.DispatcherMiddleware(
    application,
    {
        "/favicon.ico": static.Cling("static/favicon.ico"),
        "/robots.txt": static.Cling("static/robots.txt"),
        "/static": static.Cling("static/"),
        "/static/__pywb": static.Cling(resource_filename("pywb", "static/")),
        "/static/__shared/viewer/web/viewer.html": redirect_old_viewer,
        "/h": redirect_strip_matched_path,
        "/_status": status_endpoint,
    },
)
application = newrelic.agent.WSGIApplicationWrapper(application, name="proxy")
コード例 #25
0
ファイル: cli.py プロジェクト: yoavram/goldensphinx
# -*- coding: utf-8 -*-
from __future__ import print_function

import os
import subprocess
import shlex

import static
import click
import sphinx

import goldensphinx

app = static.Cling('.')


@click.group(chain=True)
@click.version_option(version=goldensphinx.__version__,
                      prog_name=goldensphinx.__name__)
def cli():
    if os.environ.get('GOLDENSPHINX', 'true').lower() == 'false':
        return


@cli.command()
@click.option('--static_dir',
              default="docs/_build/html",
              envvar="STATIC_DIR",
              type=click.Path(),
              help="Static directory to serve")
@click.option('--host',
コード例 #26
0
def test_static(url):
    static_app = static.Cling(resource_filename('pdp', 'static'))
    req = Request.blank(url)
    resp = req.get_response(static_app)
    assert resp.status == '200 OK'
コード例 #27
0
ファイル: app.py プロジェクト: tetratorus/via
#     /foo/bar?baz            -> /bar?baz
#     /foo/http://example.com -> /http://example.com
#
# and so on.
@wsgi.responder
def redirect_strip_matched_path(environ, start_response):
    request = Request(environ)
    path = request.path
    if request.query_string:
        path += '?' + request.query_string
    return redirect(path, code=301)


def app(environ, start_response):
    embed_url = os.environ.get('H_EMBED_URL', 'https://hypothes.is/embed.js')

    template_params = environ.get('pywb.template_params', {})
    template_params['h_embed_url'] = embed_url
    environ['pywb.template_params'] = template_params

    return pywb.apps.wayback.application(environ, start_response)


application = wsgi.DispatcherMiddleware(app, {
    '/favicon.ico': static.Cling('static/favicon.ico'),
    '/static': static.Cling('static/'),
    '/static/__pywb': static.Cling(resource_filename('pywb', 'static/')),
    '/static/__shared/viewer/web/viewer.html': redirect_old_viewer,
    '/h': redirect_strip_matched_path,
})
コード例 #28
0
ファイル: sitexml.py プロジェクト: kgbplus/SiteXML-Python
    start_response(sitexml.status, sitexml.response_headers)
    return [sitexml.response_body.encode()]


session_opts = {
    'session.auto': True,
    'session.type': 'cookie',
    'session.validate_key': 'ABCDEF',
    'session.cookie_expires': True,
    'session.httponly': True,
    'session.secure': True
}

session_app = SessionMiddleware(app, session_opts)
wsgi_app = static.Cling(REAL_PATH,
                        not_found=session_app,
                        method_not_allowed=session_app)
application = session_app

if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server

        httpd = make_server('', 8080, wsgi_app)
        print('Serving on port 8080...')
        httpd.serve_forever()

    except KeyboardInterrupt:
        print('Goodbye.')
コード例 #29
0
 def __init__(self):
     self.django_handler = get_wsgi_application()
     self.static_handler = static.Cling(
         os.path.dirname(os.path.dirname(__file__)))