示例#1
0
 def __init__(self, options={}):
     options = {
         "headers": "*",
         "methods": "*",
         "maxage": "86400",
         "origin": "*",
         **options
     }
     self.cors = CORS(lambda x, y: None, **options)
示例#2
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)

    # MongoDB and Pyramid

    db_url = settings['mongo_uri']
    config.registry.db = MongoClient(db_url)

    def add_db(request):
        return config.registry.db.greenhouse

    def add_fs(request):
        return GridFS(request.db)

    config.add_request_method(add_db, 'db', reify=True)
    config.add_request_method(add_fs, 'fs', reify=True)

    # Routes
    config.add_route('home', '/')

    config.add_route('data_readings', '/data_readings')

    config.add_route('settings', '/settings')

    config.add_route('actuators', '/actuators')
    config.add_route('actuators_state', '/actuators/{name}/state')

    config.add_route('greenhouse_server_state', '/greenhouse_server_state')

    config.scan('sgreen2_web.views')

    from wsgicors import CORS
    return CORS(config.make_wsgi_app(), headers="*", methods="*", maxage="180", origin="*")
示例#3
0
def start_server():
    launch_file_monitor()
    provider = FilesystemProvider('workspace')
    config = DEFAULT_CONFIG.copy()
    config.update({
        "mount_path": "/dav",
        "provider_mapping": {
            "/": provider
        },
        "user_mapping": {},
        "verbose": 1,
    })
    dav_app = WsgiDAVApp(config)
    cors_dav_app = CORS(dav_app,
                        headers="*",
                        methods="*",
                        maxage="180",
                        origin="*")
    # CORS middleware doesn't like exc_info
    filtered_dav_app = DAVFilterMiddleWare(cors_dav_app)
    filtered_dav_app = GzipMiddleware(filtered_dav_app,
                                      mime_types=[
                                          'application/javascript',
                                          'application/x-rapyd',
                                          'application/xml', 'image/svg+xml',
                                          'text/*'
                                      ])
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app,
                                        {'/dav': filtered_dav_app})
    socketio.run(app, host='0.0.0.0', port=54991)
示例#4
0
def make_app(global_config=None):
    paasta_api_path = os.path.dirname(paasta_tools.api.__file__)
    setup_paasta_api()

    config = Configurator(settings={
        'service_name': 'paasta-api',
        'pyramid_swagger.schema_directory': os.path.join(paasta_api_path, 'api_docs'),
        'pyramid_swagger.skip_validation': ['/(static)\\b', '/(status)\\b', '/(swagger.json)\\b'],
        'pyramid_swagger.swagger_versions': ['2.0'],
    })

    config.include('pyramid_swagger')
    config.add_route('resources.utilization', '/v1/resources/utilization')
    config.add_route('service.instance.status', '/v1/services/{service}/{instance}/status')
    config.add_route('service.instance.delay', '/v1/services/{service}/{instance}/delay')
    config.add_route('service.instance.tasks', '/v1/services/{service}/{instance}/tasks')
    config.add_route('service.instance.tasks.task', '/v1/services/{service}/{instance}/tasks/{task_id}')
    config.add_route('service.list', '/v1/services/{service}')
    config.add_route('services', '/v1/services')
    config.add_route('service.autoscaler.get', '/v1/services/{service}/{instance}/autoscaler', request_method="GET")
    config.add_route('service.autoscaler.post', '/v1/services/{service}/{instance}/autoscaler', request_method="POST")
    config.add_route('service_autoscaler.pause.post', '/v1/service_autoscaler/pause', request_method="POST")
    config.add_route('service_autoscaler.pause.delete', '/v1/service_autoscaler/pause', request_method="DELETE")
    config.add_route('service_autoscaler.pause.get', '/v1/service_autoscaler/pause', request_method="GET")
    config.add_route('version', '/v1/version')
    config.add_route('marathon_dashboard', '/v1/marathon_dashboard', request_method="GET")
    config.scan()
    return CORS(config.make_wsgi_app(), headers="*", methods="*", maxage="180", origin="*")
示例#5
0
def main():
    with Configurator() as config:
        config.include('pyramid_debugtoolbar')
        config.include('example_app.users')
        config.include('example_app.documents')

        wsgi_app = config.make_wsgi_app()
        wsgi_app = CORS(
            wsgi_app,
            headers='*',
            expose_headers='Content-Length, X-Total-Count',
            methods='HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE',
            maxage='180',
            origin='copy',
        )

    server = make_server('0.0.0.0', 6543, wsgi_app)
    print('Server started on http://0.0.0.0:6543')
    server.serve_forever()
示例#6
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    # Load in all the routes from the routes directory.
    routes.main(config)

    # One off endpoints
    config.add_route("sleep", "/sleep")
    config.add_route("test", "/test")
    config.add_route("test2", "/test2")
    config.add_route("db_test", "/db_test")
    config.add_route("athena", "/athena")
    config.scan()

    return CORS(config.make_wsgi_app(),
                headers="*",
                methods="*",
                maxage="180",
                origin="*")
示例#7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('categories', '/categories')
    config.add_route('participants', '/participants')
    config.add_route('selectcategory',
                     '/selectcategory/{participant}/{category}')
    config.add_route('catchall_static', '/*subpath')
    config.add_view('backend.views.static_view', route_name='catchall_static')
    config.scan()
    return CORS(config.make_wsgi_app(),
                headers="*",
                methods="*",
                maxage="180",
                origin="*")
示例#8
0
def main(global_config, **settings):
    log = logging.getLogger(__name__)
    log.warning(sys.version)
    log.warning(u'Start')
    log.warning('++++++++++++++++++++++start')
    # print('++++++++++++++++++++++start')
    config = Configurator(settings=settings)
    # config.include('pyramid_chameleon')
    #config.set_authorization_policy(ACLAuthorizationPolicy())
    # config.include('pyramid_tm')
    config.include('pyramid_sqlalchemy')
    config.include('pyramid_jwtauth')

    config = configure_route(config)
    # return config.make_wsgi_app()
    from wsgicors import CORS
    return CORS(config.make_wsgi_app(),
                headers="*",
                methods="*",
                maxage="180",
                origin="*")
示例#9
0
def create_app(_components=None, _middleware=None, _routes=None, _renderers=None):
    """
    Factory function for the creation of a `molten.App`.
    """
    setup_logging()

    wrapped_app = app = ExtApp(
        components=_components or components,
        middleware=_middleware or middleware,
        routes=_routes or routes,
        renderers=_renderers or renderers
    )

    {%- if cookiecutter.cors_support == 'y' %}
    wrapped_app = CORS(wrapped_app,  **settings.strict_get("wsgicors"))
    {%- endif %}

    {%- if cookiecutter.static_support == 'y' %}
    wrapped_app = WhiteNoise(wrapped_app, **settings.strict_get("whitenoise"))
    {%- endif %}

    return wrapped_app, app
示例#10
0
class CORSRequestHooks:

    def __init__(self, options={}):
        options = {
            "headers": "*",
            "methods": "*",
            "maxage": "86400",
            "origin": "*",
            **options
        }
        self.cors = CORS(lambda x, y: None, **options)

    def on_request(self, environ: wsgi.WSGIEnviron, start_response: wsgi.WSGIStartResponse):
        self.cors(environ, start_response)

    def on_response(self, environ: wsgi.WSGIEnviron, response: Response):
        orig = environ.get("HTTP_ORIGIN", None)
        request_method = environ['REQUEST_METHOD']
        headers = response.headers

        policyname, ret_origin = self.cors.selectPolicy(orig, request_method)
        policy = self.cors.policies[policyname]

        if policy.credentials == 'true' and policy.origin == "*":
            # for credentialed access '*' are ignored in origin
            ret_origin = orig

        if ret_origin:
            headers['Access-Control-Allow-Origin'] = ret_origin

            if policy.credentials == 'true':
                headers['Access-Control-Allow-Credentials'] = 'true'

            if policy.expose_headers:
                headers['Access-Control-Expose-Headers'] = policy.expose_headers

            if policy.origin != "*":
                headers['Vary'] = 'Origin'
示例#11
0
def wrap_CORS(app: App) -> CORS:
    """Initializes CORS wsgi middleware from app settings.

    """

    _cors_settings = {
        k: v
        for k, v in app.settings.items() if k.startswith("CORS")
    }

    for setting in CORS_SETTINGS:
        if setting not in _cors_settings or _cors_settings.get(
                setting) is None:
            raise ConfigurationError(f"CORS setting {setting} not configured")

    extended_app = CORS(
        app,
        headers=_cors_settings.get("CORS_HEADERS"),
        methods=_cors_settings.get("CORS_METHODS"),
        origin=_cors_settings.get("CORS_ORIGIN"),
        maxage=_cors_settings.get("CORS_MAXAGE"),
    )

    return extended_app
示例#12
0
文件: app.py 项目: What-If-I/FeedMe
def make_zbs_CORS(app):
    return CORS(app, headers="*", methods="*", origin="*", maxage="86400")
示例#13
0
 def __call__(self, environ, start_response):
     cors = CORS(super().__call__, headers='*', methods='*', origin='*')
     return cors(environ, start_response)
示例#14
0
from index import create_app
from wsgicors import CORS

app = CORS(create_app(), headers="*", methods="*", origin="*", maxage="86400")
示例#15
0
def make_app(global_config=None):
    paasta_api_path = os.path.dirname(paasta_tools.api.__file__)
    setup_paasta_api()

    config = Configurator(
        settings={
            "service_name":
            "paasta-api",
            "pyramid_swagger.schema_directory":
            os.path.join(paasta_api_path, "api_docs"),
            "pyramid_swagger.skip_validation": [
                "/(static)\\b",
                "/(status)\\b",
                "/(swagger.json)\\b",
            ],
            "pyramid_swagger.swagger_versions": ["2.0"],
        })

    config.include("pyramid_swagger")
    config.add_route("resources.utilization", "/v1/resources/utilization")
    config.add_route("service.instance.status",
                     "/v1/services/{service}/{instance}/status")
    config.add_route(
        "service.instance.set_state",
        "/v1/services/{service}/{instance}/state/{desired_state}",
    )
    config.add_route("service.instance.delay",
                     "/v1/services/{service}/{instance}/delay")
    config.add_route("service.instance.tasks",
                     "/v1/services/{service}/{instance}/tasks")
    config.add_route(
        "service.instance.tasks.task",
        "/v1/services/{service}/{instance}/tasks/{task_id}",
    )
    config.add_route("service.list", "/v1/services/{service}")
    config.add_route("services", "/v1/services")
    config.add_route(
        "service.autoscaler.get",
        "/v1/services/{service}/{instance}/autoscaler",
        request_method="GET",
    )
    config.add_route(
        "service.autoscaler.post",
        "/v1/services/{service}/{instance}/autoscaler",
        request_method="POST",
    )
    config.add_route(
        "service_autoscaler.pause.post",
        "/v1/service_autoscaler/pause",
        request_method="POST",
    )
    config.add_route(
        "service_autoscaler.pause.delete",
        "/v1/service_autoscaler/pause",
        request_method="DELETE",
    )
    config.add_route(
        "service_autoscaler.pause.get",
        "/v1/service_autoscaler/pause",
        request_method="GET",
    )
    config.add_route("version", "/v1/version")
    config.add_route("marathon_dashboard",
                     "/v1/marathon_dashboard",
                     request_method="GET")
    config.add_route("metastatus", "/v1/metastatus")
    config.scan()
    return CORS(config.make_wsgi_app(),
                headers="*",
                methods="*",
                maxage="180",
                origin="*")
示例#16
0
from wsgicors import CORS
from factory import create_app

app = CORS(create_app(), headers='*', methods='*', origin='*')
示例#17
0
 def __call__(self, environ, start_response, **options):
     cors = CORS(super().__call__, **options)
     return cors(environ, start_response)
示例#18
0
文件: app.py 项目: jairojair/emeeting
    title="Emeeting API",
    description="An API for managing your room meetings.",
    version="0.0.1",
))

get_docs = OpenAPIUIHandler()
"""
Add middlewares
"""

middlewares = [prometheus_middleware, ResponseRendererMiddleware()]
"""
Include or add routes
"""

routes = [
    Route("/", get_docs),
    Route("/schema", get_schema),
    Route("/metrics", expose_metrics),
    Include("/v1/rooms", routes=room.routes),
    Include("/v1/meetings", routes=meeting.routes),
]
"""
Start application
"""

app = App(routes=routes, middleware=middlewares)
app = CORS(app, headers="*", methods="*", origin="*", maxage="86400")

log.info("Start application successfully.")
示例#19
0
文件: main.py 项目: cyrusaf/foos-api
    def CreateLeague(self, req, ctx):
        league = League.new(req.name)
        self.league_store.insert_league(league)
        return twirp.CreateLeagueResponse(league=twirp.League(
            id=league.id, name=league.name, player_ids=league.player_ids))

    def GetLeagues(self, req, ctx):
        leagues = self.league_store.get_leagues()
        return twirp.GetLeaguesResponse(leagues=[
            twirp.League(
                id=league.id, name=league.name, player_ids=league.player_ids)
            for league in leagues
        ])


@twirp.error_occurred.connect
def error_occurred(ctx):
    print("error")
    print(ctx)
    print(ctx["exception"])
    print(ctx["exc_info"])
    print(ctx["exc_info"][2])
    traceback.print_tb(ctx["exc_info"][2])


if __name__ == "__main__":
    app = twirp.FoosServer(
        Foos(PlayerStoreLocal(), GameStoreLocal(), LeagueStoreLocal()))
    bjoern.run(CORS(app, headers="*", methods="*", maxage="180", origin="*"),
               "0.0.0.0", 8080)