Esempio n. 1
0
def includeme(config):
    settings = config.get_settings()
    for key, value in settings.iteritems():
        if not key.startswith('static.'):
            continue
        path, url = aslist(value)
        config.add_static_view(name=url, path=path)
        view_config(route_name=key)(staticRedirectView)
        config.add_route(key, url)
Esempio n. 2
0
def includeme(config):
    """Setup swagger ui

    swagger_ui.url: URL at which the swagger ui should be accessable
                    swagger-ui will not be available if not provided or empty
    """
    settings = config.get_settings()
    swagger_url = settings.get('swagger_ui.url')
    if swagger_url:
        view_config(route_name='swagger-ui',
                    renderer='index.jinja2'
                   )(swaggerUIView)
        config.add_route('swagger-ui', swagger_url)
        config.add_static_view(name='/%s_resources/' % swagger_url,
                               path='iris.service:swaggerui/dist')
Esempio n. 3
0
File: common.py Progetto: dulton/IVR
 def __init__(self, **settings):
     method = self.__class__.__name__.split('_')[0].upper()
     super(_rest_view, self).__init__(request_method=method,
                                      **settings)
     # add CORS OPTIONS method support for registered REST view
     route_name = settings['route_name']
     if route_name in self.cors_route:
         self.cors_route[route_name].add_method(method)
         return
     handler = PrefligthHandlerFactory(route_name, method)
     self.cors_route[route_name] = handler
     view_config(request_method='OPTIONS', route_name=route_name, _depth=1)(handler)
     # dirty hack
     # to get caller's module, in order to inject preflight_handler to that module
     # so when scan configuration, pyramid will pick OPTIONS for that route
     module = inspect.getmodule(inspect.getouterframes(inspect.currentframe())[0][0].f_back)
     setattr(module, 'preflight_'+route_name, handler)
Esempio n. 4
0
File: views.py Progetto: bradparks/h
def api_config(**kwargs):
    """Extend Pyramid's @view_config decorator with modified defaults."""
    config = {
        'accept': 'application/json',
        'renderer': 'json',
    }
    config.update(kwargs)
    return view_config(**config)
Esempio n. 5
0
def api_config(**kwargs):
    """Pyramid's @view_config decorator but with modified defaults"""
    config = {
        # The containment predicate ensures we only respond to API calls
        'containment': 'h.resources.APIResource',
        'accept': 'application/json',
        'renderer': 'json',
    }
    config.update(kwargs)
    return view_config(**config)
Esempio n. 6
0
    def __call__(self, wrapped):
        method = self.method or wrapped.__name__
        kw = self.kw.copy()

        def xmlrpc_method_predicate(context, request):
            return getattr(request, "rpc_method", None) == method

        predicates = kw.setdefault("custom_predicates", [])
        predicates.append(xmlrpc_method_predicate)
        return view_config(**kw)(wrapped)
Esempio n. 7
0
File: views.py Progetto: djcun95/h
def api_config(**settings):
    """
    A view configuration decorator with defaults.

    JSON in and out. CORS with tokens and client id but no cookie.
    """
    settings.setdefault('accept', 'application/json')
    settings.setdefault('renderer', 'json')
    settings.setdefault('decorator', cors_policy)
    return view_config(**settings)
Esempio n. 8
0
    def __call__(self, wrapped, view_config=view_config):
        # view_config passable for unit testing purposes only
        method_name = self.method or wrapped.__name__
        try:
            # pyramid 1.1
            from pyramid.renderers import null_renderer

            renderer = null_renderer
        except ImportError:  # pragma: no cover
            # pyramid 1.0
            renderer = None
        return view_config(route_name=self.route_name, name=method_name, renderer=renderer)(wrapped)
Esempio n. 9
0
 def __call__(self, wrapped):
     view_config.venusian = self.venusian
     method_name = self.method or wrapped.__name__
     try:
         # pyramid 1.1
         from pyramid.renderers import null_renderer
         renderer = null_renderer
     except ImportError:
         # pyramid 1.0
         renderer = None
     return view_config(route_name=self.route_name, name=method_name,
                        renderer=renderer)(wrapped)
Esempio n. 10
0
    def __call__(self, **settings):
        new_settings = {}
        new_settings.update(self.__config_defaults)
        new_settings.update(settings)

        new_settings.setdefault('custom_predicates', [])
        predicates = new_settings['custom_predicates']
        predicates.append(self.lookup_records)
        if 'permit' in new_settings:
            predicates.append(new_settings.pop('permit'))

        permit = self.__permits.get(new_settings.get('request_method', 'GET'))
        if permit:
            predicates.append(permit)

        return view_config(**new_settings)
Esempio n. 11
0
def api_config(**settings):
    """
    A view configuration decorator with defaults.

    JSON in and out. CORS with tokens and client id but no cookie.
    """
    settings.setdefault('accept', 'application/json')
    settings.setdefault('renderer', 'json')
    settings.setdefault('decorator', cors_policy)

    request_method = settings.get('request_method', ())
    if not isinstance(request_method, tuple):
        request_method = (request_method,)
    if len(request_method) == 0:
        request_method = ('DELETE', 'GET', 'HEAD', 'POST', 'PUT',)
    settings['request_method'] = request_method + ('OPTIONS',)

    return view_config(**settings)
Esempio n. 12
0
File: views.py Progetto: chrber/h
def json_view(**settings):
    """A view configuration decorator with JSON defaults."""
    settings.setdefault("accept", "application/json")
    settings.setdefault("renderer", "json")
    return view_config(**settings)
Esempio n. 13
0
        self.request = request

    def __call__(self, *args, **kwargs):
        return Response("hello")


# 还有下面这种奇葩的使用方式(我想你在项目中肯定不会这样写的)
class MyView2:
    def __init__(self, request):
        self.request = request

    def __call__(self, *args, **kwargs):
        return Response("Hello2")


my_view2 = view_config(route_name="hello")(MyView2)


# 多个 view_config 修饰同一个函数, 这样路由 edit 和 change 都会调用 edit 函数
@view_config(route_name="edit")
@view_config(route_name="change")
def edit(request):
    return Response("edited!")


# 直接修饰类的方法
class MyView3:
    def __init__(self, request):
        self.request = request

    @view_config(route_name="hello3")
Esempio n. 14
0
    
    @srpc(String, Integer, _returns=Iterable(String))
    def say_hello(name, times):
        '''
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''

        for i in range(times):
            yield 'Hello, %s' % name

# view
soapApp = view_config(route_name="home")(
    pyramid_soap11_application([HelloWorldService], tns))

if __name__ == '__main__':
    # configuration settings
    settings = {}
    settings['debug_all'] = True
    # configuration setup
    config = Configurator(settings=settings)
    # routes setup
    config.add_route('home', '/')
    config.scan()
    # serve app
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8000, app)
    server.serve_forever()
Esempio n. 15
0
    return 'grokked_post'

@view_config(name='stacked2', renderer=null_renderer)
@view_config(name='stacked1', renderer=null_renderer)
def stacked(context, request):
    return 'stacked'

class stacked_class(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        return 'stacked_class'

stacked_class = view_config(name='stacked_class1',
                            renderer=null_renderer)(stacked_class)
stacked_class = view_config(name='stacked_class2',
                            renderer=null_renderer)(stacked_class)
    
class oldstyle_grokked_class:
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        return 'oldstyle_grokked_class'
    
oldstyle_grokked_class = view_config(name='oldstyle_grokked_class',
                                     renderer=null_renderer)(
    oldstyle_grokked_class)
Esempio n. 16
0
 def __call__(self, wrapped):
     view_config.venusian = self.venusian
     method_name = self.method or wrapped.__name__
     return view_config(route_name=self.route_name, name=method_name)(wrapped)
Esempio n. 17
0
    if order_by is not None:
        models = models.order_by(order_by)
    c.models = models

def success_redirect(c, message=None, route_name=None):
    c.request.session.flash(message.format(obj=c.obj))
    return HTTPFound(c.request.route_url(route_name))

def add_form(c, form):
    c.form = form.format(action=c.request.current_route_path(), method="POST") #fixme

loop = (view_loop()
        .add(partial(create_model, model=User))
        .add(partial(add_session))
        .add(partial(success_redirect, message="user: {obj.name} is created.", route_name="user.create"))
)
user_create = view_config(route_name="user.create", request_method="POST", renderer='input.mako')(ViewFromLoopForLazy(loop, "create_user"))

user_form = """
<form action="{action}" method="{method}">
  <input name="name" type="text" value=""/>
  <input type="submit"/>
</form>
"""

loop = (view_loop() 
        .add(partial(get_model_list, model=User, order_by=sa.asc(User.name)))
        .add(partial(add_form, form=user_form))
)
user_create_input = view_config(route_name="user.create", request_method="GET", renderer='input.mako')(ViewFromLoopForLazy(loop, "create_user_input"))
Esempio n. 18
0
from pyramid.view import view_config

from marlton.interfaces import IWebSite

from marlton.utils import API

@view_config(for_=IWebSite, name='videos', permission='view',
             renderer='marlton.views:templates/videos.pt')
def videos_view(context, request):
    return dict(
        api = API(context, request),
        )

for x in range(1, 11):
    # add groundhog1 - 10 urls
    gh_view = view_config(for_=IWebSite,
                          name='groundhog%s' % x, permission='view',
                          renderer='marlton.views:templates/videos.pt')
    videos_view = gh_view(videos_view)
Esempio n. 19
0
from sqlalchemy.exc import DBAPIError

from .models import (
    DBSession,
    MyModel,
    )
{% endif %}
{% if cookiecutter.persistence == 'zodb' %}
from .models import MyModel
{% endif %}


{% if cookiecutter.persistence == 'zodb' -%}
@view_config(context=MyModel,
{% else -%}
@view_config(route_name='home',
{% endif -%}
             {% if cookiecutter.template_engine == 'chameleon' -%}renderer='templates/mytemplate.pt'){% endif -%}
             {% if cookiecutter.template_engine == 'jinja2' -%}renderer='templates/mytemplate.jinja2'){% endif -%}
             {% if cookiecutter.template_engine == 'mako' -%}renderer='templates/mytemplate.mako'){% endif %}
def my_view(request):
{% if cookiecutter.persistence != 'sqlalchemy' %}
    return {'project': '{{ cookiecutter.project_name }}'}
{% else %}
    try:
        one = DBSession.query(MyModel).filter(MyModel.name == 'one').first()
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    return {'one': one, 'project': '{{ cookiecutter.project_name}}'}

Esempio n. 20
0
def api_config(login_required=True, *args, **kwargs):
    decorators = []
    if login_required:
        decorators.append(login_required_decorator)
    return view_config(decorator=decorators, *args, **kwargs)
Esempio n. 21
0
    return 'grokked_post'

@view_config(name='stacked2')
@view_config(name='stacked1')
def stacked(context, request):
    return 'stacked'

class stacked_class(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        return 'stacked_class'

stacked_class = view_config(name='stacked_class1')(stacked_class)
stacked_class = view_config(name='stacked_class2')(stacked_class)
    
class oldstyle_grokked_class:
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        return 'oldstyle_grokked_class'
    
oldstyle_grokked_class = view_config(name='oldstyle_grokked_class')(
    oldstyle_grokked_class)

class grokked_class(object):
    def __init__(self, context, request):
Esempio n. 22
0
def json_view(**settings):
    """A view configuration decorator with JSON defaults."""
    settings.setdefault('accept', 'application/json')
    settings.setdefault('renderer', 'json')
    return view_config(**settings)
Esempio n. 23
0
def auth_view(**settings):
    settings.setdefault('accept', 'text/html')
    settings.setdefault('renderer', 'h:templates/auth.html.jinja2')
    return view_config(**settings)
Esempio n. 24
0
    return {}

@view_config(route_name='test_predicates',
        renderer='__main__:templates/index.mako')
def test_predicates(request):
    return {'title':'Test route predicates'}

@view_config(route_name='test_chameleon_exc',
             renderer='__main__:templates/error.pt')
@view_config(route_name='test_mako_exc',
        renderer='__main__:templates/error.mako')
def test_template_exc(request):
    return {'title':'Test template exceptions'}
if pyramid_jinja2 is not None:
    test_template_exc = view_config(
        route_name='test_jinja2_exc',
        renderer='__main__:templates/error.jinja2')(
        test_template_exc)


class DummyRootFactory(object):
    def __init__(self, request):
        self.request = request
    def __getitem__(self, name):
        return self

if __name__ == '__main__':
    # configuration settings
    try:
        # ease testing py2 and py3 in same directory
        shutil.rmtree(os.path.join(here, 'mako_modules'))
    except:
Esempio n. 25
0
    """Basic function for putting a server into some state, for basic state-change calls."""
    vm_id, actor_id = _resolve_vm(request)
    return {"vm_id": vm_id, "touch_id": server.touch_to_state(actor_id, vm_id, target_state)}


# Pyramid is not designed to allow you to add view configurations programatically.
# But in Python all things are possible.  Here is a way to set up view configurations in a loop.
# This will declare the functions "set_server_to_Boosting", etc...
# And bind them to the routes "server_Boosting" and "server_by_id_Boosting"

### Here are the states that can only be set by agents...
for state in ["Stopped", "Started", "Prepared", "Pre_Deboosted", "Boosting", "Deboosting", "Starting_Boosted"]:
    funcname = "set_server_to_" + state
    globals()[funcname] = lambda request, state=state: _set_server_state(request, state)
    globals()[funcname] = view_config(
        request_method="POST", routes=["server_" + state, "server_by_id_" + state], renderer="json", permission="act"
    )(globals()[funcname])
    globals()[funcname].__name__ = funcname
    globals()[funcname].__qualname__ = funcname

### States that any user can put their server into...
for state in ["Starting", "Stopping", "Restarting", "Error"]:
    funcname = "set_server_to_" + state
    globals()[funcname] = lambda request, state=state: _set_server_state(request, state)
    globals()[funcname] = view_config(
        request_method="POST", routes=["server_" + state, "server_by_id_" + state], renderer="json", permission="use"
    )(globals()[funcname])
    globals()[funcname].__name__ = funcname
    globals()[funcname].__qualname__ = funcname

### Any user can Boost, but it will cost.