本文整理汇总了Python中pyramid.config.Configurator.action方法的典型用法代码示例。如果您正苦于以下问题:Python Configurator.action方法的具体用法?Python Configurator.action怎么用?Python Configurator.action使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.config.Configurator
的用法示例。
在下文中一共展示了Configurator.action方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_validation_error_view
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def add_validation_error_view(config: Configurator, view_name: str) -> None:
"""Use this to register a view for rendering validation errors."""
def register() -> None:
config.registry._pyramid_openapi3_validation_view_name = view_name # noqa: SF01
config.action(
("pyramid_openapi3_validation_error_view",), register, order=PHASE0_CONFIG
)
示例2: setup_sqlalchemy
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def setup_sqlalchemy(config: Configurator,
*,
settings: Optional[dict] =_NOT_SET,
prefix: str ='sqlalchemy.',
engine: Optional['sqlalchemy.Engine'] =_NOT_SET,
name: str='') -> None:
"""
Sets up SQLAlchemy, creating a request scoped service for the ORM session.
Include all models before calling this configurator.
:param config: the configurator
:param base: The declarative base class. Required
:param settings: Optional settings dictionary for the engine creation
:param prefix: Optional settings prefix for the engine settings
:param engine: The engine to use - if specified, settings must not be
given, or vice versa
:param name: the alternate name for which to bind the session service
"""
from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker, Session, configure_mappers, scoped_session
if settings is not _NOT_SET:
if engine is not _NOT_SET:
raise ValueError('Only one of settings, '
'engine may be specified')
else:
settings = config.registry.settings
if engine is _NOT_SET:
engine = engine_from_config(settings, prefix)
session_factory = sessionmaker()
session_factory.configure(bind=engine)
if 'tet.sqlalchemy.simple.factories' not in config.registry:
config.registry['tet.sqlalchemy.simple.factories' ] = {}
config.registry['tet.sqlalchemy.simple.factories'][name] = session_factory
def _session_service(context: Any, request: Request):
return get_tm_session(session_factory, request.tm)
config.register_service_factory(
_session_service, Session, Interface, name=name)
config.register_service(
scoped_session(session_factory),
name='scoped_session' + (':' + name if name else '')
)
config.action('tet.sqlalchemy.simple.configure_mappers', configure_mappers)
示例3: add_sdi_add_view_directive
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def add_sdi_add_view_directive(config: Configurator,
iresource: IInterface,
view_name: str,
):
"""Create `add_sdi_add_view` pyramid config directive.
Example usage::
config.add_sdi_add_view(IResource, 'add_iresource')
"""
config.action(('add_sdi_add_view', iresource, view_name),
add_sdi_add_view,
args=(config, iresource, view_name))
示例4: add_explorer_view
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def add_explorer_view(
config: Configurator,
route: str = "/docs/",
route_name: str = "pyramid_openapi3.explorer",
template: str = "static/index.html",
ui_version: str = "3.17.1",
) -> None:
"""Serve Swagger UI at `route` url path.
:param route: URL path where to serve
:param route_name: Route name that's being added
:param template: Dotted path to the html template that renders Swagger UI response
:param ui_version: Swagger UI version string
"""
def register():
resolved_template = AssetResolver().resolve(template)
def explorer_view(request):
settings = config.registry.settings
if settings.get("pyramid_openapi3") is None:
raise ConfigurationError(
"You need to call config.pyramid_openapi3_spec for explorer to work."
)
with open(resolved_template.abspath()) as f:
template = Template(f.read())
html = template.safe_substitute(
ui_version=ui_version,
spec_url=request.route_url(
settings["pyramid_openapi3"]["spec_route_name"]
),
)
return Response(html)
config.add_route(route_name, route)
config.add_view(route_name=route_name, view=explorer_view)
config.action(("pyramid_openapi3_add_explorer",), register, order=PHASE0_CONFIG)
示例5: add_spec_view
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def add_spec_view(
config: Configurator,
filepath: str,
route: str = "/openapi.yaml",
route_name: str = "pyramid_openapi3.spec",
) -> None:
"""Serve and register OpenApi 3.0 specification file.
:param filepath: absolute/relative path to the specification file
:param route: URL path where to serve specification file
:param route_name: Route name under which specification file will be served
"""
def register() -> None:
spec_dict = read_yaml_file(filepath)
validate_spec(spec_dict)
spec = create_spec(spec_dict)
def spec_view(request: Request) -> FileResponse:
return FileResponse(filepath, request=request, content_type="text/yaml")
config.add_route(route_name, route)
config.add_view(route_name=route_name, view=spec_view)
custom_formatters = config.registry.settings.get("pyramid_openapi3_formatters")
config.registry.settings["pyramid_openapi3"] = {
"filepath": filepath,
"spec_route_name": route_name,
"spec": spec,
"request_validator": RequestValidator(spec, custom_formatters),
"response_validator": ResponseValidator(spec, custom_formatters),
}
config.action(("pyramid_openapi3_spec",), register, order=PHASE0_CONFIG)
示例6: main
# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import action [as 别名]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
settings.setdefault("jinja2.i18n.domain", "testscaffold")
auth_tkt = AuthTktAuthenticationPolicy(
settings["auth_tkt.seed"], callback=groupfinder
)
auth_token_policy = AuthTokenAuthenticationPolicy(callback=groupfinder)
authorization_policy = ACLAuthorizationPolicy()
def policy_selector(request):
# default policy
policy = "auth_tkt"
# return API token policy if header is present
if request.headers.get("x-testscaffold-auth-token"):
policy = "auth_token_policy"
log.info("Policy used: {}".format(policy))
return policy
auth_policy = PyramidSelectorPolicy(
policy_selector=policy_selector,
policies={
"auth_tkt": auth_tkt,
"auth_token_policy": auth_token_policy
}
)
settings["jinja2.undefined"] = "strict"
config = Configurator(
settings=settings,
authentication_policy=auth_policy,
authorization_policy=authorization_policy,
root_factory="testscaffold.security.RootFactory",
)
config.include("pyramid_apispec.views")
config.pyramid_apispec_add_explorer(
spec_route_name="openapi_spec")
config.add_translation_dirs("testscaffold:locale/", "wtforms:locale/")
# modify json renderer
json_renderer = JSON(indent=4)
def datetime_adapter(obj, request):
return obj.isoformat()
json_renderer.add_adapter(datetime.datetime, datetime_adapter)
json_renderer.add_adapter(datetime.date, datetime_adapter)
config.add_renderer("json", json_renderer)
# set crypto key used to store sensitive data like auth tokens
encryption.ENCRYPTION_SECRET = settings["encryption_secret"]
# CSRF is enabled by defualt
# use X-XSRF-TOKEN for angular
# config.set_default_csrf_options(require_csrf=True, header='X-XSRF-TOKEN')
config.add_view_deriver(
"testscaffold.predicates.auth_token_aware_csrf_view", name="csrf_view"
)
config.include("pyramid_mailer")
config.include("pyramid_jinja2")
config.include("pyramid_redis_sessions")
config.include("ziggurat_foundations.ext.pyramid.sign_in")
# make request.user available
config.add_request_method("testscaffold.util.request:get_user", "user", reify=True)
config.add_request_method(
"testscaffold.util.request:safe_json_body", "safe_json_body", reify=True
)
config.add_request_method(
"testscaffold.util.request:unsafe_json_body", "unsafe_json_body", reify=True
)
config.add_request_method(
"testscaffold.util.request:get_authomatic", "authomatic", reify=True
)
config.add_view_predicate(
"context_type_class", "testscaffold.predicates.ContextTypeClass"
)
config.scan("testscaffold.events")
config.scan("testscaffold.subscribers")
config.include("testscaffold.models")
config.include("testscaffold.routes")
config.include("testscaffold.views")
# configure celery in later phase
def wrap_config_celery():
configure_celery(config.registry)
config.action(None, wrap_config_celery, order=PHASE3_CONFIG + 999)
# setup dogpile cache
cache_regions.regions = cache_regions.CacheRegions(settings)
config.registry.cache_regions = cache_regions.regions
if not config.registry.settings.get("testscaffold.ignore_warnings", True):
warnings.filterwarnings("default")
#.........这里部分代码省略.........