Add initial pep8 support.
This ignores plenty of warnings and errors in pep8 and only
focuses on a small subset that can easily be achieved.
Ignores applying pep8 to tests for now and only enforces on
the pyramid core code.
| | |
| | | |
| | | VALID_TOKEN = re.compile(r"^[A-Za-z][A-Za-z0-9+_-]*$") |
| | | |
| | | |
| | | class CallbackAuthenticationPolicy(object): |
| | | """ Abstract class """ |
| | | |
| | |
| | | debug and self._log( |
| | | ('use of userid %r is disallowed by any built-in Pyramid ' |
| | | 'security policy, returning None' % userid), |
| | | 'authenticated_userid' , |
| | | 'authenticated_userid', |
| | | request) |
| | | return None |
| | | |
| | | |
| | | if self.callback is None: |
| | | debug and self._log( |
| | | 'there was no groupfinder callback; returning %r' % (userid,), |
| | |
| | | request |
| | | ) |
| | | return effective_principals |
| | | |
| | | |
| | | if self.callback is None: |
| | | debug and self._log( |
| | | 'groupfinder callback is None, so groups is []', |
| | |
| | | effective_principals,), |
| | | 'effective_principals', |
| | | request |
| | | ) |
| | | ) |
| | | return effective_principals |
| | | |
| | | |
| | | @implementer(IAuthenticationPolicy) |
| | | class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy): |
| | |
| | | 'authenticated_userid', |
| | | request) |
| | | return None |
| | | |
| | | |
| | | if self._clean_principal(userid) is None: |
| | | self.debug and self._log( |
| | | ('use of userid %r is disallowed by any built-in Pyramid ' |
| | |
| | | |
| | | def remember(self, request, userid, **kw): |
| | | """ Store the ``userid`` as ``repoze.who.userid``. |
| | | |
| | | |
| | | The identity to authenticated to :mod:`repoze.who` |
| | | will contain the given userid as ``userid``, and |
| | | provide all keyword arguments as additional identity |
| | |
| | | hashalg='md5', parent_domain=False, domain=None): |
| | | |
| | | serializer = _SimpleSerializer() |
| | | |
| | | |
| | | self.cookie_profile = CookieProfile( |
| | | cookie_name = cookie_name, |
| | | secure = secure, |
| | | max_age = max_age, |
| | | httponly = http_only, |
| | | path = path, |
| | | cookie_name=cookie_name, |
| | | secure=secure, |
| | | max_age=max_age, |
| | | httponly=http_only, |
| | | path=path, |
| | | serializer=serializer |
| | | ) |
| | | ) |
| | | |
| | | self.secret = secret |
| | | self.cookie_name = cookie_name |
| | |
| | | kw['domains'] = domains |
| | | if max_age is not None: |
| | | kw['max_age'] = max_age |
| | | |
| | | |
| | | headers = profile.get_headers(value, **kw) |
| | | return headers |
| | | |
| | |
| | | |
| | | def dumps(self, appstruct): |
| | | return bytes_(appstruct) |
| | | |
| | |
| | | :class:`pyramid.security.ACLDenied` if not.""" |
| | | |
| | | acl = '<No ACL found on any object in resource lineage>' |
| | | |
| | | |
| | | for location in lineage(context): |
| | | try: |
| | | acl = location.__acl__ |
| | |
| | | |
| | | allowed_here = set() |
| | | denied_here = set() |
| | | |
| | | |
| | | if acl and callable(acl): |
| | | acl = acl() |
| | | |
| | |
| | | if not is_nonstr_iter(ace_permissions): |
| | | ace_permissions = [ace_permissions] |
| | | if (ace_action == Allow) and (permission in ace_permissions): |
| | | if not ace_principal in denied_here: |
| | | if ace_principal not in denied_here: |
| | | allowed_here.add(ace_principal) |
| | | if (ace_action == Deny) and (permission in ace_permissions): |
| | | denied_here.add(ace_principal) |
| | |
| | | if session_factory is not None: |
| | | self.set_session_factory(session_factory) |
| | | |
| | | tweens = aslist(registry.settings.get('pyramid.tweens', [])) |
| | | tweens = aslist(registry.settings.get('pyramid.tweens', [])) |
| | | for factory in tweens: |
| | | self._add_tween(factory, explicit=True) |
| | | |
| | |
| | | if package is None: # pragma: no cover |
| | | package = caller_package() |
| | | |
| | | ctorkw = {'config':self} |
| | | ctorkw = {'config': self} |
| | | ctorkw.update(kw) |
| | | |
| | | scanner = self.venusian.Scanner(**ctorkw) |
| | | |
| | | |
| | | scanner.scan(package, categories=categories, onerror=onerror, |
| | | ignore=ignore) |
| | | |
| | |
| | | # Push the registry onto the stack in case any code that depends on |
| | | # the registry threadlocal APIs used in listeners subscribed to the |
| | | # IApplicationCreated event. |
| | | self.manager.push({'registry':self.registry, 'request':None}) |
| | | self.manager.push({'registry': self.registry, 'request': None}) |
| | | try: |
| | | self.registry.notify(ApplicationCreated(app)) |
| | | finally: |
| | |
| | | |
| | | return app |
| | | |
| | | |
| | | # this class is licensed under the ZPL (stolen from Zope) |
| | | class ActionState(object): |
| | | def __init__(self): |
| | | # NB "actions" is an API, dep'd upon by pyramid_zcml's load_zcml func |
| | | self.actions = [] |
| | | self.actions = [] |
| | | self._seen_files = set() |
| | | |
| | | def processSpec(self, spec): |
| | |
| | | ConfigurationExecutionError(t, v, info), |
| | | tb) |
| | | finally: |
| | | del t, v, tb |
| | | del t, v, tb |
| | | |
| | | if introspector is not None: |
| | | for introspectable in introspectables: |
| | |
| | | See :ref:`changing_the_traverser` for more information. |
| | | """ |
| | | iface = self.maybe_dotted(iface) |
| | | adapter= self.maybe_dotted(adapter) |
| | | adapter = self.maybe_dotted(adapter) |
| | | def register(iface=iface): |
| | | if iface is None: |
| | | iface = Interface |
| | |
| | | reg = get_current_registry() |
| | | overrides = reg.queryUtility(IPackageOverrides, self.module_name) |
| | | return overrides |
| | | |
| | | |
| | | def get_resource_filename(self, manager, resource_name): |
| | | """ Return a true filesystem path for resource_name, |
| | | co-ordinating the extraction with manager, if the resource |
| | |
| | | return filename |
| | | return pkg_resources.DefaultProvider.get_resource_filename( |
| | | self, manager, resource_name) |
| | | |
| | | |
| | | def get_resource_stream(self, manager, resource_name): |
| | | """ Return a readable file-like object for resource_name.""" |
| | | overrides = self._get_overrides() |
| | | if overrides is not None: |
| | | stream = overrides.get_stream(resource_name) |
| | | stream = overrides.get_stream(resource_name) |
| | | if stream is not None: |
| | | return stream |
| | | return pkg_resources.DefaultProvider.get_resource_stream( |
| | |
| | | self.action(None, register, introspectables=(intr,)) |
| | | |
| | | override_resource = override_asset # bw compat |
| | | |
| | | |
| | |
| | | hashes = [hashes] |
| | | for h in hashes: |
| | | phash.update(bytes_(h)) |
| | | weights.append(1 << n+1) |
| | | weights.append(1 << n + 1) |
| | | preds.append(pred) |
| | | if kw: |
| | | raise ConfigurationError('Unknown predicate values: %r' % (kw,)) |
| | |
| | | self.decorated_view( |
| | | self.rendered_view( |
| | | self.mapped_view( |
| | | view))))))))) |
| | | view))))))))) |
| | | |
| | | @wraps_view |
| | | def mapped_view(self, view): |
| | |
| | | permission = None |
| | | |
| | | wrapped_view = view |
| | | if self.authn_policy and self.authz_policy and (permission is not None): |
| | | if ( |
| | | self.authn_policy and |
| | | self.authz_policy and |
| | | (permission is not None) |
| | | ): |
| | | def _permitted(context, request): |
| | | principals = self.authn_policy.effective_principals(request) |
| | | return self.authz_policy.permits(context, principals, |
| | |
| | | else: |
| | | principals = self.authn_policy.effective_principals( |
| | | request) |
| | | msg = str(self.authz_policy.permits(context, principals, |
| | | msg = str(self.authz_policy.permits(context, |
| | | principals, |
| | | permission)) |
| | | else: |
| | | msg = 'Allowed (no authorization policy in use)' |
| | |
| | | preds = self.kw.get('predicates', ()) |
| | | if not preds: |
| | | return view |
| | | |
| | | def predicate_wrapper(context, request): |
| | | for predicate in preds: |
| | | if not predicate(context, request): |
| | | view_name = getattr(view, '__name__', view) |
| | | raise PredicateMismatch( |
| | | 'predicate mismatch for view %s (%s)' % ( |
| | | view_name, predicate.text())) |
| | | 'predicate mismatch for view %s (%s)' % ( |
| | | view_name, predicate.text())) |
| | | return view(context, request) |
| | | |
| | | def checker(context, request): |
| | | return all((predicate(context, request) for predicate in |
| | | preds)) |
| | |
| | | (accept is None) and |
| | | (order == MAX_ORDER) and |
| | | (phash == DEFAULT_PHASH) |
| | | ): |
| | | ): |
| | | return view # defaults |
| | | def attr_view(context, request): |
| | | return view(context, request) |
| | |
| | | renderer = renderers.RendererHelper( |
| | | name=renderer_name, |
| | | package=self.kw.get('package'), |
| | | registry = registry) |
| | | registry=registry) |
| | | if '__view__' in attrs: |
| | | view_inst = attrs.pop('__view__') |
| | | else: |
| | |
| | | http_cache=None, |
| | | match_param=None, |
| | | check_csrf=None, |
| | | **predicates): |
| | | **predicates |
| | | ): |
| | | """ Add a :term:`view configuration` to the current |
| | | configuration state. Arguments to ``add_view`` are broken |
| | | down below into *predicate* arguments and *non-predicate* |
| | |
| | | if isinstance(renderer, string_types): |
| | | renderer = renderers.RendererHelper( |
| | | name=renderer, package=self.package, |
| | | registry = self.registry) |
| | | registry=self.registry) |
| | | |
| | | if accept is not None: |
| | | accept = accept.lower() |
| | |
| | | # is. It can't be computed any sooner because thirdparty |
| | | # predicates may not yet exist when add_view is called. |
| | | order, preds, phash = predlist.make(self, **pvals) |
| | | view_intr.update({'phash':phash, 'order':order, 'predicates':preds}) |
| | | view_intr.update({ |
| | | 'phash': phash, |
| | | 'order': order, |
| | | 'predicates': preds |
| | | }) |
| | | return ('view', context, name, route_name, phash) |
| | | |
| | | discriminator = Deferred(discrim_func) |
| | |
| | | tmpl_intr is not None and |
| | | intrspc is not None and |
| | | intrspc.get('renderer factories', renderer_type) is not None |
| | | ): |
| | | ): |
| | | # allow failure of registered template factories to be deferred |
| | | # until view execution, like other bad renderer factories; if |
| | | # we tried to relate this to an existing renderer factory |
| | |
| | | permission, |
| | | permission, |
| | | 'permission' |
| | | ) |
| | | ) |
| | | perm_intr['value'] = permission |
| | | perm_intr.relate('views', discriminator) |
| | | introspectables.append(perm_intr) |
| | |
| | | factory, |
| | | weighs_more_than=weighs_more_than, |
| | | weighs_less_than=weighs_less_than |
| | | ) |
| | | ) |
| | | |
| | | def add_default_view_predicates(self): |
| | | p = pyramid.config.predicates |
| | |
| | | ('physical_path', p.PhysicalPathPredicate), |
| | | ('effective_principals', p.EffectivePrincipalsPredicate), |
| | | ('custom', p.CustomPredicate), |
| | | ): |
| | | ): |
| | | self.add_view_predicate(name, factory) |
| | | |
| | | def derive_view(self, view, attr=None, renderer=None): |
| | |
| | | if isinstance(renderer, string_types): |
| | | renderer = renderers.RendererHelper( |
| | | name=renderer, package=self.package, |
| | | registry = self.registry) |
| | | registry=self.registry) |
| | | if renderer is None: |
| | | # use default renderer if one exists |
| | | if self.registry.queryUtility(IRendererFactory) is not None: |
| | |
| | | mapper=None, |
| | | match_param=None, |
| | | **predicates |
| | | ): |
| | | ): |
| | | """ Add a forbidden view to the current configuration state. The |
| | | view will be called when Pyramid or application code raises a |
| | | :exc:`pyramid.httpexceptions.HTTPForbidden` exception and the set of |
| | |
| | | raise ConfigurationError( |
| | | '%s may not be used as an argument to add_forbidden_view' |
| | | % arg |
| | | ) |
| | | ) |
| | | |
| | | if view is None: |
| | | view = default_exceptionresponse_view |
| | |
| | | permission=NO_PERMISSION_REQUIRED, |
| | | attr=attr, |
| | | renderer=renderer, |
| | | ) |
| | | ) |
| | | settings.update(predicates) |
| | | return self.add_view(**settings) |
| | | |
| | |
| | | match_param=None, |
| | | append_slash=False, |
| | | **predicates |
| | | ): |
| | | ): |
| | | """ Add a default Not Found View to the current configuration state. |
| | | The view will be called when Pyramid or application code raises an |
| | | :exc:`pyramid.httpexceptions.HTTPNotFound` exception (e.g. when a |
| | |
| | | raise ConfigurationError( |
| | | '%s may not be used as an argument to add_notfound_view' |
| | | % arg |
| | | ) |
| | | ) |
| | | |
| | | if view is None: |
| | | view = default_exceptionresponse_view |
| | |
| | | match_param=match_param, |
| | | route_name=route_name, |
| | | permission=NO_PERMISSION_REQUIRED, |
| | | ) |
| | | ) |
| | | settings.update(predicates) |
| | | if append_slash: |
| | | view = self._derive_view(view, attr=attr, renderer=renderer) |
| | |
| | | return ( |
| | | isinstance(o, Exception) or |
| | | (inspect.isclass(o) and (issubclass(o, Exception))) |
| | | ) |
| | | ) |
| | | |
| | | |
| | | @implementer(IStaticURLInfo) |
| | |
| | | |
| | | # register a route using the computed view, permission, and |
| | | # pattern, plus any extras passed to us via add_static_view |
| | | pattern = "%s*subpath" % name # name already ends with slash |
| | | pattern = "%s*subpath" % name # name already ends with slash |
| | | if config.route_prefix: |
| | | route_name = '__%s/%s' % (config.route_prefix, name) |
| | | else: |
| | |
| | | permission=permission, |
| | | context=context, |
| | | renderer=renderer, |
| | | ) |
| | | ) |
| | | |
| | | def register(): |
| | | registrations = self._get_registrations(config.registry) |
| | | |
| | | names = [ t[0] for t in registrations ] |
| | | names = [t[0] for t in registrations] |
| | | |
| | | if name in names: |
| | | idx = names.index(name) |
| | |
| | | intr['spec'] = spec |
| | | |
| | | config.action(None, callable=register, introspectables=(intr,)) |
| | | |
| | |
| | | be treated as :class:`HTTPNotFound`` by any exception view |
| | | registrations. Thus, typically, this exception will not be seen |
| | | publicly. |
| | | |
| | | |
| | | However, this exception will be raised if the predicates of all |
| | | views configured to handle another exception context cannot be |
| | | successfully matched. For instance, if a view is configured to |
| | |
| | | r.append(" For: %s" % (discriminator, )) |
| | | for info in infos: |
| | | for line in str(info).rstrip().split(CR): |
| | | r.append(" "+line) |
| | | r.append(" " + line) |
| | | |
| | | return CR.join(r) |
| | | |
| | |
| | | L.append('%r sorts before %r' % (dependent, dependees)) |
| | | msg = 'Implicit ordering cycle:' + '; '.join(L) |
| | | return msg |
| | | |
| | | |
| | |
| | | Substitution of WSGI environment values is performed if a ``request`` is |
| | | passed to the exception's constructor. |
| | | |
| | | The subclasses of :class:`~_HTTPMove` |
| | | The subclasses of :class:`~_HTTPMove` |
| | | (:class:`~HTTPMultipleChoices`, :class:`~HTTPMovedPermanently`, |
| | | :class:`~HTTPFound`, :class:`~HTTPSeeOther`, :class:`~HTTPUseProxy` and |
| | | :class:`~HTTPTemporaryRedirect`) are redirections that require a ``Location`` |
| | | :class:`~HTTPTemporaryRedirect`) are redirections that require a ``Location`` |
| | | field. Reflecting this, these subclasses have one additional keyword argument: |
| | | ``location``, which indicates the location to which to redirect. |
| | | """ |
| | |
| | | base class for exceptions with status codes in the 400s and 500s |
| | | |
| | | This is an exception which indicates that an error has occurred, |
| | | and that any work in progress should not be committed. |
| | | and that any work in progress should not be committed. |
| | | """ |
| | | |
| | | class HTTPRedirection(HTTPException): |
| | |
| | | subclass of :class:`~HTTPSuccessful` |
| | | |
| | | Indicates that the request has succeeded. |
| | | |
| | | |
| | | code: 200, title: OK |
| | | """ |
| | | code = 200 |
| | |
| | | |
| | | This indicates that request has been fulfilled and resulted in a new |
| | | resource being created. |
| | | |
| | | |
| | | code: 201, title: Created |
| | | """ |
| | | code = 201 |
| | |
| | | This indicates that the server has fulfilled the request but does |
| | | not need to return an entity-body, and might want to return updated |
| | | metainformation. |
| | | |
| | | |
| | | code: 204, title: No Content |
| | | """ |
| | | code = 204 |
| | |
| | | This indicates that the server has fulfilled the request and |
| | | the user agent SHOULD reset the document view which caused the |
| | | request to be sent. |
| | | |
| | | |
| | | code: 205, title: Reset Content |
| | | """ |
| | | code = 205 |
| | |
| | | |
| | | This indicates that the server has fulfilled the partial GET |
| | | request for the resource. |
| | | |
| | | |
| | | code: 206, title: Partial Content |
| | | """ |
| | | code = 206 |
| | |
| | | and agent-driven negotiation information is being provided so that |
| | | the user can select a preferred representation and redirect its |
| | | request to that location. |
| | | |
| | | |
| | | code: 300, title: Multiple Choices |
| | | """ |
| | | code = 300 |
| | |
| | | |
| | | This indicates that the requested resource resides temporarily under |
| | | a different URI. |
| | | |
| | | |
| | | code: 302, title: Found |
| | | """ |
| | | code = 302 |
| | |
| | | This indicates that the response to the request can be found under |
| | | a different URI and SHOULD be retrieved using a GET method on that |
| | | resource. |
| | | |
| | | |
| | | code: 303, title: See Other |
| | | """ |
| | | code = 303 |
| | |
| | | |
| | | This indicates that the requested resource MUST be accessed through |
| | | the proxy given by the Location field. |
| | | |
| | | |
| | | code: 305, title: Use Proxy |
| | | """ |
| | | # Not a move, but looks a little like one |
| | |
| | | |
| | | This indicates that the requested resource resides temporarily |
| | | under a different URI. |
| | | |
| | | |
| | | code: 307, title: Temporary Redirect |
| | | """ |
| | | code = 307 |
| | |
| | | subclass of :class:`~HTTPClientError` |
| | | |
| | | This indicates that the request requires user authentication. |
| | | |
| | | |
| | | code: 401, title: Unauthorized |
| | | """ |
| | | code = 401 |
| | |
| | | class HTTPPaymentRequired(HTTPClientError): |
| | | """ |
| | | subclass of :class:`~HTTPClientError` |
| | | |
| | | |
| | | code: 402, title: Payment Required |
| | | """ |
| | | code = 402 |
| | |
| | | # differences from webob.exc.HTTPForbidden: |
| | | # |
| | | # - accepts a ``result`` keyword argument |
| | | # |
| | | # |
| | | # - overrides constructor to set ``self.result`` |
| | | # |
| | | # differences from older ``pyramid.exceptions.Forbidden``: |
| | |
| | | |
| | | This indicates that the server did not find anything matching the |
| | | Request-URI. |
| | | |
| | | |
| | | code: 404, title: Not Found |
| | | |
| | | Raise this exception within :term:`view` code to immediately |
| | |
| | | capable of generating response entities which have content |
| | | characteristics not acceptable according to the accept headers |
| | | sent in the request. |
| | | |
| | | |
| | | code: 406, title: Not Acceptable |
| | | """ |
| | | # differences from webob.exc.HTTPNotAcceptable: |
| | |
| | | |
| | | This is similar to 401, but indicates that the client must first |
| | | authenticate itself with the proxy. |
| | | |
| | | |
| | | code: 407, title: Proxy Authentication Required |
| | | """ |
| | | code = 407 |
| | |
| | | |
| | | This indicates that the client did not produce a request within |
| | | the time that the server was prepared to wait. |
| | | |
| | | |
| | | code: 408, title: Request Timeout |
| | | """ |
| | | code = 408 |
| | |
| | | |
| | | This indicates that the request could not be completed due to a |
| | | conflict with the current state of the resource. |
| | | |
| | | |
| | | code: 409, title: Conflict |
| | | """ |
| | | code = 409 |
| | |
| | | |
| | | This indicates that the requested resource is no longer available |
| | | at the server and no forwarding address is known. |
| | | |
| | | |
| | | code: 410, title: Gone |
| | | """ |
| | | code = 410 |
| | |
| | | |
| | | This indicates that the server refuses to accept the request |
| | | without a defined Content-Length. |
| | | |
| | | |
| | | code: 411, title: Length Required |
| | | """ |
| | | code = 411 |
| | |
| | | This indicates that the precondition given in one or more of the |
| | | request-header fields evaluated to false when it was tested on the |
| | | server. |
| | | |
| | | |
| | | code: 412, title: Precondition Failed |
| | | """ |
| | | code = 412 |
| | |
| | | This indicates that the server is refusing to service the request |
| | | because the Request-URI is longer than the server is willing to |
| | | interpret. |
| | | |
| | | |
| | | code: 414, title: Request-URI Too Long |
| | | """ |
| | | code = 414 |
| | |
| | | This indicates that the server is refusing to service the request |
| | | because the entity of the request is in a format not supported by |
| | | the requested resource for the requested method. |
| | | |
| | | |
| | | code: 415, title: Unsupported Media Type |
| | | """ |
| | | # differences from webob.exc.HTTPUnsupportedMediaType: |
| | |
| | | range-specifier values in this field overlap the current extent |
| | | of the selected resource, and the request did not include an |
| | | If-Range request-header field. |
| | | |
| | | |
| | | code: 416, title: Request Range Not Satisfiable |
| | | """ |
| | | code = 416 |
| | |
| | | |
| | | This indidcates that the expectation given in an Expect |
| | | request-header field could not be met by this server. |
| | | |
| | | |
| | | code: 417, title: Expectation Failed |
| | | """ |
| | | code = 417 |
| | |
| | | subclass of :class:`~HTTPClientError` |
| | | |
| | | This indicates that the server is unable to process the contained |
| | | instructions. |
| | | instructions. |
| | | |
| | | May be used to notify the client that their JSON/XML is well formed, but |
| | | not correct for the current request. |
| | | |
| | | See RFC4918 section 11 for more information. |
| | | |
| | | |
| | | code: 422, title: Unprocessable Entity |
| | | """ |
| | | ## Note: from WebDAV |
| | |
| | | subclass of :class:`~HTTPClientError` |
| | | |
| | | This indicates that the resource is locked. |
| | | |
| | | |
| | | code: 423, title: Locked |
| | | """ |
| | | ## Note: from WebDAV |
| | |
| | | |
| | | This indicates that the method could not be performed because the |
| | | requested action depended on another action and that action failed. |
| | | |
| | | |
| | | code: 424, title: Failed Dependency |
| | | """ |
| | | ## Note: from WebDAV |
| | |
| | | |
| | | This indicates that the server does not support the functionality |
| | | required to fulfill the request. |
| | | |
| | | |
| | | code: 501, title: Not Implemented |
| | | """ |
| | | # differences from webob.exc.HTTPNotAcceptable: |
| | |
| | | This indicates that the server, while acting as a gateway or proxy, |
| | | received an invalid response from the upstream server it accessed |
| | | in attempting to fulfill the request. |
| | | |
| | | |
| | | code: 502, title: Bad Gateway |
| | | """ |
| | | code = 502 |
| | |
| | | |
| | | This indicates that the server is currently unable to handle the |
| | | request due to a temporary overloading or maintenance of the server. |
| | | |
| | | |
| | | code: 503, title: Service Unavailable |
| | | """ |
| | | code = 503 |
| | |
| | | |
| | | This indicates that the server does not have enough space to save |
| | | the resource. |
| | | |
| | | |
| | | code: 507, title: Insufficient Storage |
| | | """ |
| | | code = 507 |
| | |
| | | context = request.exception or context |
| | | return context # assumed to be an IResponse |
| | | |
| | | status_map={} |
| | | status_map = {} |
| | | code = None |
| | | for name, value in list(globals().items()): |
| | | if (isinstance(value, class_types) and |
| | |
| | | TranslationStringFactory, # API |
| | | ) |
| | | |
| | | TranslationString = TranslationString # PyFlakes |
| | | TranslationStringFactory = TranslationStringFactory # PyFlakes |
| | | |
| | | from pyramid.compat import PY3 |
| | | from pyramid.decorator import reify |
| | | |
| | |
| | | |
| | | from pyramid.threadlocal import get_current_registry |
| | | |
| | | TranslationString = TranslationString # PyFlakes |
| | | TranslationStringFactory = TranslationStringFactory # PyFlakes |
| | | |
| | | |
| | | class Localizer(object): |
| | | """ |
| | | An object providing translation and pluralizations related to |
| | |
| | | """Gets and sets and deletes the Content-MD5 header. For more |
| | | information on Content-MD5 see RFC 2616 section 14.14.""") |
| | | |
| | | content_range = Attribute( |
| | | content_range = Attribute( |
| | | """Gets and sets and deletes the Content-Range header. For more |
| | | information on Content-Range see section 14.16. Converts using |
| | | ContentRange object.""") |
| | |
| | | |
| | | def caller_path(path, level=2): |
| | | if not os.path.isabs(path): |
| | | module = caller_module(level+1) |
| | | module = caller_module(level + 1) |
| | | prefix = package_path(module) |
| | | path = os.path.join(prefix, path) |
| | | return path |
| | |
| | | |
| | | def caller_package(level=2, caller_module=caller_module): |
| | | # caller_module in arglist for tests |
| | | module = caller_module(level+1) |
| | | module = caller_module(level + 1) |
| | | f = getattr(module, '__file__', '') |
| | | if (('__init__.py' in f) or ('__init__$py' in f)): # empty at >>> |
| | | # Module is a package |
| | |
| | | values = category.values() |
| | | values = sorted(set(values), key=sort_key) |
| | | return [ |
| | | {'introspectable':intr, |
| | | 'related':self.related(intr)} |
| | | for intr in values |
| | | ] |
| | | {'introspectable': intr, |
| | | 'related': self.related(intr)} |
| | | for intr in values |
| | | ] |
| | | |
| | | def categorized(self, sort_key=None): |
| | | L = [] |
| | |
| | | |
| | | from pyramid.decorator import reify |
| | | from pyramid.i18n import LocalizerRequestMixin |
| | | from pyramid.response import Response, _get_response_factory |
| | | from pyramid.response import Response, _get_response_factory |
| | | from pyramid.security import ( |
| | | AuthenticationAPIMixin, |
| | | AuthorizationAPIMixin, |
| | |
| | | called if an exception happens in application code, or if the |
| | | response object returned by :term:`view` code is invalid. |
| | | |
| | | All response callbacks are called *after* the tweens and |
| | | All response callbacks are called *after* the tweens and |
| | | *before* the :class:`pyramid.events.NewResponse` event is sent. |
| | | |
| | | Errors raised by callbacks are not handled specially. They |
| | |
| | | def json_body(self): |
| | | return json.loads(text_(self.body, self.charset)) |
| | | |
| | | |
| | | |
| | | def route_request_iface(name, bases=()): |
| | | # zope.interface treats the __name__ as the __doc__ and changes __name__ |
| | | # to None for interfaces that contain spaces if you do not pass a |
| | |
| | | iface.combined = InterfaceClass( |
| | | '%s_combined_IRequest' % name, |
| | | bases=(iface, IRequest), |
| | | __doc__ = 'route_request_iface-generated combined interface') |
| | | __doc__='route_request_iface-generated combined interface') |
| | | return iface |
| | | |
| | | |
| | | def add_global_response_headers(request, headerlist): |
| | | def add_headers(request, response): |
| | | for k, v in headerlist: |
| | |
| | | |
| | | fsenc = sys.getfilesystemencoding() |
| | | |
| | | |
| | | class SkipTemplate(Exception): |
| | | """ |
| | | Raised to indicate that the template should not be copied over. |
| | |
| | | names = sorted(pkg_resources.resource_listdir(source[0], source[1])) |
| | | else: |
| | | names = sorted(os.listdir(source)) |
| | | pad = ' '*(indent*2) |
| | | pad = ' ' * (indent * 2) |
| | | if not os.path.exists(dest): |
| | | if verbosity >= 1: |
| | | out('%sCreating %s/' % (pad, dest)) |
| | |
| | | if verbosity: |
| | | out('%sRecursing into %s' % (pad, os.path.basename(full))) |
| | | copy_dir((source[0], full), dest_full, vars, verbosity, simulate, |
| | | indent=indent+1, sub_vars=sub_vars, |
| | | indent=indent + 1, sub_vars=sub_vars, |
| | | interactive=interactive, overwrite=overwrite, |
| | | template_renderer=template_renderer, out_=out_) |
| | | continue |
| | |
| | | if verbosity: |
| | | out('%sRecursing into %s' % (pad, os.path.basename(full))) |
| | | copy_dir(full, dest_full, vars, verbosity, simulate, |
| | | indent=indent+1, sub_vars=sub_vars, |
| | | indent=indent + 1, sub_vars=sub_vars, |
| | | interactive=interactive, overwrite=overwrite, |
| | | template_renderer=template_renderer, out_=out_) |
| | | continue |
| | |
| | | src_content.splitlines(), |
| | | dest_fn, src_fn)) |
| | | added = len([l for l in u_diff if l.startswith('+') |
| | | and not l.startswith('+++')]) |
| | | and not l.startswith('+++')]) |
| | | removed = len([l for l in u_diff if l.startswith('-') |
| | | and not l.startswith('---')]) |
| | | if added > removed: |
| | | msg = '; %i lines added' % (added-removed) |
| | | msg = '; %i lines added' % (added - removed) |
| | | elif removed > added: |
| | | msg = '; %i lines removed' % (removed-added) |
| | | msg = '; %i lines removed' % (removed - added) |
| | | else: |
| | | msg = '' |
| | | out('Replace %i bytes with %i bytes (%i/%i lines changed%s)' % ( |
| | |
| | | try: |
| | | import httplib |
| | | except ImportError: # pragma: no cover |
| | | import http.client as httplib #py3 |
| | | import http.client as httplib # py3 |
| | | |
| | | |
| | | class TemplateTest(object): |
| | | def make_venv(self, directory): # pragma: no cover |
| | |
| | | site_packages=False, |
| | | clear=False, |
| | | unzip_setuptools=True) |
| | | |
| | | def install(self, tmpl_name): # pragma: no cover |
| | | try: |
| | | self.old_cwd = os.getcwd() |
| | |
| | | if hastoolbar: |
| | | assert toolbarchunk in data, ininame |
| | | else: |
| | | assert not toolbarchunk in data, ininame |
| | | assert toolbarchunk not in data, ininame |
| | | finally: |
| | | proc.terminate() |
| | | finally: |
| | |
| | | |
| | | |
| | | def appmaker(zodb_root): |
| | | if not 'app_root' in zodb_root: |
| | | if 'app_root' not in zodb_root: |
| | | app_root = MyModel() |
| | | zodb_root['app_root'] = app_root |
| | | import transaction |
| | |
| | | for scaffold in scaffolds: |
| | | self.out(' %s:%s %s' % ( |
| | | scaffold.name, |
| | | ' '*(max_name-len(scaffold.name)), scaffold.summary)) |
| | | ' ' * (max_name - len(scaffold.name)), scaffold.summary)) |
| | | else: |
| | | self.out('No scaffolds available') |
| | | return 0 |
| | |
| | | parser.add_option( |
| | | '-n', '--app-name', |
| | | dest='app_name', |
| | | metavar= 'NAME', |
| | | help="Load the named application from the config file (default 'main')", |
| | | metavar='NAME', |
| | | help=( |
| | | "Load the named application from the config file (default 'main')" |
| | | ), |
| | | type="string", |
| | | ) |
| | | parser.add_option( |
| | |
| | | metavar='NAME:VALUE', |
| | | type='string', |
| | | action='append', |
| | | help="Header to add to request (you can use this option multiple times)" |
| | | ) |
| | | help=( |
| | | "Header to add to request (you can use this option multiple times)" |
| | | ), |
| | | ) |
| | | parser.add_option( |
| | | '-d', '--display-headers', |
| | | dest='display_headers', |
| | |
| | | if name.lower() == 'content-type': |
| | | name = 'CONTENT_TYPE' |
| | | else: |
| | | name = 'HTTP_'+name.upper().replace('-', '_') |
| | | name = 'HTTP_' + name.upper().replace('-', '_') |
| | | environ[name] = value |
| | | |
| | | request = Request.blank(path, environ=environ) |
| | |
| | | default=default_verbosity, |
| | | dest='verbose', |
| | | action='count', |
| | | help="Set verbose level (default "+str(default_verbosity)+")") |
| | | help="Set verbose level (default " + str(default_verbosity) + ")") |
| | | parser.add_option( |
| | | '-q', '--quiet', |
| | | action='store_const', |
| | |
| | | def change_user_group(self, user, group): # pragma: no cover |
| | | if not user and not group: |
| | | return |
| | | import pwd, grp |
| | | import pwd |
| | | import grp |
| | | |
| | | uid = gid = None |
| | | if group: |
| | | try: |
| | |
| | | os.setgid(gid) |
| | | if uid: |
| | | os.setuid(uid) |
| | | |
| | | |
| | | class LazyWriter(object): |
| | | |
| | |
| | | self.type = type |
| | | |
| | | def __call__(self, *args, **kw): |
| | | assert not 'self' in kw and not 'cls' in kw, ( |
| | | assert 'self' not in kw and 'cls' not in kw, ( |
| | | "You cannot use 'self' or 'cls' arguments to a " |
| | | "classinstancemethod") |
| | | return self.func(*((self.obj, self.type) + args), **kw) |
| | | |
| | | |
| | | class Monitor(object): # pragma: no cover |
| | | """ |
| | |
| | | continue |
| | | if filename.endswith('.pyc') and os.path.exists(filename[:-1]): |
| | | mtime = max(os.stat(filename[:-1]).st_mtime, mtime) |
| | | if not filename in self.module_mtimes: |
| | | if filename not in self.module_mtimes: |
| | | self.module_mtimes[filename] = mtime |
| | | elif self.module_mtimes[filename] < mtime: |
| | | print("%s changed; reloading..." % filename) |
| | |
| | | |
| | | def _get_tweens(self, registry): |
| | | from pyramid.config import Configurator |
| | | config = Configurator(registry = registry) |
| | | config = Configurator(registry=registry) |
| | | return config.registry.queryUtility(ITweens) |
| | | |
| | | def out(self, msg): # pragma: no cover |
| | |
| | | def show_chain(self, chain): |
| | | fmt = '%-10s %-65s' |
| | | self.out(fmt % ('Position', 'Name')) |
| | | self.out(fmt % ('-'*len('Position'), '-'*len('Name'))) |
| | | self.out(fmt % ('-' * len('Position'), '-' * len('Name'))) |
| | | self.out(fmt % ('-', INGRESS)) |
| | | for pos, (name, _) in enumerate(chain): |
| | | self.out(fmt % (pos, name)) |
| | |
| | | if traverser is None: |
| | | traverser = ResourceTreeTraverser(root) |
| | | tdict = traverser(request) |
| | | context, view_name, subpath, traversed, vroot, vroot_path =( |
| | | tdict['context'], tdict['view_name'], tdict['subpath'], |
| | | tdict['traversed'], tdict['virtual_root'], |
| | | tdict['virtual_root_path']) |
| | | context, view_name = (tdict['context'], tdict['view_name']) |
| | | |
| | | attrs.update(tdict) |
| | | |
| | | # find a view callable |
| | |
| | | if not IMultiView.providedBy(view_wrapper): |
| | | # single view for this route, so repeat call without route data |
| | | del request_attrs['matched_route'] |
| | | self.output_view_info(view_wrapper, level+1) |
| | | self.output_view_info(view_wrapper, level + 1) |
| | | else: |
| | | self.out("%sView:" % indent) |
| | | self.out("%s-----" % indent) |
| | |
| | | raise HTTPNotFound('Out of bounds: %s' % request.url) |
| | | |
| | | if self.package_name: # package resource |
| | | |
| | | resource_path ='%s/%s' % (self.docroot.rstrip('/'), path) |
| | | resource_path = '%s/%s' % (self.docroot.rstrip('/'), path) |
| | | if resource_isdir(self.package_name, resource_path): |
| | | if not request.path_url.endswith('/'): |
| | | self.add_slash_redirect(request) |
| | | resource_path = '%s/%s' % (resource_path.rstrip('/'),self.index) |
| | | resource_path = '%s/%s' % ( |
| | | resource_path.rstrip('/'), self.index |
| | | ) |
| | | |
| | | if not resource_exists(self.package_name, resource_path): |
| | | raise HTTPNotFound(request.url) |
| | | filepath = resource_filename(self.package_name, resource_path) |
| | |
| | | from pyramid.config import Configurator |
| | | from pyramid.decorator import reify |
| | | from pyramid.path import caller_package |
| | | from pyramid.response import Response, _get_response_factory |
| | | from pyramid.response import _get_response_factory |
| | | from pyramid.registry import Registry |
| | | |
| | | from pyramid.security import ( |
| | |
| | | if myval != v: |
| | | raise AssertionError( |
| | | '\nasserted value for %s: %r\nactual value: %r' % ( |
| | | k, v, myval)) |
| | | k, v, myval)) |
| | | return True |
| | | |
| | | |
| | | class DummyResource: |
| | | """ A dummy :app:`Pyramid` :term:`resource` object.""" |
| | |
| | | |
| | | @reify |
| | | def response(self): |
| | | f = _get_response_factory(self.registry) |
| | | f = _get_response_factory(self.registry) |
| | | return f(self) |
| | | |
| | | have_zca = True |
| | | |
| | | |
| | | def setUp(registry=None, request=None, hook_zca=True, autocommit=True, |
| | | settings=None, package=None): |
| | |
| | | skip = True |
| | | if platform == 'py3' and PY3: |
| | | skip = True |
| | | |
| | | def decorator(func): |
| | | if isinstance(func, class_types): |
| | | if skip: return None |
| | | else: return func |
| | | if skip: |
| | | return None |
| | | else: |
| | | return func |
| | | else: |
| | | def wrapper(*args, **kw): |
| | | if skip: |
| | |
| | | VH_ROOT_KEY, |
| | | ) |
| | | |
| | | with warnings.catch_warnings(): |
| | | warnings.filterwarnings('ignore') |
| | | from pyramid.interfaces import IContextURL |
| | | |
| | | from pyramid.compat import ( |
| | | PY3, |
| | | native_, |
| | |
| | | from pyramid.exceptions import URLDecodeError |
| | | from pyramid.location import lineage |
| | | from pyramid.threadlocal import get_current_registry |
| | | |
| | | with warnings.catch_warnings(): |
| | | warnings.filterwarnings('ignore') |
| | | from pyramid.interfaces import IContextURL |
| | | |
| | | empty = text_('') |
| | | |
| | |
| | | |
| | | if VH_ROOT_KEY in environ: |
| | | # HTTP_X_VHM_ROOT |
| | | vroot_path = decode_path_info(environ[VH_ROOT_KEY]) |
| | | vroot_path = decode_path_info(environ[VH_ROOT_KEY]) |
| | | vroot_tuple = split_path_info(vroot_path) |
| | | vpath = vroot_path + path # both will (must) be unicode or asciistr |
| | | vroot_idx = len(vroot_tuple) -1 |
| | | vroot_idx = len(vroot_tuple) - 1 |
| | | else: |
| | | vroot_tuple = () |
| | | vpath = path |
| | |
| | | vpath_tuple = split_path_info(vpath) |
| | | for segment in vpath_tuple: |
| | | if segment[:2] == view_selector: |
| | | return {'context':ob, |
| | | 'view_name':segment[2:], |
| | | 'subpath':vpath_tuple[i+1:], |
| | | 'traversed':vpath_tuple[:vroot_idx+i+1], |
| | | 'virtual_root':vroot, |
| | | 'virtual_root_path':vroot_tuple, |
| | | 'root':root} |
| | | return {'context': ob, |
| | | 'view_name': segment[2:], |
| | | 'subpath': vpath_tuple[i + 1:], |
| | | 'traversed': vpath_tuple[:vroot_idx + i + 1], |
| | | 'virtual_root': vroot, |
| | | 'virtual_root_path': vroot_tuple, |
| | | 'root': root} |
| | | try: |
| | | getitem = ob.__getitem__ |
| | | except AttributeError: |
| | | return {'context':ob, |
| | | 'view_name':segment, |
| | | 'subpath':vpath_tuple[i+1:], |
| | | 'traversed':vpath_tuple[:vroot_idx+i+1], |
| | | 'virtual_root':vroot, |
| | | 'virtual_root_path':vroot_tuple, |
| | | 'root':root} |
| | | return {'context': ob, |
| | | 'view_name': segment, |
| | | 'subpath': vpath_tuple[i + 1:], |
| | | 'traversed': vpath_tuple[:vroot_idx + i + 1], |
| | | 'virtual_root': vroot, |
| | | 'virtual_root_path': vroot_tuple, |
| | | 'root': root} |
| | | |
| | | try: |
| | | next = getitem(segment) |
| | | except KeyError: |
| | | return {'context':ob, |
| | | 'view_name':segment, |
| | | 'subpath':vpath_tuple[i+1:], |
| | | 'traversed':vpath_tuple[:vroot_idx+i+1], |
| | | 'virtual_root':vroot, |
| | | 'virtual_root_path':vroot_tuple, |
| | | 'root':root} |
| | | return {'context': ob, |
| | | 'view_name': segment, |
| | | 'subpath': vpath_tuple[i + 1:], |
| | | 'traversed': vpath_tuple[:vroot_idx + i + 1], |
| | | 'virtual_root': vroot, |
| | | 'virtual_root_path': vroot_tuple, |
| | | 'root': root} |
| | | if i == vroot_idx: |
| | | vroot = next |
| | | ob = next |
| | |
| | | if local_url is not None: |
| | | # the resource handles its own url generation |
| | | d = dict( |
| | | virtual_path = virtual_path, |
| | | physical_path = url_adapter.physical_path, |
| | | app_url = app_url, |
| | | ) |
| | | virtual_path=virtual_path, |
| | | physical_path=url_adapter.physical_path, |
| | | app_url=app_url, |
| | | ) |
| | | |
| | | # allow __resource_url__ to punt by returning None |
| | | resource_url = local_url(self, d) |
| | | |
| | |
| | | |
| | | """ |
| | | if not os.path.isabs(path): |
| | | if not ':' in path: |
| | | if ':' not in path: |
| | | # if it's not a package:relative/name and it's not an |
| | | # /absolute/path it's a relative/path; this means its relative |
| | | # to the package in which the caller's module is defined. |
| | |
| | | to ``static_path`` will be ignored. |
| | | """ |
| | | if not os.path.isabs(path): |
| | | if not ':' in path: |
| | | if ':' not in path: |
| | | # if it's not a package:relative/name and it's not an |
| | | # /absolute/path it's a relative/path; this means its relative |
| | | # to the package in which the caller's module is defined. |
| | |
| | | |
| | | model_url = resource_url # b/w compat (forever) |
| | | |
| | | |
| | | def static_url(path, request, **kw): |
| | | """ |
| | | This is a backwards compatibility function. Its result is the same as |
| | |
| | | See :meth:`pyramid.request.Request.static_url` for more information. |
| | | """ |
| | | if not os.path.isabs(path): |
| | | if not ':' in path: |
| | | if ':' not in path: |
| | | # if it's not a package:relative/name and it's not an |
| | | # /absolute/path it's a relative/path; this means its relative |
| | | # to the package in which the caller's module is defined. |
| | | package = caller_package() |
| | | path = '%s:%s' % (package.__name__, path) |
| | | return request.static_url(path, **kw) |
| | | |
| | | |
| | | def static_path(path, request, **kw): |
| | | """ |
| | |
| | | See :meth:`pyramid.request.Request.static_path` for more information. |
| | | """ |
| | | if not os.path.isabs(path): |
| | | if not ':' in path: |
| | | if ':' not in path: |
| | | # if it's not a package:relative/name and it's not an |
| | | # /absolute/path it's a relative/path; this means its relative |
| | | # to the package in which the caller's module is defined. |
| | |
| | | order.append((a, b)) |
| | | |
| | | def add_node(node): |
| | | if not node in graph: |
| | | if node not in graph: |
| | | roots.append(node) |
| | | graph[node] = [0] # 0 = number of arcs coming into this node |
| | | |
| | |
| | | view = self.maybe_dotted(view) |
| | | if inspect.isclass(view): |
| | | defaults = getattr(view, '__view_defaults__', {}).copy() |
| | | if not '_backframes' in kw: |
| | | if '_backframes' not in kw: |
| | | kw['_backframes'] = 1 # for action_method |
| | | defaults.update(kw) |
| | | return wrapped(self, *arg, **defaults) |
| | |
| | | qs = request.query_string |
| | | if qs: |
| | | qs = '?' + qs |
| | | return HTTPFound(location=request.path+'/'+qs) |
| | | return HTTPFound(location=request.path + '/' + qs) |
| | | return self.notfound_view(context, request) |
| | | |
| | | append_slash_notfound_view = AppendSlashNotFoundViewFactory() |
| | |
| | | [bdist_wheel] |
| | | universal = 1 |
| | | |
| | | [flake8] |
| | | ignore = E301,E302,E731,E261,E123,E121,E128,E129,E125,W291,E501,W293,E303,W391,E266,E231,E201,E202,E127,E262 |
| | | exclude = pyramid/tests/,pyramid/compat.py,pyramid/resource.py |
| | | show-source = True |
| | |
| | | deps = |
| | | nosexcover |
| | | |
| | | [testenv:pep8] |
| | | commands = |
| | | flake8 pyramid/ |
| | | deps = |
| | | flake8 |
| | | |
| | | # we separate coverage into its own testenv because a) "last run wins" wrt |
| | | # cobertura jenkins reporting and b) pypy and jython can't handle any |
| | | # combination of versions of coverage and nosexcover that i can find. |