nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
NullResource.HEAD
(self, REQUEST, RESPONSE)
Retrieve resource information without a response message body.
Retrieve resource information without a response message body.
[ "Retrieve", "resource", "information", "without", "a", "response", "message", "body", "." ]
def HEAD(self, REQUEST, RESPONSE): """Retrieve resource information without a response message body.""" self.dav__init(REQUEST, RESPONSE) RESPONSE.setBody('', lock=True) raise NotFound('The requested resource does not exist.')
[ "def", "HEAD", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "RESPONSE", ".", "setBody", "(", "''", ",", "lock", "=", "True", ")", "raise", "NotFound", "(", "'The requested resource does not exist.'", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L90-L94
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
NullResource.PUT
(self, REQUEST, RESPONSE)
return RESPONSE
Create a new non-collection resource.
Create a new non-collection resource.
[ "Create", "a", "new", "non", "-", "collection", "resource", "." ]
def PUT(self, REQUEST, RESPONSE): """Create a new non-collection resource. """ self.dav__init(REQUEST, RESPONSE) name = self.__name__ parent = self.__parent__ ifhdr = REQUEST.get_header('If', '') if IWriteLock.providedBy(parent) and parent.wl_isLocked(): if ifhdr: parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1) else: # There was no If header at all, and our parent is locked, # so we fail here raise Locked elif ifhdr: # There was an If header, but the parent is not locked raise PreconditionFailed # SDS: Only use BODY if the file size is smaller than # LARGE_FILE_THRESHOLD, otherwise read # LARGE_FILE_THRESHOLD bytes from the file # which should be enough to trigger # content_type detection, and possibly enough for CMF's # content_type_registry too. # # Note that body here is really just used for detecting the # content type and figuring out the correct factory. The correct # file content will be uploaded on ob.PUT(REQUEST, RESPONSE) after # the object has been created. # # A problem I could see is content_type_registry predicates # that do depend on the whole file being passed here as an # argument. There's none by default that does this though. If # they really do want to look at the file, they should use # REQUEST['BODYFILE'] directly and try as much as possible not # to read the whole file into memory. if int(REQUEST.get('CONTENT_LENGTH') or 0) > LARGE_FILE_THRESHOLD: file = REQUEST['BODYFILE'] body = file.read(LARGE_FILE_THRESHOLD) if not isinstance(body, bytes): body = body.encode('UTF-8') file.seek(0) else: body = REQUEST.get('BODY', b'') typ = REQUEST.get_header('content-type', None) if typ is None: typ, enc = guess_content_type(name, body) factory = getattr(parent, 'PUT_factory', self._default_PUT_factory) ob = factory(name, typ, body) if ob is None: ob = self._default_PUT_factory(name, typ, body) # We call _verifyObjectPaste with verify_src=0, to see if the # user can create this type of object (and we don't need to # check the clipboard. try: parent._verifyObjectPaste(ob.__of__(parent), 0) except CopyError: sMsg = 'Unable to create object of class %s in %s: %s' % \ (ob.__class__, repr(parent), sys.exc_info()[1],) raise Unauthorized(sMsg) # Delegate actual PUT handling to the new object, # SDS: But just *after* it has been stored. self.__parent__._setObject(name, ob) ob = self.__parent__._getOb(name) ob.PUT(REQUEST, RESPONSE) RESPONSE.setStatus(201) RESPONSE.setBody('') return RESPONSE
[ "def", "PUT", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "name", "=", "self", ".", "__name__", "parent", "=", "self", ".", "__parent__", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "if", "IWriteLock", ".", "providedBy", "(", "parent", ")", "and", "parent", ".", "wl_isLocked", "(", ")", ":", "if", "ifhdr", ":", "parent", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "col", "=", "1", ")", "else", ":", "# There was no If header at all, and our parent is locked,", "# so we fail here", "raise", "Locked", "elif", "ifhdr", ":", "# There was an If header, but the parent is not locked", "raise", "PreconditionFailed", "# SDS: Only use BODY if the file size is smaller than", "# LARGE_FILE_THRESHOLD, otherwise read", "# LARGE_FILE_THRESHOLD bytes from the file", "# which should be enough to trigger", "# content_type detection, and possibly enough for CMF's", "# content_type_registry too.", "#", "# Note that body here is really just used for detecting the", "# content type and figuring out the correct factory. The correct", "# file content will be uploaded on ob.PUT(REQUEST, RESPONSE) after", "# the object has been created.", "#", "# A problem I could see is content_type_registry predicates", "# that do depend on the whole file being passed here as an", "# argument. There's none by default that does this though. If", "# they really do want to look at the file, they should use", "# REQUEST['BODYFILE'] directly and try as much as possible not", "# to read the whole file into memory.", "if", "int", "(", "REQUEST", ".", "get", "(", "'CONTENT_LENGTH'", ")", "or", "0", ")", ">", "LARGE_FILE_THRESHOLD", ":", "file", "=", "REQUEST", "[", "'BODYFILE'", "]", "body", "=", "file", ".", "read", "(", "LARGE_FILE_THRESHOLD", ")", "if", "not", "isinstance", "(", "body", ",", "bytes", ")", ":", "body", "=", "body", ".", "encode", "(", "'UTF-8'", ")", "file", ".", "seek", "(", "0", ")", "else", ":", "body", "=", "REQUEST", ".", "get", "(", "'BODY'", ",", "b''", ")", "typ", "=", "REQUEST", ".", "get_header", "(", "'content-type'", ",", "None", ")", "if", "typ", "is", "None", ":", "typ", ",", "enc", "=", "guess_content_type", "(", "name", ",", "body", ")", "factory", "=", "getattr", "(", "parent", ",", "'PUT_factory'", ",", "self", ".", "_default_PUT_factory", ")", "ob", "=", "factory", "(", "name", ",", "typ", ",", "body", ")", "if", "ob", "is", "None", ":", "ob", "=", "self", ".", "_default_PUT_factory", "(", "name", ",", "typ", ",", "body", ")", "# We call _verifyObjectPaste with verify_src=0, to see if the", "# user can create this type of object (and we don't need to", "# check the clipboard.", "try", ":", "parent", ".", "_verifyObjectPaste", "(", "ob", ".", "__of__", "(", "parent", ")", ",", "0", ")", "except", "CopyError", ":", "sMsg", "=", "'Unable to create object of class %s in %s: %s'", "%", "(", "ob", ".", "__class__", ",", "repr", "(", "parent", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ",", ")", "raise", "Unauthorized", "(", "sMsg", ")", "# Delegate actual PUT handling to the new object,", "# SDS: But just *after* it has been stored.", "self", ".", "__parent__", ".", "_setObject", "(", "name", ",", "ob", ")", "ob", "=", "self", ".", "__parent__", ".", "_getOb", "(", "name", ")", "ob", ".", "PUT", "(", "REQUEST", ",", "RESPONSE", ")", "RESPONSE", ".", "setStatus", "(", "201", ")", "RESPONSE", ".", "setBody", "(", "''", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L120-L195
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
NullResource.MKCOL
(self, REQUEST, RESPONSE)
return RESPONSE
Create a new collection resource.
Create a new collection resource.
[ "Create", "a", "new", "collection", "resource", "." ]
def MKCOL(self, REQUEST, RESPONSE): """Create a new collection resource.""" self.dav__init(REQUEST, RESPONSE) if REQUEST.get('BODY', ''): raise UnsupportedMediaType('Unknown request body.') name = self.__name__ parent = self.__parent__ if hasattr(aq_base(parent), name): raise MethodNotAllowed('The name %s is in use.' % name) if not isDavCollection(parent): raise Forbidden('Cannot create collection at this location.') ifhdr = REQUEST.get_header('If', '') if IWriteLock.providedBy(parent) and parent.wl_isLocked(): if ifhdr: parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1) else: raise Locked elif ifhdr: # There was an If header, but the parent is not locked raise PreconditionFailed # Add hook for webdav MKCOL (Collector #2254) (needed for CMF) mkcol_handler = getattr(parent, 'MKCOL_handler', parent.manage_addFolder) mkcol_handler(name) RESPONSE.setStatus(201) RESPONSE.setBody('') return RESPONSE
[ "def", "MKCOL", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "if", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", ":", "raise", "UnsupportedMediaType", "(", "'Unknown request body.'", ")", "name", "=", "self", ".", "__name__", "parent", "=", "self", ".", "__parent__", "if", "hasattr", "(", "aq_base", "(", "parent", ")", ",", "name", ")", ":", "raise", "MethodNotAllowed", "(", "'The name %s is in use.'", "%", "name", ")", "if", "not", "isDavCollection", "(", "parent", ")", ":", "raise", "Forbidden", "(", "'Cannot create collection at this location.'", ")", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "if", "IWriteLock", ".", "providedBy", "(", "parent", ")", "and", "parent", ".", "wl_isLocked", "(", ")", ":", "if", "ifhdr", ":", "parent", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "col", "=", "1", ")", "else", ":", "raise", "Locked", "elif", "ifhdr", ":", "# There was an If header, but the parent is not locked", "raise", "PreconditionFailed", "# Add hook for webdav MKCOL (Collector #2254) (needed for CMF)", "mkcol_handler", "=", "getattr", "(", "parent", ",", "'MKCOL_handler'", ",", "parent", ".", "manage_addFolder", ")", "mkcol_handler", "(", "name", ")", "RESPONSE", ".", "setStatus", "(", "201", ")", "RESPONSE", ".", "setBody", "(", "''", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L198-L229
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
NullResource.LOCK
(self, REQUEST, RESPONSE)
LOCK on a Null Resource makes a LockNullResource instance
LOCK on a Null Resource makes a LockNullResource instance
[ "LOCK", "on", "a", "Null", "Resource", "makes", "a", "LockNullResource", "instance" ]
def LOCK(self, REQUEST, RESPONSE): """ LOCK on a Null Resource makes a LockNullResource instance """ self.dav__init(REQUEST, RESPONSE) security = getSecurityManager() creator = security.getUser() body = REQUEST.get('BODY', '') ifhdr = REQUEST.get_header('If', '') depth = REQUEST.get_header('Depth', 'infinity') name = self.__name__ parent = self.__parent__ if isinstance(parent, NullResource): # Can happen if someone specified a bad path to # the object. Missing path elements may be created # as NullResources. Give up in this case. raise BadRequest('Parent %s does not exist' % parent.__name__) if IWriteLock.providedBy(parent) and parent.wl_isLocked(): if ifhdr: parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1) else: raise Locked if not body: # No body means refresh lock, which makes no sense on # a null resource. But if the parent is locked it can be # interpreted as an indirect refresh lock for the parent. return parent.LOCK(REQUEST, RESPONSE) elif ifhdr: # There was an If header, but the parent is not locked. raise PreconditionFailed # The logic involved in locking a null resource is simpler than # a regular resource, since we know we're not already locked, # and the lock isn't being refreshed. if not body: raise BadRequest('No body was in the request') locknull = LockNullResource(name) parent._setObject(name, locknull) locknull = parent._getOb(name) cmd = Lock(REQUEST) token, result = cmd.apply(locknull, creator, depth=depth) if result: # Return the multistatus result (there were multiple errors) # This *shouldn't* happen for locking a NullResource, but it's # inexpensive to handle and is good coverage for any future # changes in davcmds.Lock RESPONSE.setStatus(207) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setBody(result) else: # The command was succesful lock = locknull.wl_getLock(token) RESPONSE.setStatus(201) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setHeader('Lock-Token', 'opaquelocktoken:' + token) RESPONSE.setBody(lock.asXML())
[ "def", "LOCK", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "security", "=", "getSecurityManager", "(", ")", "creator", "=", "security", ".", "getUser", "(", ")", "body", "=", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "depth", "=", "REQUEST", ".", "get_header", "(", "'Depth'", ",", "'infinity'", ")", "name", "=", "self", ".", "__name__", "parent", "=", "self", ".", "__parent__", "if", "isinstance", "(", "parent", ",", "NullResource", ")", ":", "# Can happen if someone specified a bad path to", "# the object. Missing path elements may be created", "# as NullResources. Give up in this case.", "raise", "BadRequest", "(", "'Parent %s does not exist'", "%", "parent", ".", "__name__", ")", "if", "IWriteLock", ".", "providedBy", "(", "parent", ")", "and", "parent", ".", "wl_isLocked", "(", ")", ":", "if", "ifhdr", ":", "parent", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "col", "=", "1", ")", "else", ":", "raise", "Locked", "if", "not", "body", ":", "# No body means refresh lock, which makes no sense on", "# a null resource. But if the parent is locked it can be", "# interpreted as an indirect refresh lock for the parent.", "return", "parent", ".", "LOCK", "(", "REQUEST", ",", "RESPONSE", ")", "elif", "ifhdr", ":", "# There was an If header, but the parent is not locked.", "raise", "PreconditionFailed", "# The logic involved in locking a null resource is simpler than", "# a regular resource, since we know we're not already locked,", "# and the lock isn't being refreshed.", "if", "not", "body", ":", "raise", "BadRequest", "(", "'No body was in the request'", ")", "locknull", "=", "LockNullResource", "(", "name", ")", "parent", ".", "_setObject", "(", "name", ",", "locknull", ")", "locknull", "=", "parent", ".", "_getOb", "(", "name", ")", "cmd", "=", "Lock", "(", "REQUEST", ")", "token", ",", "result", "=", "cmd", ".", "apply", "(", "locknull", ",", "creator", ",", "depth", "=", "depth", ")", "if", "result", ":", "# Return the multistatus result (there were multiple errors)", "# This *shouldn't* happen for locking a NullResource, but it's", "# inexpensive to handle and is good coverage for any future", "# changes in davcmds.Lock", "RESPONSE", ".", "setStatus", "(", "207", ")", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/xml; charset=\"utf-8\"'", ")", "RESPONSE", ".", "setBody", "(", "result", ")", "else", ":", "# The command was succesful", "lock", "=", "locknull", ".", "wl_getLock", "(", "token", ")", "RESPONSE", ".", "setStatus", "(", "201", ")", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/xml; charset=\"utf-8\"'", ")", "RESPONSE", ".", "setHeader", "(", "'Lock-Token'", ",", "'opaquelocktoken:'", "+", "token", ")", "RESPONSE", ".", "setBody", "(", "lock", ".", "asXML", "(", ")", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L232-L290
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
LockNullResource.PROPFIND
(self, REQUEST, RESPONSE)
return Resource.PROPFIND(self, REQUEST, RESPONSE)
Retrieve properties defined on the resource.
Retrieve properties defined on the resource.
[ "Retrieve", "properties", "defined", "on", "the", "resource", "." ]
def PROPFIND(self, REQUEST, RESPONSE): """Retrieve properties defined on the resource.""" return Resource.PROPFIND(self, REQUEST, RESPONSE)
[ "def", "PROPFIND", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "return", "Resource", ".", "PROPFIND", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L333-L335
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
LockNullResource.LOCK
(self, REQUEST, RESPONSE)
return RESPONSE
A Lock command on a LockNull resource should only be a refresh request (one without a body)
A Lock command on a LockNull resource should only be a refresh request (one without a body)
[ "A", "Lock", "command", "on", "a", "LockNull", "resource", "should", "only", "be", "a", "refresh", "request", "(", "one", "without", "a", "body", ")" ]
def LOCK(self, REQUEST, RESPONSE): """ A Lock command on a LockNull resource should only be a refresh request (one without a body) """ self.dav__init(REQUEST, RESPONSE) body = REQUEST.get('BODY', '') ifhdr = REQUEST.get_header('If', '') if body: # If there's a body, then this is a full lock request # which conflicts with the fact that we're already locked RESPONSE.setStatus(423) else: # There's no body, so this is likely to be a refresh request if not ifhdr: raise PreconditionFailed taglist = IfParser(ifhdr) found = 0 for tag in taglist: for listitem in tag.list: token = tokenFinder(listitem) if token and self.wl_hasLock(token): lock = self.wl_getLock(token) timeout = REQUEST.get_header('Timeout', 'infinite') lock.setTimeout(timeout) # Automatically refreshes found = 1 RESPONSE.setStatus(200) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setBody(lock.asXML()) if found: break if not found: RESPONSE.setStatus(412) # Precondition failed return RESPONSE
[ "def", "LOCK", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "body", "=", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "if", "body", ":", "# If there's a body, then this is a full lock request", "# which conflicts with the fact that we're already locked", "RESPONSE", ".", "setStatus", "(", "423", ")", "else", ":", "# There's no body, so this is likely to be a refresh request", "if", "not", "ifhdr", ":", "raise", "PreconditionFailed", "taglist", "=", "IfParser", "(", "ifhdr", ")", "found", "=", "0", "for", "tag", "in", "taglist", ":", "for", "listitem", "in", "tag", ".", "list", ":", "token", "=", "tokenFinder", "(", "listitem", ")", "if", "token", "and", "self", ".", "wl_hasLock", "(", "token", ")", ":", "lock", "=", "self", ".", "wl_getLock", "(", "token", ")", "timeout", "=", "REQUEST", ".", "get_header", "(", "'Timeout'", ",", "'infinite'", ")", "lock", ".", "setTimeout", "(", "timeout", ")", "# Automatically refreshes", "found", "=", "1", "RESPONSE", ".", "setStatus", "(", "200", ")", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/xml; charset=\"utf-8\"'", ")", "RESPONSE", ".", "setBody", "(", "lock", ".", "asXML", "(", ")", ")", "if", "found", ":", "break", "if", "not", "found", ":", "RESPONSE", ".", "setStatus", "(", "412", ")", "# Precondition failed", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L338-L373
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
LockNullResource.UNLOCK
(self, REQUEST, RESPONSE)
return RESPONSE
Unlocking a Null Resource removes it from its parent
Unlocking a Null Resource removes it from its parent
[ "Unlocking", "a", "Null", "Resource", "removes", "it", "from", "its", "parent" ]
def UNLOCK(self, REQUEST, RESPONSE): """ Unlocking a Null Resource removes it from its parent """ self.dav__init(REQUEST, RESPONSE) token = REQUEST.get_header('Lock-Token', '') url = REQUEST['URL'] if token: token = tokenFinder(token) else: raise BadRequest('No lock token was submitted in the request') cmd = Unlock() result = cmd.apply(self, token, url) parent = aq_parent(self) parent._delObject(self.id) if result: RESPONSE.setStatus(207) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setBody(result) else: RESPONSE.setStatus(204) return RESPONSE
[ "def", "UNLOCK", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "token", "=", "REQUEST", ".", "get_header", "(", "'Lock-Token'", ",", "''", ")", "url", "=", "REQUEST", "[", "'URL'", "]", "if", "token", ":", "token", "=", "tokenFinder", "(", "token", ")", "else", ":", "raise", "BadRequest", "(", "'No lock token was submitted in the request'", ")", "cmd", "=", "Unlock", "(", ")", "result", "=", "cmd", ".", "apply", "(", "self", ",", "token", ",", "url", ")", "parent", "=", "aq_parent", "(", "self", ")", "parent", ".", "_delObject", "(", "self", ".", "id", ")", "if", "result", ":", "RESPONSE", ".", "setStatus", "(", "207", ")", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/xml; charset=\"utf-8\"'", ")", "RESPONSE", ".", "setBody", "(", "result", ")", "else", ":", "RESPONSE", ".", "setStatus", "(", "204", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L376-L398
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
LockNullResource.PUT
(self, REQUEST, RESPONSE)
return RESPONSE
Create a new non-collection resource, deleting the LockNull object from the container before putting the new object in.
Create a new non-collection resource, deleting the LockNull object from the container before putting the new object in.
[ "Create", "a", "new", "non", "-", "collection", "resource", "deleting", "the", "LockNull", "object", "from", "the", "container", "before", "putting", "the", "new", "object", "in", "." ]
def PUT(self, REQUEST, RESPONSE): """ Create a new non-collection resource, deleting the LockNull object from the container before putting the new object in. """ self.dav__init(REQUEST, RESPONSE) name = self.__name__ parent = self.aq_parent parenturl = parent.absolute_url() ifhdr = REQUEST.get_header('If', '') # Since a Lock null resource is always locked by definition, all # operations done by an owner of the lock that affect the resource # MUST have the If header in the request if not ifhdr: raise PreconditionFailed('No If-header') # First we need to see if the parent of the locknull is locked, and # if the user owns that lock (checked by handling the information in # the If header). if IWriteLock.providedBy(parent) and parent.wl_isLocked(): itrue = parent.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT', col=1, url=parenturl, refresh=1) if not itrue: raise PreconditionFailed( 'Condition failed against resources parent') # Now we need to check the If header against our own lock state itrue = self.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT', refresh=1) if not itrue: raise PreconditionFailed( 'Condition failed against locknull resource') # All of the If header tests succeeded, now we need to remove ourselves # from our parent. We need to transfer lock state to the new object. locks = self.wl_lockItems() parent._delObject(name) # Now we need to go through the regular operations of PUT body = REQUEST.get('BODY', '') typ = REQUEST.get_header('content-type', None) if typ is None: typ, enc = guess_content_type(name, body) factory = getattr(parent, 'PUT_factory', self._default_PUT_factory) ob = factory(name, typ, body) or self._default_PUT_factory(name, typ, body) # Verify that the user can create this type of object try: parent._verifyObjectPaste(ob.__of__(parent), 0) except Unauthorized: raise except Exception: raise Forbidden(sys.exc_info()[1]) # Put the locks on the new object if not IWriteLock.providedBy(ob): raise MethodNotAllowed( 'The target object type cannot be locked') for token, lock in locks: ob.wl_setLock(token, lock) # Delegate actual PUT handling to the new object. ob.PUT(REQUEST, RESPONSE) parent._setObject(name, ob) RESPONSE.setStatus(201) RESPONSE.setBody('') return RESPONSE
[ "def", "PUT", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "name", "=", "self", ".", "__name__", "parent", "=", "self", ".", "aq_parent", "parenturl", "=", "parent", ".", "absolute_url", "(", ")", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "# Since a Lock null resource is always locked by definition, all", "# operations done by an owner of the lock that affect the resource", "# MUST have the If header in the request", "if", "not", "ifhdr", ":", "raise", "PreconditionFailed", "(", "'No If-header'", ")", "# First we need to see if the parent of the locknull is locked, and", "# if the user owns that lock (checked by handling the information in", "# the If header).", "if", "IWriteLock", ".", "providedBy", "(", "parent", ")", "and", "parent", ".", "wl_isLocked", "(", ")", ":", "itrue", "=", "parent", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "'PUT'", ",", "col", "=", "1", ",", "url", "=", "parenturl", ",", "refresh", "=", "1", ")", "if", "not", "itrue", ":", "raise", "PreconditionFailed", "(", "'Condition failed against resources parent'", ")", "# Now we need to check the If header against our own lock state", "itrue", "=", "self", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "'PUT'", ",", "refresh", "=", "1", ")", "if", "not", "itrue", ":", "raise", "PreconditionFailed", "(", "'Condition failed against locknull resource'", ")", "# All of the If header tests succeeded, now we need to remove ourselves", "# from our parent. We need to transfer lock state to the new object.", "locks", "=", "self", ".", "wl_lockItems", "(", ")", "parent", ".", "_delObject", "(", "name", ")", "# Now we need to go through the regular operations of PUT", "body", "=", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", "typ", "=", "REQUEST", ".", "get_header", "(", "'content-type'", ",", "None", ")", "if", "typ", "is", "None", ":", "typ", ",", "enc", "=", "guess_content_type", "(", "name", ",", "body", ")", "factory", "=", "getattr", "(", "parent", ",", "'PUT_factory'", ",", "self", ".", "_default_PUT_factory", ")", "ob", "=", "factory", "(", "name", ",", "typ", ",", "body", ")", "or", "self", ".", "_default_PUT_factory", "(", "name", ",", "typ", ",", "body", ")", "# Verify that the user can create this type of object", "try", ":", "parent", ".", "_verifyObjectPaste", "(", "ob", ".", "__of__", "(", "parent", ")", ",", "0", ")", "except", "Unauthorized", ":", "raise", "except", "Exception", ":", "raise", "Forbidden", "(", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "# Put the locks on the new object", "if", "not", "IWriteLock", ".", "providedBy", "(", "ob", ")", ":", "raise", "MethodNotAllowed", "(", "'The target object type cannot be locked'", ")", "for", "token", ",", "lock", "in", "locks", ":", "ob", ".", "wl_setLock", "(", "token", ",", "lock", ")", "# Delegate actual PUT handling to the new object.", "ob", ".", "PUT", "(", "REQUEST", ",", "RESPONSE", ")", "parent", ".", "_setObject", "(", "name", ",", "ob", ")", "RESPONSE", ".", "setStatus", "(", "201", ")", "RESPONSE", ".", "setBody", "(", "''", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L401-L470
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/NullResource.py
python
LockNullResource.MKCOL
(self, REQUEST, RESPONSE)
return RESPONSE
Create a new Collection (folder) resource. Since this is being done on a LockNull resource, this also involves removing the LockNull object and transferring its locks to the newly created Folder
Create a new Collection (folder) resource. Since this is being done on a LockNull resource, this also involves removing the LockNull object and transferring its locks to the newly created Folder
[ "Create", "a", "new", "Collection", "(", "folder", ")", "resource", ".", "Since", "this", "is", "being", "done", "on", "a", "LockNull", "resource", "this", "also", "involves", "removing", "the", "LockNull", "object", "and", "transferring", "its", "locks", "to", "the", "newly", "created", "Folder" ]
def MKCOL(self, REQUEST, RESPONSE): """ Create a new Collection (folder) resource. Since this is being done on a LockNull resource, this also involves removing the LockNull object and transferring its locks to the newly created Folder """ self.dav__init(REQUEST, RESPONSE) if REQUEST.get('BODY', ''): raise UnsupportedMediaType('Unknown request body.') name = self.__name__ parent = self.aq_parent parenturl = parent.absolute_url() ifhdr = REQUEST.get_header('If', '') if not ifhdr: raise PreconditionFailed('No If-header') # If the parent object is locked, that information should be in the # if-header if the user owns a lock on the parent if IWriteLock.providedBy(parent) and parent.wl_isLocked(): itrue = parent.dav__simpleifhandler( REQUEST, RESPONSE, 'MKCOL', col=1, url=parenturl, refresh=1) if not itrue: raise PreconditionFailed( 'Condition failed against resources parent') # Now we need to check the If header against our own lock state itrue = self.dav__simpleifhandler( REQUEST, RESPONSE, 'MKCOL', refresh=1) if not itrue: raise PreconditionFailed( 'Condition failed against locknull resource') # All of the If header tests succeeded, now we need to remove ourselves # from our parent. We need to transfer lock state to the new folder. locks = self.wl_lockItems() parent._delObject(name) parent.manage_addFolder(name) folder = parent._getOb(name) for token, lock in locks: folder.wl_setLock(token, lock) RESPONSE.setStatus(201) RESPONSE.setBody('') return RESPONSE
[ "def", "MKCOL", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "if", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", ":", "raise", "UnsupportedMediaType", "(", "'Unknown request body.'", ")", "name", "=", "self", ".", "__name__", "parent", "=", "self", ".", "aq_parent", "parenturl", "=", "parent", ".", "absolute_url", "(", ")", "ifhdr", "=", "REQUEST", ".", "get_header", "(", "'If'", ",", "''", ")", "if", "not", "ifhdr", ":", "raise", "PreconditionFailed", "(", "'No If-header'", ")", "# If the parent object is locked, that information should be in the", "# if-header if the user owns a lock on the parent", "if", "IWriteLock", ".", "providedBy", "(", "parent", ")", "and", "parent", ".", "wl_isLocked", "(", ")", ":", "itrue", "=", "parent", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "'MKCOL'", ",", "col", "=", "1", ",", "url", "=", "parenturl", ",", "refresh", "=", "1", ")", "if", "not", "itrue", ":", "raise", "PreconditionFailed", "(", "'Condition failed against resources parent'", ")", "# Now we need to check the If header against our own lock state", "itrue", "=", "self", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "'MKCOL'", ",", "refresh", "=", "1", ")", "if", "not", "itrue", ":", "raise", "PreconditionFailed", "(", "'Condition failed against locknull resource'", ")", "# All of the If header tests succeeded, now we need to remove ourselves", "# from our parent. We need to transfer lock state to the new folder.", "locks", "=", "self", ".", "wl_lockItems", "(", ")", "parent", ".", "_delObject", "(", "name", ")", "parent", ".", "manage_addFolder", "(", "name", ")", "folder", "=", "parent", ".", "_getOb", "(", "name", ")", "for", "token", ",", "lock", "in", "locks", ":", "folder", ".", "wl_setLock", "(", "token", ",", "lock", ")", "RESPONSE", ".", "setStatus", "(", "201", ")", "RESPONSE", ".", "setBody", "(", "''", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/NullResource.py#L473-L516
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/common.py
python
isDavCollection
(object)
return getattr(object, '__dav_collection__', 0)
Return true if object is a DAV collection.
Return true if object is a DAV collection.
[ "Return", "true", "if", "object", "is", "a", "DAV", "collection", "." ]
def isDavCollection(object): """Return true if object is a DAV collection.""" return getattr(object, '__dav_collection__', 0)
[ "def", "isDavCollection", "(", "object", ")", ":", "return", "getattr", "(", "object", ",", "'__dav_collection__'", ",", "0", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/common.py#L88-L90
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/webdav/davcmds.py
python
Lock.apply
(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1)
return token, result.getvalue()
Apply, built for recursion (so that we may lock subitems of a collection if requested
Apply, built for recursion (so that we may lock subitems of a collection if requested
[ "Apply", "built", "for", "recursion", "(", "so", "that", "we", "may", "lock", "subitems", "of", "a", "collection", "if", "requested" ]
def apply(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1): """ Apply, built for recursion (so that we may lock subitems of a collection if requested """ if result is None: result = StringIO() url = urlfix(self.request['URL'], 'LOCK') url = urlbase(url) iscol = isDavCollection(obj) if iscol and url[-1] != '/': url = url + '/' errmsg = None exc_ob = None lock = None try: lock = LockItem(creator, self.owner, depth, self.timeout, self.type, self.scope, token) if token is None: token = lock.getLockToken() except ValueError: errmsg = "412 Precondition Failed" exc_ob = HTTPPreconditionFailed() except Exception: errmsg = "403 Forbidden" exc_ob = Forbidden() try: if not IWriteLock.providedBy(obj): if top: # This is the top level object in the apply, so we # do want an error errmsg = "405 Method Not Allowed" exc_ob = MethodNotAllowed() else: # We're in an infinity request and a subobject does # not support locking, so we'll just pass pass elif obj.wl_isLocked(): errmsg = "423 Locked" exc_ob = ResourceLockedError() else: method = getattr(obj, 'wl_setLock') vld = getSecurityManager().validate(None, obj, 'wl_setLock', method) if vld and token and (lock is not None): obj.wl_setLock(token, lock) else: errmsg = "403 Forbidden" exc_ob = Forbidden() except Exception: errmsg = "403 Forbidden" exc_ob = Forbidden() if errmsg: if top and ((depth in (0, '0')) or (not iscol)): # We don't need to raise multistatus errors raise exc_ob elif not result.getvalue(): # We haven't had any errors yet, so our result is empty # and we need to set up the XML header result.write('<?xml version="1.0" encoding="utf-8" ?>\n' '<d:multistatus xmlns:d="DAV:">\n') result.write('<d:response>\n <d:href>%s</d:href>\n' % url) result.write(' <d:status>HTTP/1.1 %s</d:status>\n' % errmsg) result.write('</d:response>\n') if depth == 'infinity' and iscol: for ob in obj.objectValues(): if hasattr(obj, '__dav_resource__'): uri = urljoin(url, absattr(ob.getId())) self.apply(ob, creator, depth, token, result, uri, top=0) if not top: return token, result if result.getvalue(): # One or more subitems probably failed, so close the multistatus # element and clear out all succesful locks result.write('</d:multistatus>') transaction.abort() # This *SHOULD* clear all succesful locks return token, result.getvalue()
[ "def", "apply", "(", "self", ",", "obj", ",", "creator", "=", "None", ",", "depth", "=", "'infinity'", ",", "token", "=", "None", ",", "result", "=", "None", ",", "url", "=", "None", ",", "top", "=", "1", ")", ":", "if", "result", "is", "None", ":", "result", "=", "StringIO", "(", ")", "url", "=", "urlfix", "(", "self", ".", "request", "[", "'URL'", "]", ",", "'LOCK'", ")", "url", "=", "urlbase", "(", "url", ")", "iscol", "=", "isDavCollection", "(", "obj", ")", "if", "iscol", "and", "url", "[", "-", "1", "]", "!=", "'/'", ":", "url", "=", "url", "+", "'/'", "errmsg", "=", "None", "exc_ob", "=", "None", "lock", "=", "None", "try", ":", "lock", "=", "LockItem", "(", "creator", ",", "self", ".", "owner", ",", "depth", ",", "self", ".", "timeout", ",", "self", ".", "type", ",", "self", ".", "scope", ",", "token", ")", "if", "token", "is", "None", ":", "token", "=", "lock", ".", "getLockToken", "(", ")", "except", "ValueError", ":", "errmsg", "=", "\"412 Precondition Failed\"", "exc_ob", "=", "HTTPPreconditionFailed", "(", ")", "except", "Exception", ":", "errmsg", "=", "\"403 Forbidden\"", "exc_ob", "=", "Forbidden", "(", ")", "try", ":", "if", "not", "IWriteLock", ".", "providedBy", "(", "obj", ")", ":", "if", "top", ":", "# This is the top level object in the apply, so we", "# do want an error", "errmsg", "=", "\"405 Method Not Allowed\"", "exc_ob", "=", "MethodNotAllowed", "(", ")", "else", ":", "# We're in an infinity request and a subobject does", "# not support locking, so we'll just pass", "pass", "elif", "obj", ".", "wl_isLocked", "(", ")", ":", "errmsg", "=", "\"423 Locked\"", "exc_ob", "=", "ResourceLockedError", "(", ")", "else", ":", "method", "=", "getattr", "(", "obj", ",", "'wl_setLock'", ")", "vld", "=", "getSecurityManager", "(", ")", ".", "validate", "(", "None", ",", "obj", ",", "'wl_setLock'", ",", "method", ")", "if", "vld", "and", "token", "and", "(", "lock", "is", "not", "None", ")", ":", "obj", ".", "wl_setLock", "(", "token", ",", "lock", ")", "else", ":", "errmsg", "=", "\"403 Forbidden\"", "exc_ob", "=", "Forbidden", "(", ")", "except", "Exception", ":", "errmsg", "=", "\"403 Forbidden\"", "exc_ob", "=", "Forbidden", "(", ")", "if", "errmsg", ":", "if", "top", "and", "(", "(", "depth", "in", "(", "0", ",", "'0'", ")", ")", "or", "(", "not", "iscol", ")", ")", ":", "# We don't need to raise multistatus errors", "raise", "exc_ob", "elif", "not", "result", ".", "getvalue", "(", ")", ":", "# We haven't had any errors yet, so our result is empty", "# and we need to set up the XML header", "result", ".", "write", "(", "'<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n'", "'<d:multistatus xmlns:d=\"DAV:\">\\n'", ")", "result", ".", "write", "(", "'<d:response>\\n <d:href>%s</d:href>\\n'", "%", "url", ")", "result", ".", "write", "(", "' <d:status>HTTP/1.1 %s</d:status>\\n'", "%", "errmsg", ")", "result", ".", "write", "(", "'</d:response>\\n'", ")", "if", "depth", "==", "'infinity'", "and", "iscol", ":", "for", "ob", "in", "obj", ".", "objectValues", "(", ")", ":", "if", "hasattr", "(", "obj", ",", "'__dav_resource__'", ")", ":", "uri", "=", "urljoin", "(", "url", ",", "absattr", "(", "ob", ".", "getId", "(", ")", ")", ")", "self", ".", "apply", "(", "ob", ",", "creator", ",", "depth", ",", "token", ",", "result", ",", "uri", ",", "top", "=", "0", ")", "if", "not", "top", ":", "return", "token", ",", "result", "if", "result", ".", "getvalue", "(", ")", ":", "# One or more subitems probably failed, so close the multistatus", "# element and clear out all succesful locks", "result", ".", "write", "(", "'</d:multistatus>'", ")", "transaction", ".", "abort", "(", ")", "# This *SHOULD* clear all succesful locks", "return", "token", ",", "result", ".", "getvalue", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/webdav/davcmds.py#L351-L433
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/zmi/styles/subscriber.py
python
css_paths
(context)
return ( '/++resource++zmi/bootstrap-4.6.0/bootstrap.min.css', '/++resource++zmi/fontawesome-free-5.15.2/css/all.css', '/++resource++zmi/zmi_base.css', )
Return paths to CSS files needed for the Zope 4 ZMI.
Return paths to CSS files needed for the Zope 4 ZMI.
[ "Return", "paths", "to", "CSS", "files", "needed", "for", "the", "Zope", "4", "ZMI", "." ]
def css_paths(context): """Return paths to CSS files needed for the Zope 4 ZMI.""" return ( '/++resource++zmi/bootstrap-4.6.0/bootstrap.min.css', '/++resource++zmi/fontawesome-free-5.15.2/css/all.css', '/++resource++zmi/zmi_base.css', )
[ "def", "css_paths", "(", "context", ")", ":", "return", "(", "'/++resource++zmi/bootstrap-4.6.0/bootstrap.min.css'", ",", "'/++resource++zmi/fontawesome-free-5.15.2/css/all.css'", ",", "'/++resource++zmi/zmi_base.css'", ",", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/zmi/styles/subscriber.py#L6-L12
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/zmi/styles/subscriber.py
python
js_paths
(context)
return ( '/++resource++zmi/jquery-3.5.1.min.js', '/++resource++zmi/bootstrap-4.6.0/bootstrap.bundle.min.js', '/++resource++zmi/ace.ajax.org/ace.js', '/++resource++zmi/zmi_base.js', )
Return paths to JS files needed for the Zope 4 ZMI.
Return paths to JS files needed for the Zope 4 ZMI.
[ "Return", "paths", "to", "JS", "files", "needed", "for", "the", "Zope", "4", "ZMI", "." ]
def js_paths(context): """Return paths to JS files needed for the Zope 4 ZMI.""" return ( '/++resource++zmi/jquery-3.5.1.min.js', '/++resource++zmi/bootstrap-4.6.0/bootstrap.bundle.min.js', '/++resource++zmi/ace.ajax.org/ace.js', '/++resource++zmi/zmi_base.js', )
[ "def", "js_paths", "(", "context", ")", ":", "return", "(", "'/++resource++zmi/jquery-3.5.1.min.js'", ",", "'/++resource++zmi/bootstrap-4.6.0/bootstrap.bundle.min.js'", ",", "'/++resource++zmi/ace.ajax.org/ace.js'", ",", "'/++resource++zmi/zmi_base.js'", ",", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/zmi/styles/subscriber.py#L16-L23
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/SiteAccess/VirtualHostMonster.py
python
VirtualHostMonster.set_map
(self, map_text, RESPONSE=None)
Set domain to path mappings.
Set domain to path mappings.
[ "Set", "domain", "to", "path", "mappings", "." ]
def set_map(self, map_text, RESPONSE=None): "Set domain to path mappings." lines = map_text.split('\n') self.fixed_map = fixed_map = {} self.sub_map = sub_map = {} new_lines = [] for line in lines: line = line.split('#!')[0].strip() if not line: continue try: # Drop the protocol, if any line = line.split('://')[-1] try: host, path = [x.strip() for x in line.split('/', 1)] except Exception: raise ValueError( 'Line needs a slash between host and path: %s' % line) pp = list(filter(None, path.split('/'))) if pp: obpath = pp[:] if obpath[0] == 'VirtualHostBase': obpath = obpath[3:] if 'VirtualHostRoot' in obpath: i1 = obpath.index('VirtualHostRoot') i2 = i1 + 1 while i2 < len(obpath) and obpath[i2][:4] == '_vh_': i2 = i2 + 1 del obpath[i1:i2] if obpath: try: ob = self.unrestrictedTraverse(obpath) except Exception: raise ValueError( 'Path not found: %s' % obpath) if not getattr(ob.aq_base, 'isAnObjectManager', 0): raise ValueError( 'Path must lead to an Object Manager: %s' % obpath) if 'VirtualHostRoot' not in pp: pp.append('/') pp.reverse() try: int(host.replace('.', '')) raise ValueError( 'IP addresses are not mappable: %s' % host) except ValueError: pass if host[:2] == '*.': host_map = sub_map host = host[2:] else: host_map = fixed_map hostname, port = (host.split(':', 1) + [None])[:2] if hostname not in host_map: host_map[hostname] = {} host_map[hostname][port] = pp except ValueError as msg: line = f'{line} #! {msg}' new_lines.append(line) self.lines = tuple(new_lines) self.have_map = bool(fixed_map or sub_map) # booleanize if RESPONSE is not None: RESPONSE.redirect( 'manage_edit?manage_tabs_message=Changes%20Saved.')
[ "def", "set_map", "(", "self", ",", "map_text", ",", "RESPONSE", "=", "None", ")", ":", "lines", "=", "map_text", ".", "split", "(", "'\\n'", ")", "self", ".", "fixed_map", "=", "fixed_map", "=", "{", "}", "self", ".", "sub_map", "=", "sub_map", "=", "{", "}", "new_lines", "=", "[", "]", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "split", "(", "'#!'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "try", ":", "# Drop the protocol, if any", "line", "=", "line", ".", "split", "(", "'://'", ")", "[", "-", "1", "]", "try", ":", "host", ",", "path", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "line", ".", "split", "(", "'/'", ",", "1", ")", "]", "except", "Exception", ":", "raise", "ValueError", "(", "'Line needs a slash between host and path: %s'", "%", "line", ")", "pp", "=", "list", "(", "filter", "(", "None", ",", "path", ".", "split", "(", "'/'", ")", ")", ")", "if", "pp", ":", "obpath", "=", "pp", "[", ":", "]", "if", "obpath", "[", "0", "]", "==", "'VirtualHostBase'", ":", "obpath", "=", "obpath", "[", "3", ":", "]", "if", "'VirtualHostRoot'", "in", "obpath", ":", "i1", "=", "obpath", ".", "index", "(", "'VirtualHostRoot'", ")", "i2", "=", "i1", "+", "1", "while", "i2", "<", "len", "(", "obpath", ")", "and", "obpath", "[", "i2", "]", "[", ":", "4", "]", "==", "'_vh_'", ":", "i2", "=", "i2", "+", "1", "del", "obpath", "[", "i1", ":", "i2", "]", "if", "obpath", ":", "try", ":", "ob", "=", "self", ".", "unrestrictedTraverse", "(", "obpath", ")", "except", "Exception", ":", "raise", "ValueError", "(", "'Path not found: %s'", "%", "obpath", ")", "if", "not", "getattr", "(", "ob", ".", "aq_base", ",", "'isAnObjectManager'", ",", "0", ")", ":", "raise", "ValueError", "(", "'Path must lead to an Object Manager: %s'", "%", "obpath", ")", "if", "'VirtualHostRoot'", "not", "in", "pp", ":", "pp", ".", "append", "(", "'/'", ")", "pp", ".", "reverse", "(", ")", "try", ":", "int", "(", "host", ".", "replace", "(", "'.'", ",", "''", ")", ")", "raise", "ValueError", "(", "'IP addresses are not mappable: %s'", "%", "host", ")", "except", "ValueError", ":", "pass", "if", "host", "[", ":", "2", "]", "==", "'*.'", ":", "host_map", "=", "sub_map", "host", "=", "host", "[", "2", ":", "]", "else", ":", "host_map", "=", "fixed_map", "hostname", ",", "port", "=", "(", "host", ".", "split", "(", "':'", ",", "1", ")", "+", "[", "None", "]", ")", "[", ":", "2", "]", "if", "hostname", "not", "in", "host_map", ":", "host_map", "[", "hostname", "]", "=", "{", "}", "host_map", "[", "hostname", "]", "[", "port", "]", "=", "pp", "except", "ValueError", "as", "msg", ":", "line", "=", "f'{line} #! {msg}'", "new_lines", ".", "append", "(", "line", ")", "self", ".", "lines", "=", "tuple", "(", "new_lines", ")", "self", ".", "have_map", "=", "bool", "(", "fixed_map", "or", "sub_map", ")", "# booleanize", "if", "RESPONSE", "is", "not", "None", ":", "RESPONSE", ".", "redirect", "(", "'manage_edit?manage_tabs_message=Changes%20Saved.'", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/SiteAccess/VirtualHostMonster.py#L50-L114
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/SiteAccess/VirtualHostMonster.py
python
VirtualHostMonster.__call__
(self, client, request, response=None)
Traversing at home
Traversing at home
[ "Traversing", "at", "home" ]
def __call__(self, client, request, response=None): '''Traversing at home''' vh_used = 0 stack = request['TraversalRequestNameStack'] path = None while 1: if stack and stack[-1] == 'VirtualHostBase': vh_used = 1 stack.pop() protocol = stack.pop() host = stack.pop() hostname, port = splitport(host) port = int(port) if port else None request.setServerURL(protocol, hostname, port) path = list(stack) # Find and convert VirtualHostRoot directive # If it is followed by one or more path elements that each # start with '_vh_', use them to construct the path to the # virtual root. vh = -1 for ii in range(len(stack)): if stack[ii] == 'VirtualHostRoot': vh_used = 1 pp = [''] at_end = (ii == len(stack) - 1) if vh >= 0: for jj in range(vh, ii): pp.insert(1, stack[jj][4:]) stack[vh:ii + 1] = ['/'.join(pp), self.id] ii = vh + 1 elif ii > 0 and stack[ii - 1][:1] == '/': pp = stack[ii - 1].split('/') stack[ii] = self.id else: stack[ii] = self.id stack.insert(ii, '/') ii += 1 if '*' in stack: stack[stack.index('*')] = host.split('.')[0] path = stack[:ii] # If the directive is on top of the stack, go ahead # and process it right away. if at_end: request.setVirtualRoot(pp) del stack[-2:] break elif vh < 0 and stack[ii][:4] == '_vh_': vh = ii if vh_used or not self.have_map: if path is not None: path.reverse() vh_part = '' if path and path[0].startswith('/'): vh_part = path.pop(0)[1:] if vh_part: request['VIRTUAL_URL_PARTS'] = vup = ( request['SERVER_URL'], vh_part, quote('/'.join(path))) else: request['VIRTUAL_URL_PARTS'] = vup = ( request['SERVER_URL'], quote('/'.join(path))) request['VIRTUAL_URL'] = '/'.join(vup) # new ACTUAL_URL add = path and \ request['ACTUAL_URL'].endswith('/') and '/' or '' request['ACTUAL_URL'] = request['VIRTUAL_URL'] + add return vh_used = 1 # Only retry once. # Try to apply the host map if one exists, and if no # VirtualHost directives were found. host = request['SERVER_URL'].split('://')[1].lower() hostname, port = (host.split(':', 1) + [None])[:2] ports = self.fixed_map.get(hostname, 0) if not ports and self.sub_map: get = self.sub_map.get while hostname: ports = get(hostname, 0) if ports: break if '.' not in hostname: return hostname = hostname.split('.', 1)[1] if ports: pp = ports.get(port, 0) if pp == 0 and port is not None: # Try default port pp = ports.get(None, 0) if not pp: return # If there was no explicit VirtualHostRoot, add one at the end if pp[0] == '/': pp = pp[:] pp.insert(1, self.id) stack.extend(pp)
[ "def", "__call__", "(", "self", ",", "client", ",", "request", ",", "response", "=", "None", ")", ":", "vh_used", "=", "0", "stack", "=", "request", "[", "'TraversalRequestNameStack'", "]", "path", "=", "None", "while", "1", ":", "if", "stack", "and", "stack", "[", "-", "1", "]", "==", "'VirtualHostBase'", ":", "vh_used", "=", "1", "stack", ".", "pop", "(", ")", "protocol", "=", "stack", ".", "pop", "(", ")", "host", "=", "stack", ".", "pop", "(", ")", "hostname", ",", "port", "=", "splitport", "(", "host", ")", "port", "=", "int", "(", "port", ")", "if", "port", "else", "None", "request", ".", "setServerURL", "(", "protocol", ",", "hostname", ",", "port", ")", "path", "=", "list", "(", "stack", ")", "# Find and convert VirtualHostRoot directive", "# If it is followed by one or more path elements that each", "# start with '_vh_', use them to construct the path to the", "# virtual root.", "vh", "=", "-", "1", "for", "ii", "in", "range", "(", "len", "(", "stack", ")", ")", ":", "if", "stack", "[", "ii", "]", "==", "'VirtualHostRoot'", ":", "vh_used", "=", "1", "pp", "=", "[", "''", "]", "at_end", "=", "(", "ii", "==", "len", "(", "stack", ")", "-", "1", ")", "if", "vh", ">=", "0", ":", "for", "jj", "in", "range", "(", "vh", ",", "ii", ")", ":", "pp", ".", "insert", "(", "1", ",", "stack", "[", "jj", "]", "[", "4", ":", "]", ")", "stack", "[", "vh", ":", "ii", "+", "1", "]", "=", "[", "'/'", ".", "join", "(", "pp", ")", ",", "self", ".", "id", "]", "ii", "=", "vh", "+", "1", "elif", "ii", ">", "0", "and", "stack", "[", "ii", "-", "1", "]", "[", ":", "1", "]", "==", "'/'", ":", "pp", "=", "stack", "[", "ii", "-", "1", "]", ".", "split", "(", "'/'", ")", "stack", "[", "ii", "]", "=", "self", ".", "id", "else", ":", "stack", "[", "ii", "]", "=", "self", ".", "id", "stack", ".", "insert", "(", "ii", ",", "'/'", ")", "ii", "+=", "1", "if", "'*'", "in", "stack", ":", "stack", "[", "stack", ".", "index", "(", "'*'", ")", "]", "=", "host", ".", "split", "(", "'.'", ")", "[", "0", "]", "path", "=", "stack", "[", ":", "ii", "]", "# If the directive is on top of the stack, go ahead", "# and process it right away.", "if", "at_end", ":", "request", ".", "setVirtualRoot", "(", "pp", ")", "del", "stack", "[", "-", "2", ":", "]", "break", "elif", "vh", "<", "0", "and", "stack", "[", "ii", "]", "[", ":", "4", "]", "==", "'_vh_'", ":", "vh", "=", "ii", "if", "vh_used", "or", "not", "self", ".", "have_map", ":", "if", "path", "is", "not", "None", ":", "path", ".", "reverse", "(", ")", "vh_part", "=", "''", "if", "path", "and", "path", "[", "0", "]", ".", "startswith", "(", "'/'", ")", ":", "vh_part", "=", "path", ".", "pop", "(", "0", ")", "[", "1", ":", "]", "if", "vh_part", ":", "request", "[", "'VIRTUAL_URL_PARTS'", "]", "=", "vup", "=", "(", "request", "[", "'SERVER_URL'", "]", ",", "vh_part", ",", "quote", "(", "'/'", ".", "join", "(", "path", ")", ")", ")", "else", ":", "request", "[", "'VIRTUAL_URL_PARTS'", "]", "=", "vup", "=", "(", "request", "[", "'SERVER_URL'", "]", ",", "quote", "(", "'/'", ".", "join", "(", "path", ")", ")", ")", "request", "[", "'VIRTUAL_URL'", "]", "=", "'/'", ".", "join", "(", "vup", ")", "# new ACTUAL_URL", "add", "=", "path", "and", "request", "[", "'ACTUAL_URL'", "]", ".", "endswith", "(", "'/'", ")", "and", "'/'", "or", "''", "request", "[", "'ACTUAL_URL'", "]", "=", "request", "[", "'VIRTUAL_URL'", "]", "+", "add", "return", "vh_used", "=", "1", "# Only retry once.", "# Try to apply the host map if one exists, and if no", "# VirtualHost directives were found.", "host", "=", "request", "[", "'SERVER_URL'", "]", ".", "split", "(", "'://'", ")", "[", "1", "]", ".", "lower", "(", ")", "hostname", ",", "port", "=", "(", "host", ".", "split", "(", "':'", ",", "1", ")", "+", "[", "None", "]", ")", "[", ":", "2", "]", "ports", "=", "self", ".", "fixed_map", ".", "get", "(", "hostname", ",", "0", ")", "if", "not", "ports", "and", "self", ".", "sub_map", ":", "get", "=", "self", ".", "sub_map", ".", "get", "while", "hostname", ":", "ports", "=", "get", "(", "hostname", ",", "0", ")", "if", "ports", ":", "break", "if", "'.'", "not", "in", "hostname", ":", "return", "hostname", "=", "hostname", ".", "split", "(", "'.'", ",", "1", ")", "[", "1", "]", "if", "ports", ":", "pp", "=", "ports", ".", "get", "(", "port", ",", "0", ")", "if", "pp", "==", "0", "and", "port", "is", "not", "None", ":", "# Try default port", "pp", "=", "ports", ".", "get", "(", "None", ",", "0", ")", "if", "not", "pp", ":", "return", "# If there was no explicit VirtualHostRoot, add one at the end", "if", "pp", "[", "0", "]", "==", "'/'", ":", "pp", "=", "pp", "[", ":", "]", "pp", ".", "insert", "(", "1", ",", "self", ".", "id", ")", "stack", ".", "extend", "(", "pp", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/SiteAccess/VirtualHostMonster.py#L141-L238
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/SiteAccess/VirtualHostMonster.py
python
VirtualHostMonster.__bobo_traverse__
(self, request, name)
return parents.pop()
Traversing away
Traversing away
[ "Traversing", "away" ]
def __bobo_traverse__(self, request, name): '''Traversing away''' if name[:1] != '/': return getattr(self, name) parents = request.PARENTS parents.pop() # I don't belong there if len(name) > 1: request.setVirtualRoot(name) else: request.setVirtualRoot([]) return parents.pop()
[ "def", "__bobo_traverse__", "(", "self", ",", "request", ",", "name", ")", ":", "if", "name", "[", ":", "1", "]", "!=", "'/'", ":", "return", "getattr", "(", "self", ",", "name", ")", "parents", "=", "request", ".", "PARENTS", "parents", ".", "pop", "(", ")", "# I don't belong there", "if", "len", "(", "name", ")", ">", "1", ":", "request", ".", "setVirtualRoot", "(", "name", ")", "else", ":", "request", ".", "setVirtualRoot", "(", "[", "]", ")", "return", "parents", ".", "pop", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/SiteAccess/VirtualHostMonster.py#L240-L251
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/sizeconfigure.py
python
classSizable
(class_)
Monkey the class to be sizable through Five
Monkey the class to be sizable through Five
[ "Monkey", "the", "class", "to", "be", "sizable", "through", "Five" ]
def classSizable(class_): """Monkey the class to be sizable through Five""" # tuck away the original method if necessary if hasattr(class_, "get_size") and not isFiveMethod(class_.get_size): class_.__five_original_get_size = class_.get_size class_.get_size = get_size # remember class for clean up _monkied.append(class_)
[ "def", "classSizable", "(", "class_", ")", ":", "# tuck away the original method if necessary", "if", "hasattr", "(", "class_", ",", "\"get_size\"", ")", "and", "not", "isFiveMethod", "(", "class_", ".", "get_size", ")", ":", "class_", ".", "__five_original_get_size", "=", "class_", ".", "get_size", "class_", ".", "get_size", "=", "get_size", "# remember class for clean up", "_monkied", ".", "append", "(", "class_", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/sizeconfigure.py#L40-L47
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/sizeconfigure.py
python
killMonkey
(class_, name, fallback, attr=None)
Die monkey, die!
Die monkey, die!
[ "Die", "monkey", "die!" ]
def killMonkey(class_, name, fallback, attr=None): """Die monkey, die!""" method = getattr(class_, name, None) if isFiveMethod(method): original = getattr(class_, fallback, None) if original is not None: delattr(class_, fallback) if original is None or isFiveMethod(original): try: delattr(class_, name) except AttributeError: pass else: setattr(class_, name, original) if attr is not None: try: delattr(class_, attr) except (AttributeError, KeyError): pass
[ "def", "killMonkey", "(", "class_", ",", "name", ",", "fallback", ",", "attr", "=", "None", ")", ":", "method", "=", "getattr", "(", "class_", ",", "name", ",", "None", ")", "if", "isFiveMethod", "(", "method", ")", ":", "original", "=", "getattr", "(", "class_", ",", "fallback", ",", "None", ")", "if", "original", "is", "not", "None", ":", "delattr", "(", "class_", ",", "fallback", ")", "if", "original", "is", "None", "or", "isFiveMethod", "(", "original", ")", ":", "try", ":", "delattr", "(", "class_", ",", "name", ")", "except", "AttributeError", ":", "pass", "else", ":", "setattr", "(", "class_", ",", "name", ",", "original", ")", "if", "attr", "is", "not", "None", ":", "try", ":", "delattr", "(", "class_", ",", "attr", ")", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "pass" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/sizeconfigure.py#L58-L77
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/sizeconfigure.py
python
unsizable
(class_)
Restore class's initial state with respect to being sizable
Restore class's initial state with respect to being sizable
[ "Restore", "class", "s", "initial", "state", "with", "respect", "to", "being", "sizable" ]
def unsizable(class_): """Restore class's initial state with respect to being sizable""" killMonkey(class_, 'get_size', '__five_original_get_size')
[ "def", "unsizable", "(", "class_", ")", ":", "killMonkey", "(", "class_", ",", "'get_size'", ",", "'__five_original_get_size'", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/sizeconfigure.py#L80-L82
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/component/__init__.py
python
findSite
(obj, iface=ISite)
return obj
Find a site by walking up the object hierarchy, supporting both the ``ILocation`` API and Zope 2 Acquisition.
Find a site by walking up the object hierarchy, supporting both the ``ILocation`` API and Zope 2 Acquisition.
[ "Find", "a", "site", "by", "walking", "up", "the", "object", "hierarchy", "supporting", "both", "the", "ILocation", "API", "and", "Zope", "2", "Acquisition", "." ]
def findSite(obj, iface=ISite): """Find a site by walking up the object hierarchy, supporting both the ``ILocation`` API and Zope 2 Acquisition.""" while obj is not None and not iface.providedBy(obj): obj = aq_parent(aq_inner(obj)) return obj
[ "def", "findSite", "(", "obj", ",", "iface", "=", "ISite", ")", ":", "while", "obj", "is", "not", "None", "and", "not", "iface", ".", "providedBy", "(", "obj", ")", ":", "obj", "=", "aq_parent", "(", "aq_inner", "(", "obj", ")", ")", "return", "obj" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/component/__init__.py#L38-L43
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/component/__init__.py
python
siteManagerAdapter
(ob)
return site.getSiteManager()
Look-up a site manager/component registry for local component lookup. This is registered in place of the one in zope.site so that we lookup using acquisition in addition to the ``ILocation`` API.
Look-up a site manager/component registry for local component lookup. This is registered in place of the one in zope.site so that we lookup using acquisition in addition to the ``ILocation`` API.
[ "Look", "-", "up", "a", "site", "manager", "/", "component", "registry", "for", "local", "component", "lookup", ".", "This", "is", "registered", "in", "place", "of", "the", "one", "in", "zope", ".", "site", "so", "that", "we", "lookup", "using", "acquisition", "in", "addition", "to", "the", "ILocation", "API", "." ]
def siteManagerAdapter(ob): """Look-up a site manager/component registry for local component lookup. This is registered in place of the one in zope.site so that we lookup using acquisition in addition to the ``ILocation`` API. """ site = findSite(ob) if site is None: return zope.component.getGlobalSiteManager() return site.getSiteManager()
[ "def", "siteManagerAdapter", "(", "ob", ")", ":", "site", "=", "findSite", "(", "ob", ")", "if", "site", "is", "None", ":", "return", "zope", ".", "component", ".", "getGlobalSiteManager", "(", ")", "return", "site", ".", "getSiteManager", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/component/__init__.py#L48-L56
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/component/__init__.py
python
enableSite
(obj, iface=ISite)
Install __before_traverse__ hook for Local Site
Install __before_traverse__ hook for Local Site
[ "Install", "__before_traverse__", "hook", "for", "Local", "Site" ]
def enableSite(obj, iface=ISite): """Install __before_traverse__ hook for Local Site """ # We want the original object, not stuff in between, and no acquisition obj = aq_base(obj) if not IPossibleSite.providedBy(obj): raise TypeError('Must provide IPossibleSite') hook = NameCaller(HOOK_NAME) registerBeforeTraverse(obj, hook, HOOK_NAME, 1) if not hasattr(obj, HOOK_NAME): setattr(obj, HOOK_NAME, LocalSiteHook()) zope.interface.alsoProvides(obj, iface)
[ "def", "enableSite", "(", "obj", ",", "iface", "=", "ISite", ")", ":", "# We want the original object, not stuff in between, and no acquisition", "obj", "=", "aq_base", "(", "obj", ")", "if", "not", "IPossibleSite", ".", "providedBy", "(", "obj", ")", ":", "raise", "TypeError", "(", "'Must provide IPossibleSite'", ")", "hook", "=", "NameCaller", "(", "HOOK_NAME", ")", "registerBeforeTraverse", "(", "obj", ",", "hook", ",", "HOOK_NAME", ",", "1", ")", "if", "not", "hasattr", "(", "obj", ",", "HOOK_NAME", ")", ":", "setattr", "(", "obj", ",", "HOOK_NAME", ",", "LocalSiteHook", "(", ")", ")", "zope", ".", "interface", ".", "alsoProvides", "(", "obj", ",", "iface", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/component/__init__.py#L68-L81
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/component/__init__.py
python
disableSite
(obj, iface=ISite)
Remove __before_traverse__ hook for Local Site
Remove __before_traverse__ hook for Local Site
[ "Remove", "__before_traverse__", "hook", "for", "Local", "Site" ]
def disableSite(obj, iface=ISite): """Remove __before_traverse__ hook for Local Site """ # We want the original object, not stuff in between, and no acquisition obj = aq_base(obj) if not iface.providedBy(obj): raise TypeError('Object must be a site.') unregisterBeforeTraverse(obj, HOOK_NAME) if hasattr(obj, HOOK_NAME): delattr(obj, HOOK_NAME) zope.interface.noLongerProvides(obj, iface)
[ "def", "disableSite", "(", "obj", ",", "iface", "=", "ISite", ")", ":", "# We want the original object, not stuff in between, and no acquisition", "obj", "=", "aq_base", "(", "obj", ")", "if", "not", "iface", ".", "providedBy", "(", "obj", ")", ":", "raise", "TypeError", "(", "'Object must be a site.'", ")", "unregisterBeforeTraverse", "(", "obj", ",", "HOOK_NAME", ")", "if", "hasattr", "(", "obj", ",", "HOOK_NAME", ")", ":", "delattr", "(", "obj", ",", "HOOK_NAME", ")", "zope", ".", "interface", ".", "noLongerProvides", "(", "obj", ",", "iface", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/component/__init__.py#L84-L96
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getDirectlyProvided
()
List the interfaces directly implemented by the object.
List the interfaces directly implemented by the object.
[ "List", "the", "interfaces", "directly", "implemented", "by", "the", "object", "." ]
def getDirectlyProvided(): """List the interfaces directly implemented by the object. """
[ "def", "getDirectlyProvided", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L22-L24
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getDirectlyProvidedNames
()
List the names of interfaces directly implemented by the object.
List the names of interfaces directly implemented by the object.
[ "List", "the", "names", "of", "interfaces", "directly", "implemented", "by", "the", "object", "." ]
def getDirectlyProvidedNames(): """List the names of interfaces directly implemented by the object. """
[ "def", "getDirectlyProvidedNames", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L26-L28
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getAvailableInterfaces
()
List the marker interfaces available for the object.
List the marker interfaces available for the object.
[ "List", "the", "marker", "interfaces", "available", "for", "the", "object", "." ]
def getAvailableInterfaces(): """List the marker interfaces available for the object. """
[ "def", "getAvailableInterfaces", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L30-L32
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getAvailableInterfaceNames
()
List the names of marker interfaces available for the object.
List the names of marker interfaces available for the object.
[ "List", "the", "names", "of", "marker", "interfaces", "available", "for", "the", "object", "." ]
def getAvailableInterfaceNames(): """List the names of marker interfaces available for the object. """
[ "def", "getAvailableInterfaceNames", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L34-L36
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getInterfaces
()
List interfaces provided by the class of the object.
List interfaces provided by the class of the object.
[ "List", "interfaces", "provided", "by", "the", "class", "of", "the", "object", "." ]
def getInterfaces(): """List interfaces provided by the class of the object. """
[ "def", "getInterfaces", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L38-L40
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getInterfaceNames
()
List the names of interfaces provided by the class of the object.
List the names of interfaces provided by the class of the object.
[ "List", "the", "names", "of", "interfaces", "provided", "by", "the", "class", "of", "the", "object", "." ]
def getInterfaceNames(): """List the names of interfaces provided by the class of the object. """
[ "def", "getInterfaceNames", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L42-L44
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getProvided
()
List interfaces provided by the object.
List interfaces provided by the object.
[ "List", "interfaces", "provided", "by", "the", "object", "." ]
def getProvided(): """List interfaces provided by the object. """
[ "def", "getProvided", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L46-L48
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IReadInterface.getProvidedNames
()
List the names of interfaces provided by the object.
List the names of interfaces provided by the object.
[ "List", "the", "names", "of", "interfaces", "provided", "by", "the", "object", "." ]
def getProvidedNames(): """List the names of interfaces provided by the object. """
[ "def", "getProvidedNames", "(", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L50-L52
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IWriteInterface.update
(add=(), remove=())
Update directly provided interfaces of the object.
Update directly provided interfaces of the object.
[ "Update", "directly", "provided", "interfaces", "of", "the", "object", "." ]
def update(add=(), remove=()): """Update directly provided interfaces of the object. """
[ "def", "update", "(", "add", "=", "(", ")", ",", "remove", "=", "(", ")", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L57-L59
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IWriteInterface.mark
(interface)
Add interface to interfaces the object directly provides.
Add interface to interfaces the object directly provides.
[ "Add", "interface", "to", "interfaces", "the", "object", "directly", "provides", "." ]
def mark(interface): """Add interface to interfaces the object directly provides. """
[ "def", "mark", "(", "interface", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L61-L63
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/utilities/interfaces.py
python
IWriteInterface.erase
(interface)
Remove interfaces from interfaces the object directly provides.
Remove interfaces from interfaces the object directly provides.
[ "Remove", "interfaces", "from", "interfaces", "the", "object", "directly", "provides", "." ]
def erase(interface): """Remove interfaces from interfaces the object directly provides. """
[ "def", "erase", "(", "interface", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/utilities/interfaces.py#L65-L67
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/viewlet.py
python
SimpleViewletClass
(template, bases=(), attributes=None, name='')
return class_
A function that can be used to generate a viewlet from a set of information.
A function that can be used to generate a viewlet from a set of information.
[ "A", "function", "that", "can", "be", "used", "to", "generate", "a", "viewlet", "from", "a", "set", "of", "information", "." ]
def SimpleViewletClass(template, bases=(), attributes=None, name=''): """A function that can be used to generate a viewlet from a set of information. """ # Create the base class hierarchy bases += (simple, ViewletBase) attrs = {'index': ViewPageTemplateFile(template), '__name__': name} if attributes: attrs.update(attributes) # Generate a derived view class. class_ = type("SimpleViewletClass from %s" % template, bases, attrs) return class_
[ "def", "SimpleViewletClass", "(", "template", ",", "bases", "=", "(", ")", ",", "attributes", "=", "None", ",", "name", "=", "''", ")", ":", "# Create the base class hierarchy", "bases", "+=", "(", "simple", ",", "ViewletBase", ")", "attrs", "=", "{", "'index'", ":", "ViewPageTemplateFile", "(", "template", ")", ",", "'__name__'", ":", "name", "}", "if", "attributes", ":", "attrs", ".", "update", "(", "attributes", ")", "# Generate a derived view class.", "class_", "=", "type", "(", "\"SimpleViewletClass from %s\"", "%", "template", ",", "bases", ",", "attrs", ")", "return", "class_" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/viewlet.py#L36-L52
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/viewlet.py
python
JavaScriptViewlet
(path)
return klass
Create a viewlet that can simply insert a javascript link.
Create a viewlet that can simply insert a javascript link.
[ "Create", "a", "viewlet", "that", "can", "simply", "insert", "a", "javascript", "link", "." ]
def JavaScriptViewlet(path): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'javascript_viewlet.pt') klass = type('JavaScriptViewlet', (ResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path}) return klass
[ "def", "JavaScriptViewlet", "(", "path", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'javascript_viewlet.pt'", ")", "klass", "=", "type", "(", "'JavaScriptViewlet'", ",", "(", "ResourceViewletBase", ",", "ViewletBase", ")", ",", "{", "'index'", ":", "ViewPageTemplateFile", "(", "src", ")", ",", "'_path'", ":", "path", "}", ")", "return", "klass" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/viewlet.py#L59-L67
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/viewlet.py
python
CSSViewlet
(path, media="all", rel="stylesheet")
return klass
Create a viewlet that can simply insert a javascript link.
Create a viewlet that can simply insert a javascript link.
[ "Create", "a", "viewlet", "that", "can", "simply", "insert", "a", "javascript", "link", "." ]
def CSSViewlet(path, media="all", rel="stylesheet"): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'css_viewlet.pt') klass = type('CSSViewlet', (CSSResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path, '_media': media, '_rel': rel}) return klass
[ "def", "CSSViewlet", "(", "path", ",", "media", "=", "\"all\"", ",", "rel", "=", "\"stylesheet\"", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'css_viewlet.pt'", ")", "klass", "=", "type", "(", "'CSSViewlet'", ",", "(", "CSSResourceViewletBase", ",", "ViewletBase", ")", ",", "{", "'index'", ":", "ViewPageTemplateFile", "(", "src", ")", ",", "'_path'", ":", "path", ",", "'_media'", ":", "media", ",", "'_rel'", ":", "rel", "}", ")", "return", "klass" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/viewlet.py#L74-L85
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/manager.py
python
ViewletManagerBase.__getitem__
(self, name)
return viewlet
See zope.interface.common.mapping.IReadMapping
See zope.interface.common.mapping.IReadMapping
[ "See", "zope", ".", "interface", ".", "common", ".", "mapping", ".", "IReadMapping" ]
def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) # If the viewlet was not found, then raise a lookup error if viewlet is None: raise zope.interface.interfaces.ComponentLookupError( 'No provider with name `%s` found.' % name) # If the viewlet cannot be accessed, then raise an # unauthorized error if not guarded_hasattr(viewlet, 'render'): raise zope.security.interfaces.Unauthorized( 'You are not authorized to access the provider ' 'called `%s`.' % name) # Return the viewlet. return viewlet
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "# Find the viewlet", "viewlet", "=", "zope", ".", "component", ".", "queryMultiAdapter", "(", "(", "self", ".", "context", ",", "self", ".", "request", ",", "self", ".", "__parent__", ",", "self", ")", ",", "interfaces", ".", "IViewlet", ",", "name", "=", "name", ")", "# If the viewlet was not found, then raise a lookup error", "if", "viewlet", "is", "None", ":", "raise", "zope", ".", "interface", ".", "interfaces", ".", "ComponentLookupError", "(", "'No provider with name `%s` found.'", "%", "name", ")", "# If the viewlet cannot be accessed, then raise an", "# unauthorized error", "if", "not", "guarded_hasattr", "(", "viewlet", ",", "'render'", ")", ":", "raise", "zope", ".", "security", ".", "interfaces", ".", "Unauthorized", "(", "'You are not authorized to access the provider '", "'called `%s`.'", "%", "name", ")", "# Return the viewlet.", "return", "viewlet" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/manager.py#L32-L52
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/manager.py
python
ViewletManagerBase.filter
(self, viewlets)
return results
Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet).
Sort out all content providers
[ "Sort", "out", "all", "content", "providers" ]
def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet). """ results = [] # Only return viewlets accessible to the principal # We need to wrap each viewlet in its context to make sure that # the object has a real context from which to determine owner # security. for name, viewlet in viewlets: if guarded_hasattr(viewlet, 'render'): results.append((name, viewlet)) return results
[ "def", "filter", "(", "self", ",", "viewlets", ")", ":", "results", "=", "[", "]", "# Only return viewlets accessible to the principal", "# We need to wrap each viewlet in its context to make sure that", "# the object has a real context from which to determine owner", "# security.", "for", "name", ",", "viewlet", "in", "viewlets", ":", "if", "guarded_hasattr", "(", "viewlet", ",", "'render'", ")", ":", "results", ".", "append", "(", "(", "name", ",", "viewlet", ")", ")", "return", "results" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/manager.py#L54-L67
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/Five/viewlet/manager.py
python
ViewletManagerBase.sort
(self, viewlets)
Sort the viewlets. ``viewlets`` is a list of tuples of the form (name, viewlet).
Sort the viewlets.
[ "Sort", "the", "viewlets", "." ]
def sort(self, viewlets): """Sort the viewlets. ``viewlets`` is a list of tuples of the form (name, viewlet). """ # By default, use the standard Python way of doing sorting. Unwrap the # objects first so that they are sorted as expected. This is dumb # but it allows the tests to have deterministic results. try: # Try to sort by viewlet instances return sorted(viewlets, key=itemgetter(1)) except TypeError: # Fall back to viewlet names return sorted(viewlets, key=itemgetter(0))
[ "def", "sort", "(", "self", ",", "viewlets", ")", ":", "# By default, use the standard Python way of doing sorting. Unwrap the", "# objects first so that they are sorted as expected. This is dumb", "# but it allows the tests to have deterministic results.", "try", ":", "# Try to sort by viewlet instances", "return", "sorted", "(", "viewlets", ",", "key", "=", "itemgetter", "(", "1", ")", ")", "except", "TypeError", ":", "# Fall back to viewlet names", "return", "sorted", "(", "viewlets", ",", "key", "=", "itemgetter", "(", "0", ")", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/Five/viewlet/manager.py#L69-L83
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
boboAwareZopeTraverse
(object, path_items, econtext)
return object
Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness).
Traverses a sequence of names, first trying attributes then items.
[ "Traverses", "a", "sequence", "of", "names", "first", "trying", "attributes", "then", "items", "." ]
def boboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) validate = getSecurityManager().validate path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else: found = traversePathElement(object, name, path_items, request=request) # Special backwards compatibility exception for the name ``_``, # which was often used for translation message factories. # Allow and continue traversal. if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) object = found continue # All other names starting with ``_`` are disallowed. # This emulates what restrictedTraverse does. if name.startswith('_'): raise NotFound(name) # traversePathElement doesn't apply any Zope security policy, # so we validate access explicitly here. try: validate(object, object, name, found) object = found except Unauthorized: # Convert Unauthorized to prevent information disclosures raise NotFound(name) return object
[ "def", "boboAwareZopeTraverse", "(", "object", ",", "path_items", ",", "econtext", ")", ":", "request", "=", "getattr", "(", "econtext", ",", "'request'", ",", "None", ")", "validate", "=", "getSecurityManager", "(", ")", ".", "validate", "path_items", "=", "list", "(", "path_items", ")", "path_items", ".", "reverse", "(", ")", "while", "path_items", ":", "name", "=", "path_items", ".", "pop", "(", ")", "if", "OFS", ".", "interfaces", ".", "ITraversable", ".", "providedBy", "(", "object", ")", ":", "object", "=", "object", ".", "restrictedTraverse", "(", "name", ")", "else", ":", "found", "=", "traversePathElement", "(", "object", ",", "name", ",", "path_items", ",", "request", "=", "request", ")", "# Special backwards compatibility exception for the name ``_``,", "# which was often used for translation message factories.", "# Allow and continue traversal.", "if", "name", "==", "'_'", ":", "warnings", ".", "warn", "(", "'Traversing to the name `_` is deprecated '", "'and will be removed in Zope 6.'", ",", "DeprecationWarning", ")", "object", "=", "found", "continue", "# All other names starting with ``_`` are disallowed.", "# This emulates what restrictedTraverse does.", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "raise", "NotFound", "(", "name", ")", "# traversePathElement doesn't apply any Zope security policy,", "# so we validate access explicitly here.", "try", ":", "validate", "(", "object", ",", "object", ",", "name", ",", "found", ")", "object", "=", "found", "except", "Unauthorized", ":", "# Convert Unauthorized to prevent information disclosures", "raise", "NotFound", "(", "name", ")", "return", "object" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L66-L111
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
trustedBoboAwareZopeTraverse
(object, path_items, econtext)
return object
Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness).
Traverses a sequence of names, first trying attributes then items.
[ "Traverses", "a", "sequence", "of", "names", "first", "trying", "attributes", "then", "items", "." ]
def trustedBoboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.unrestrictedTraverse(name) else: object = traversePathElement(object, name, path_items, request=request) return object
[ "def", "trustedBoboAwareZopeTraverse", "(", "object", ",", "path_items", ",", "econtext", ")", ":", "request", "=", "getattr", "(", "econtext", ",", "'request'", ",", "None", ")", "path_items", "=", "list", "(", "path_items", ")", "path_items", ".", "reverse", "(", ")", "while", "path_items", ":", "name", "=", "path_items", ".", "pop", "(", ")", "if", "OFS", ".", "interfaces", ".", "ITraversable", ".", "providedBy", "(", "object", ")", ":", "object", "=", "object", ".", "unrestrictedTraverse", "(", "name", ")", "else", ":", "object", "=", "traversePathElement", "(", "object", ",", "name", ",", "path_items", ",", "request", "=", "request", ")", "return", "object" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L114-L132
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
render
(ob, ns)
return ob
Calls the object, possibly a document template, or just returns it if not callable. (From DT_Util.py)
Calls the object, possibly a document template, or just returns it if not callable. (From DT_Util.py)
[ "Calls", "the", "object", "possibly", "a", "document", "template", "or", "just", "returns", "it", "if", "not", "callable", ".", "(", "From", "DT_Util", ".", "py", ")" ]
def render(ob, ns): """Calls the object, possibly a document template, or just returns it if not callable. (From DT_Util.py) """ if hasattr(ob, '__render_with_namespace__'): ob = ZRPythonExpr.call_with_ns(ob.__render_with_namespace__, ns) else: # items might be acquisition wrapped base = aq_base(ob) # item might be proxied (e.g. modules might have a deprecation # proxy) base = removeAllProxies(base) if callable(base): try: if getattr(base, 'isDocTemp', 0): ob = ZRPythonExpr.call_with_ns(ob, ns, 2) else: ob = ob() except NotImplementedError: pass return ob
[ "def", "render", "(", "ob", ",", "ns", ")", ":", "if", "hasattr", "(", "ob", ",", "'__render_with_namespace__'", ")", ":", "ob", "=", "ZRPythonExpr", ".", "call_with_ns", "(", "ob", ".", "__render_with_namespace__", ",", "ns", ")", "else", ":", "# items might be acquisition wrapped", "base", "=", "aq_base", "(", "ob", ")", "# item might be proxied (e.g. modules might have a deprecation", "# proxy)", "base", "=", "removeAllProxies", "(", "base", ")", "if", "callable", "(", "base", ")", ":", "try", ":", "if", "getattr", "(", "base", ",", "'isDocTemp'", ",", "0", ")", ":", "ob", "=", "ZRPythonExpr", ".", "call_with_ns", "(", "ob", ",", "ns", ",", "2", ")", "else", ":", "ob", "=", "ob", "(", ")", "except", "NotImplementedError", ":", "pass", "return", "ob" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L135-L155
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
ZopeContext.evaluateStructure
(self, expr)
return self._handleText(text, expr)
customized version in order to get rid of unicode errors for all and ever
customized version in order to get rid of unicode errors for all and ever
[ "customized", "version", "in", "order", "to", "get", "rid", "of", "unicode", "errors", "for", "all", "and", "ever" ]
def evaluateStructure(self, expr): """ customized version in order to get rid of unicode errors for all and ever """ text = super().evaluateStructure(expr) return self._handleText(text, expr)
[ "def", "evaluateStructure", "(", "self", ",", "expr", ")", ":", "text", "=", "super", "(", ")", ".", "evaluateStructure", "(", "expr", ")", "return", "self", ".", "_handleText", "(", "text", ",", "expr", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L284-L289
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
ZopeContext.evaluateText
(self, expr)
return self._handleText(text, expr)
customized version in order to get rid of unicode errors for all and ever
customized version in order to get rid of unicode errors for all and ever
[ "customized", "version", "in", "order", "to", "get", "rid", "of", "unicode", "errors", "for", "all", "and", "ever" ]
def evaluateText(self, expr): """ customized version in order to get rid of unicode errors for all and ever """ text = self.evaluate(expr) return self._handleText(text, expr)
[ "def", "evaluateText", "(", "self", ",", "expr", ")", ":", "text", "=", "self", ".", "evaluate", "(", "expr", ")", "return", "self", ".", "_handleText", "(", "text", ",", "expr", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L291-L296
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/Expressions.py
python
ZopeContext.evaluateCode
(self, lang, code)
See ITALExpressionEngine. o This method is a fossil: nobody actually calls it, but the interface requires it.
See ITALExpressionEngine.
[ "See", "ITALExpressionEngine", "." ]
def evaluateCode(self, lang, code): """ See ITALExpressionEngine. o This method is a fossil: nobody actually calls it, but the interface requires it. """ raise NotImplementedError
[ "def", "evaluateCode", "(", "self", ",", "lang", ",", "code", ")", ":", "raise", "NotImplementedError" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/Expressions.py#L341-L347
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/interfaces.py
python
IUnicodeEncodingConflictResolver.resolve
(context, text, expression)
Returns 'text' as unicode string. 'context' is the current context object. 'expression' is the original expression (can be used for logging purposes)
Returns 'text' as unicode string. 'context' is the current context object. 'expression' is the original expression (can be used for logging purposes)
[ "Returns", "text", "as", "unicode", "string", ".", "context", "is", "the", "current", "context", "object", ".", "expression", "is", "the", "original", "expression", "(", "can", "be", "used", "for", "logging", "purposes", ")" ]
def resolve(context, text, expression): """ Returns 'text' as unicode string. 'context' is the current context object. 'expression' is the original expression (can be used for logging purposes) """
[ "def", "resolve", "(", "context", ",", "text", ",", "expression", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/interfaces.py#L24-L29
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/PageTemplateFile.py
python
PageTemplateFile._exec
(self, bound_names, args, kw)
Call a Page Template
Call a Page Template
[ "Call", "a", "Page", "Template" ]
def _exec(self, bound_names, args, kw): """Call a Page Template""" self._cook_check() if 'args' not in kw: kw['args'] = args bound_names['options'] = kw request = aq_get(self, 'REQUEST', None) if request is not None: response = request.response if 'content-type' not in response.headers: response.setHeader('content-type', self.content_type) # Execute the template in a new security context. security = getSecurityManager() bound_names['user'] = security.getUser() security.addContext(self) try: context = self.pt_getContext() context.update(bound_names) return self.pt_render(extra_context=bound_names) finally: security.removeContext(self)
[ "def", "_exec", "(", "self", ",", "bound_names", ",", "args", ",", "kw", ")", ":", "self", ".", "_cook_check", "(", ")", "if", "'args'", "not", "in", "kw", ":", "kw", "[", "'args'", "]", "=", "args", "bound_names", "[", "'options'", "]", "=", "kw", "request", "=", "aq_get", "(", "self", ",", "'REQUEST'", ",", "None", ")", "if", "request", "is", "not", "None", ":", "response", "=", "request", ".", "response", "if", "'content-type'", "not", "in", "response", ".", "headers", ":", "response", ".", "setHeader", "(", "'content-type'", ",", "self", ".", "content_type", ")", "# Execute the template in a new security context.", "security", "=", "getSecurityManager", "(", ")", "bound_names", "[", "'user'", "]", "=", "security", ".", "getUser", "(", ")", "security", ".", "addContext", "(", "self", ")", "try", ":", "context", "=", "self", ".", "pt_getContext", "(", ")", "context", ".", "update", "(", "bound_names", ")", "return", "self", ".", "pt_render", "(", "extra_context", "=", "bound_names", ")", "finally", ":", "security", ".", "removeContext", "(", "self", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/PageTemplateFile.py#L122-L145
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/PageTemplateFile.py
python
PageTemplateFile.pt_source_file
(self)
return self.__name__
Returns a file name to be compiled into the TAL code.
Returns a file name to be compiled into the TAL code.
[ "Returns", "a", "file", "name", "to", "be", "compiled", "into", "the", "TAL", "code", "." ]
def pt_source_file(self): """Returns a file name to be compiled into the TAL code.""" return self.__name__
[ "def", "pt_source_file", "(", "self", ")", ":", "return", "self", ".", "__name__" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/PageTemplateFile.py#L151-L153
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/PageTemplateFile.py
python
PageTemplateFile.document_src
(self, REQUEST=None, RESPONSE=None)
return self.read()
Return expanded document source.
Return expanded document source.
[ "Return", "expanded", "document", "source", "." ]
def document_src(self, REQUEST=None, RESPONSE=None): """Return expanded document source.""" if RESPONSE is not None: # Since _cook_check() can cause self.content_type to change, # we have to make sure we call it before setting the # Content-Type header. self._cook_check() RESPONSE.setHeader('Content-Type', 'text/plain') return self.read()
[ "def", "document_src", "(", "self", ",", "REQUEST", "=", "None", ",", "RESPONSE", "=", "None", ")", ":", "if", "RESPONSE", "is", "not", "None", ":", "# Since _cook_check() can cause self.content_type to change,", "# we have to make sure we call it before setting the", "# Content-Type header.", "self", ".", "_cook_check", "(", ")", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", "return", "self", ".", "read", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/PageTemplateFile.py#L205-L214
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/PageTemplateFile.py
python
PageTemplateFile.getOwner
(self, info=0)
return None
Gets the owner of the executable object. This method is required of all objects that go into the security context stack. Since this object came from the filesystem, it is owned by no one managed by Zope.
Gets the owner of the executable object.
[ "Gets", "the", "owner", "of", "the", "executable", "object", "." ]
def getOwner(self, info=0): """Gets the owner of the executable object. This method is required of all objects that go into the security context stack. Since this object came from the filesystem, it is owned by no one managed by Zope. """ return None
[ "def", "getOwner", "(", "self", ",", "info", "=", "0", ")", ":", "return", "None" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/PageTemplateFile.py#L225-L232
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/engine.py
python
_compile_zt_expr
(type, expression, engine=None, econtext=None)
return expr
compile *expression* of type *type*. The engine is derived either directly from *engine* or the execution content *econtext*. One of them must be given. The compilation result is cached in ``_zt_expr_registry``.
compile *expression* of type *type*.
[ "compile", "*", "expression", "*", "of", "type", "*", "type", "*", "." ]
def _compile_zt_expr(type, expression, engine=None, econtext=None): """compile *expression* of type *type*. The engine is derived either directly from *engine* or the execution content *econtext*. One of them must be given. The compilation result is cached in ``_zt_expr_registry``. """ if engine is None: engine = econtext["__zt_engine__"] key = id(engine), type, expression # cache lookup does not need to be protected by locking # (but we could potentially prevent unnecessary computations) expr = _zt_expr_registry.get(key) if expr is None: expr = engine.types[type](type, expression, engine) _zt_expr_registry[key] = expr return expr
[ "def", "_compile_zt_expr", "(", "type", ",", "expression", ",", "engine", "=", "None", ",", "econtext", "=", "None", ")", ":", "if", "engine", "is", "None", ":", "engine", "=", "econtext", "[", "\"__zt_engine__\"", "]", "key", "=", "id", "(", "engine", ")", ",", "type", ",", "expression", "# cache lookup does not need to be protected by locking", "# (but we could potentially prevent unnecessary computations)", "expr", "=", "_zt_expr_registry", ".", "get", "(", "key", ")", "if", "expr", "is", "None", ":", "expr", "=", "engine", ".", "types", "[", "type", "]", "(", "type", ",", "expression", ",", "engine", ")", "_zt_expr_registry", "[", "key", "]", "=", "expr", "return", "expr" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/engine.py#L126-L143
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/engine.py
python
_with_vars_from_chameleon
(context)
return ref(context)
prepare *context* to get its ``vars`` from ``chameleon``.
prepare *context* to get its ``vars`` from ``chameleon``.
[ "prepare", "*", "context", "*", "to", "get", "its", "vars", "from", "chameleon", "." ]
def _with_vars_from_chameleon(context): """prepare *context* to get its ``vars`` from ``chameleon``.""" cc = context.__class__ wc = _context_class_registry.get(cc) if wc is None: class ContextWrapper(_C2ZContextWrapperBase, cc): pass wc = _context_class_registry[cc] = ContextWrapper context.__class__ = wc return ref(context)
[ "def", "_with_vars_from_chameleon", "(", "context", ")", ":", "cc", "=", "context", ".", "__class__", "wc", "=", "_context_class_registry", ".", "get", "(", "cc", ")", "if", "wc", "is", "None", ":", "class", "ContextWrapper", "(", "_C2ZContextWrapperBase", ",", "cc", ")", ":", "pass", "wc", "=", "_context_class_registry", "[", "cc", "]", "=", "ContextWrapper", "context", ".", "__class__", "=", "wc", "return", "ref", "(", "context", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/engine.py#L153-L163
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/engine.py
python
RepeatDictWrapper.__call__
(self, key, iterable)
return ri, length
We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.
We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.
[ "We", "coerce", "the", "iterable", "to", "a", "tuple", "and", "return", "an", "iterator", "after", "registering", "it", "in", "the", "repeat", "dictionary", "." ]
def __call__(self, key, iterable): """We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.""" iterable = list(iterable) if iterable is not None else () length = len(iterable) # Insert as repeat item ri = self[key] = RepeatItem(None, iterable, _PseudoContext) return ri, length
[ "def", "__call__", "(", "self", ",", "key", ",", "iterable", ")", ":", "iterable", "=", "list", "(", "iterable", ")", "if", "iterable", "is", "not", "None", "else", "(", ")", "length", "=", "len", "(", "iterable", ")", "# Insert as repeat item", "ri", "=", "self", "[", "key", "]", "=", "RepeatItem", "(", "None", ",", "iterable", ",", "_PseudoContext", ")", "return", "ri", ",", "length" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/engine.py#L71-L81
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/engine.py
python
_C2ZContextWrapperBase.beginScope
(self, *args, **kw)
will not work as the scope is controlled by ``chameleon``.
will not work as the scope is controlled by ``chameleon``.
[ "will", "not", "work", "as", "the", "scope", "is", "controlled", "by", "chameleon", "." ]
def beginScope(self, *args, **kw): """will not work as the scope is controlled by ``chameleon``.""" raise NotImplementedError()
[ "def", "beginScope", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/engine.py#L211-L213
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
manage_addPageTemplate
(self, id, title='', text='', encoding='utf-8', submit=None, REQUEST=None, RESPONSE=None)
Add a Page Template with optional file content.
Add a Page Template with optional file content.
[ "Add", "a", "Page", "Template", "with", "optional", "file", "content", "." ]
def manage_addPageTemplate(self, id, title='', text='', encoding='utf-8', submit=None, REQUEST=None, RESPONSE=None): "Add a Page Template with optional file content." filename = '' content_type = 'text/html' if REQUEST and 'file' in REQUEST: file = REQUEST['file'] filename = file.filename text = file.read() headers = getattr(file, 'headers', None) if headers and 'content_type' in headers: content_type = headers['content_type'] else: content_type = guess_type(filename, text) else: if hasattr(text, 'read'): filename = getattr(text, 'filename', '') headers = getattr(text, 'headers', None) text = text.read() if headers and 'content_type' in headers: content_type = headers['content_type'] else: content_type = guess_type(filename, text) # ensure that we pass text_type to the constructor to # avoid further hassles with pt_edit() if not isinstance(text, str): text = text.decode(encoding) zpt = ZopePageTemplate(id, text, content_type, output_encoding=encoding) zpt.pt_setTitle(title, encoding) self._setObject(id, zpt) zpt = getattr(self, id) if RESPONSE: if submit == "Add and Edit": RESPONSE.redirect(zpt.absolute_url() + '/pt_editForm') else: RESPONSE.redirect(self.absolute_url() + '/manage_main') else: return zpt
[ "def", "manage_addPageTemplate", "(", "self", ",", "id", ",", "title", "=", "''", ",", "text", "=", "''", ",", "encoding", "=", "'utf-8'", ",", "submit", "=", "None", ",", "REQUEST", "=", "None", ",", "RESPONSE", "=", "None", ")", ":", "filename", "=", "''", "content_type", "=", "'text/html'", "if", "REQUEST", "and", "'file'", "in", "REQUEST", ":", "file", "=", "REQUEST", "[", "'file'", "]", "filename", "=", "file", ".", "filename", "text", "=", "file", ".", "read", "(", ")", "headers", "=", "getattr", "(", "file", ",", "'headers'", ",", "None", ")", "if", "headers", "and", "'content_type'", "in", "headers", ":", "content_type", "=", "headers", "[", "'content_type'", "]", "else", ":", "content_type", "=", "guess_type", "(", "filename", ",", "text", ")", "else", ":", "if", "hasattr", "(", "text", ",", "'read'", ")", ":", "filename", "=", "getattr", "(", "text", ",", "'filename'", ",", "''", ")", "headers", "=", "getattr", "(", "text", ",", "'headers'", ",", "None", ")", "text", "=", "text", ".", "read", "(", ")", "if", "headers", "and", "'content_type'", "in", "headers", ":", "content_type", "=", "headers", "[", "'content_type'", "]", "else", ":", "content_type", "=", "guess_type", "(", "filename", ",", "text", ")", "# ensure that we pass text_type to the constructor to", "# avoid further hassles with pt_edit()", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "text", ".", "decode", "(", "encoding", ")", "zpt", "=", "ZopePageTemplate", "(", "id", ",", "text", ",", "content_type", ",", "output_encoding", "=", "encoding", ")", "zpt", ".", "pt_setTitle", "(", "title", ",", "encoding", ")", "self", ".", "_setObject", "(", "id", ",", "zpt", ")", "zpt", "=", "getattr", "(", "self", ",", "id", ")", "if", "RESPONSE", ":", "if", "submit", "==", "\"Add and Edit\"", ":", "RESPONSE", ".", "redirect", "(", "zpt", ".", "absolute_url", "(", ")", "+", "'/pt_editForm'", ")", "else", ":", "RESPONSE", ".", "redirect", "(", "self", ".", "absolute_url", "(", ")", "+", "'/manage_main'", ")", "else", ":", "return", "zpt" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L370-L413
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.pt_editAction
(self, REQUEST, title, text, content_type, expand=0)
return self.pt_editForm(manage_tabs_message=message)
Change the title and document.
Change the title and document.
[ "Change", "the", "title", "and", "document", "." ]
def pt_editAction(self, REQUEST, title, text, content_type, expand=0): """Change the title and document.""" if self.wl_isLocked(): raise ResourceLockedError("File is locked.") self.expand = expand # The ZMI edit view uses utf-8! So we can safely assume # that 'title' and 'text' are utf-8 encoded strings - hopefully self.pt_setTitle(title, 'utf-8') self.pt_edit(text, content_type, True) REQUEST.set('text', self.read()) # May not equal 'text'! REQUEST.set('title', self.title) message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.pt_editForm(manage_tabs_message=message)
[ "def", "pt_editAction", "(", "self", ",", "REQUEST", ",", "title", ",", "text", ",", "content_type", ",", "expand", "=", "0", ")", ":", "if", "self", ".", "wl_isLocked", "(", ")", ":", "raise", "ResourceLockedError", "(", "\"File is locked.\"", ")", "self", ".", "expand", "=", "expand", "# The ZMI edit view uses utf-8! So we can safely assume", "# that 'title' and 'text' are utf-8 encoded strings - hopefully", "self", ".", "pt_setTitle", "(", "title", ",", "'utf-8'", ")", "self", ".", "pt_edit", "(", "text", ",", "content_type", ",", "True", ")", "REQUEST", ".", "set", "(", "'text'", ",", "self", ".", "read", "(", ")", ")", "# May not equal 'text'!", "REQUEST", ".", "set", "(", "'title'", ",", "self", ".", "title", ")", "message", "=", "\"Saved changes.\"", "if", "getattr", "(", "self", ",", "'_v_warnings'", ",", "None", ")", ":", "message", "=", "(", "\"<strong>Warning:</strong> <i>%s</i>\"", "%", "'<br>'", ".", "join", "(", "self", ".", "_v_warnings", ")", ")", "return", "self", ".", "pt_editForm", "(", "manage_tabs_message", "=", "message", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L149-L168
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate._setPropValue
(self, id, value)
set a property and invalidate the cache
set a property and invalidate the cache
[ "set", "a", "property", "and", "invalidate", "the", "cache" ]
def _setPropValue(self, id, value): """ set a property and invalidate the cache """ PropertyManager._setPropValue(self, id, value) self.ZCacheable_invalidate()
[ "def", "_setPropValue", "(", "self", ",", "id", ",", "value", ")", ":", "PropertyManager", ".", "_setPropValue", "(", "self", ",", "id", ",", "value", ")", "self", ".", "ZCacheable_invalidate", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L176-L179
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.pt_upload
(self, REQUEST, file='', encoding='utf-8')
return self.pt_editForm(manage_tabs_message='Saved changes')
Replace the document with the text in file.
Replace the document with the text in file.
[ "Replace", "the", "document", "with", "the", "text", "in", "file", "." ]
def pt_upload(self, REQUEST, file='', encoding='utf-8'): """Replace the document with the text in file.""" if self.wl_isLocked(): raise ResourceLockedError("File is locked.") if not file: return self.pt_editForm(manage_tabs_message='No file specified', manage_tabs_type='warning') if hasattr(file, 'read'): text = file.read() filename = file.filename else: filename = None text = file if isinstance(text, bytes): content_type = guess_type(filename, text) (text, source_encoding) = convertToUnicode(text, content_type, preferred_encodings) elif isinstance(text, str): content_type = guess_type(filename, text.encode('utf-8')) self.pt_edit(text, content_type) return self.pt_editForm(manage_tabs_message='Saved changes')
[ "def", "pt_upload", "(", "self", ",", "REQUEST", ",", "file", "=", "''", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "self", ".", "wl_isLocked", "(", ")", ":", "raise", "ResourceLockedError", "(", "\"File is locked.\"", ")", "if", "not", "file", ":", "return", "self", ".", "pt_editForm", "(", "manage_tabs_message", "=", "'No file specified'", ",", "manage_tabs_type", "=", "'warning'", ")", "if", "hasattr", "(", "file", ",", "'read'", ")", ":", "text", "=", "file", ".", "read", "(", ")", "filename", "=", "file", ".", "filename", "else", ":", "filename", "=", "None", "text", "=", "file", "if", "isinstance", "(", "text", ",", "bytes", ")", ":", "content_type", "=", "guess_type", "(", "filename", ",", "text", ")", "(", "text", ",", "source_encoding", ")", "=", "convertToUnicode", "(", "text", ",", "content_type", ",", "preferred_encodings", ")", "elif", "isinstance", "(", "text", ",", "str", ")", ":", "content_type", "=", "guess_type", "(", "filename", ",", "text", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "pt_edit", "(", "text", ",", "content_type", ")", "return", "self", ".", "pt_editForm", "(", "manage_tabs_message", "=", "'Saved changes'", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L182-L208
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.ZScriptHTML_tryParams
(self)
return []
Parameters to test the script with.
Parameters to test the script with.
[ "Parameters", "to", "test", "the", "script", "with", "." ]
def ZScriptHTML_tryParams(self): """Parameters to test the script with.""" return []
[ "def", "ZScriptHTML_tryParams", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L210-L212
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate._exec
(self, bound_names, args, kw)
Call a Page Template
Call a Page Template
[ "Call", "a", "Page", "Template" ]
def _exec(self, bound_names, args, kw): """Call a Page Template""" if 'args' not in kw: kw['args'] = args bound_names['options'] = kw request = aq_get(self, 'REQUEST', None) if request is not None: response = request.response if 'content-type' not in response.headers: response.setHeader('content-type', self.content_type) security = getSecurityManager() bound_names['user'] = security.getUser() # Retrieve the value from the cache. keyset = None if self.ZCacheable_isCachingEnabled(): # Prepare a cache key. keyset = {'here': self._getContext(), 'bound_names': bound_names} result = self.ZCacheable_get(keywords=keyset) if result is not None: # Got a cached value. return result # Execute the template in a new security context. security.addContext(self) try: result = self.pt_render(extra_context=bound_names) if keyset is not None: # Store the result in the cache. self.ZCacheable_set(result, keywords=keyset) return result finally: security.removeContext(self)
[ "def", "_exec", "(", "self", ",", "bound_names", ",", "args", ",", "kw", ")", ":", "if", "'args'", "not", "in", "kw", ":", "kw", "[", "'args'", "]", "=", "args", "bound_names", "[", "'options'", "]", "=", "kw", "request", "=", "aq_get", "(", "self", ",", "'REQUEST'", ",", "None", ")", "if", "request", "is", "not", "None", ":", "response", "=", "request", ".", "response", "if", "'content-type'", "not", "in", "response", ".", "headers", ":", "response", ".", "setHeader", "(", "'content-type'", ",", "self", ".", "content_type", ")", "security", "=", "getSecurityManager", "(", ")", "bound_names", "[", "'user'", "]", "=", "security", ".", "getUser", "(", ")", "# Retrieve the value from the cache.", "keyset", "=", "None", "if", "self", ".", "ZCacheable_isCachingEnabled", "(", ")", ":", "# Prepare a cache key.", "keyset", "=", "{", "'here'", ":", "self", ".", "_getContext", "(", ")", ",", "'bound_names'", ":", "bound_names", "}", "result", "=", "self", ".", "ZCacheable_get", "(", "keywords", "=", "keyset", ")", "if", "result", "is", "not", "None", ":", "# Got a cached value.", "return", "result", "# Execute the template in a new security context.", "security", ".", "addContext", "(", "self", ")", "try", ":", "result", "=", "self", ".", "pt_render", "(", "extra_context", "=", "bound_names", ")", "if", "keyset", "is", "not", "None", ":", "# Store the result in the cache.", "self", ".", "ZCacheable_set", "(", "result", ",", "keywords", "=", "keyset", ")", "return", "result", "finally", ":", "security", ".", "removeContext", "(", "self", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L249-L285
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.PrincipiaSearchSource
(self)
return self.read()
Support for searching - the document's contents are searched.
Support for searching - the document's contents are searched.
[ "Support", "for", "searching", "-", "the", "document", "s", "contents", "are", "searched", "." ]
def PrincipiaSearchSource(self): "Support for searching - the document's contents are searched." return self.read()
[ "def", "PrincipiaSearchSource", "(", "self", ")", ":", "return", "self", ".", "read", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L305-L307
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.document_src
(self, REQUEST=None, RESPONSE=None)
return self.read()
Return expanded document source.
Return expanded document source.
[ "Return", "expanded", "document", "source", "." ]
def document_src(self, REQUEST=None, RESPONSE=None): """Return expanded document source.""" if RESPONSE is not None: RESPONSE.setHeader('Content-Type', 'text/plain') if REQUEST is not None and REQUEST.get('raw'): return self._text return self.read()
[ "def", "document_src", "(", "self", ",", "REQUEST", "=", "None", ",", "RESPONSE", "=", "None", ")", ":", "if", "RESPONSE", "is", "not", "None", ":", "RESPONSE", ".", "setHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", "if", "REQUEST", "is", "not", "None", "and", "REQUEST", ".", "get", "(", "'raw'", ")", ":", "return", "self", ".", "_text", "return", "self", ".", "read", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L310-L316
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.pt_source_file
(self)
Returns a file name to be compiled into the TAL code.
Returns a file name to be compiled into the TAL code.
[ "Returns", "a", "file", "name", "to", "be", "compiled", "into", "the", "TAL", "code", "." ]
def pt_source_file(self): """Returns a file name to be compiled into the TAL code.""" try: return '/'.join(self.getPhysicalPath()) except Exception: # This page template is being compiled without an # acquisition context, so we don't know where it is. :-( return None
[ "def", "pt_source_file", "(", "self", ")", ":", "try", ":", "return", "'/'", ".", "join", "(", "self", ".", "getPhysicalPath", "(", ")", ")", "except", "Exception", ":", "# This page template is being compiled without an", "# acquisition context, so we don't know where it is. :-(", "return", "None" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L319-L326
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.PUT
(self, REQUEST, RESPONSE)
return RESPONSE
Handle HTTP PUT requests
Handle HTTP PUT requests
[ "Handle", "HTTP", "PUT", "requests" ]
def PUT(self, REQUEST, RESPONSE): """ Handle HTTP PUT requests """ self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) text = REQUEST.get('BODY', '') content_type = guess_type('', text) self.pt_edit(text, content_type) RESPONSE.setStatus(204) return RESPONSE
[ "def", "PUT", "(", "self", ",", "REQUEST", ",", "RESPONSE", ")", ":", "self", ".", "dav__init", "(", "REQUEST", ",", "RESPONSE", ")", "self", ".", "dav__simpleifhandler", "(", "REQUEST", ",", "RESPONSE", ",", "refresh", "=", "1", ")", "text", "=", "REQUEST", ".", "get", "(", "'BODY'", ",", "''", ")", "content_type", "=", "guess_type", "(", "''", ",", "text", ")", "self", ".", "pt_edit", "(", "text", ",", "content_type", ")", "RESPONSE", ".", "setStatus", "(", "204", ")", "return", "RESPONSE" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/ZopePageTemplate.py#L348-L357
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/utils.py
python
encodingFromXMLPreamble
(xml, default=DEFAULT_ENCODING)
return encoding.decode('ascii')
Extract the encoding from a xml preamble. Expects XML content is binary (encoded), otherwise a previous transport encoding is meaningless. Return 'utf-8' if not available
Extract the encoding from a xml preamble. Expects XML content is binary (encoded), otherwise a previous transport encoding is meaningless. Return 'utf-8' if not available
[ "Extract", "the", "encoding", "from", "a", "xml", "preamble", ".", "Expects", "XML", "content", "is", "binary", "(", "encoded", ")", "otherwise", "a", "previous", "transport", "encoding", "is", "meaningless", ".", "Return", "utf", "-", "8", "if", "not", "available" ]
def encodingFromXMLPreamble(xml, default=DEFAULT_ENCODING): """ Extract the encoding from a xml preamble. Expects XML content is binary (encoded), otherwise a previous transport encoding is meaningless. Return 'utf-8' if not available """ match = xml_preamble_reg.match(xml) if not match: return default encoding = match.group(1).lower() return encoding.decode('ascii')
[ "def", "encodingFromXMLPreamble", "(", "xml", ",", "default", "=", "DEFAULT_ENCODING", ")", ":", "match", "=", "xml_preamble_reg", ".", "match", "(", "xml", ")", "if", "not", "match", ":", "return", "default", "encoding", "=", "match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "return", "encoding", ".", "decode", "(", "'ascii'", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/utils.py#L29-L41
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/utils.py
python
charsetFromMetaEquiv
(html)
return None
Return the value of the 'charset' from a html document containing <meta http-equiv="content-type" content="text/html; charset=utf8>. Expects HTML content is binary (encoded), otherwise a previous transport encoding is meaningless. Returns None, if not available.
Return the value of the 'charset' from a html document containing <meta http-equiv="content-type" content="text/html; charset=utf8>. Expects HTML content is binary (encoded), otherwise a previous transport encoding is meaningless. Returns None, if not available.
[ "Return", "the", "value", "of", "the", "charset", "from", "a", "html", "document", "containing", "<meta", "http", "-", "equiv", "=", "content", "-", "type", "content", "=", "text", "/", "html", ";", "charset", "=", "utf8", ">", ".", "Expects", "HTML", "content", "is", "binary", "(", "encoded", ")", "otherwise", "a", "previous", "transport", "encoding", "is", "meaningless", ".", "Returns", "None", "if", "not", "available", "." ]
def charsetFromMetaEquiv(html): """ Return the value of the 'charset' from a html document containing <meta http-equiv="content-type" content="text/html; charset=utf8>. Expects HTML content is binary (encoded), otherwise a previous transport encoding is meaningless. Returns None, if not available. """ meta_tag_match = http_equiv_reg.search(html) if meta_tag_match: meta_tag = meta_tag_match.group(1) charset_match = http_equiv_reg2.search(meta_tag) if charset_match: charset = charset_match.group(1).lower() return charset.decode('ascii') return None
[ "def", "charsetFromMetaEquiv", "(", "html", ")", ":", "meta_tag_match", "=", "http_equiv_reg", ".", "search", "(", "html", ")", "if", "meta_tag_match", ":", "meta_tag", "=", "meta_tag_match", ".", "group", "(", "1", ")", "charset_match", "=", "http_equiv_reg2", ".", "search", "(", "meta_tag", ")", "if", "charset_match", ":", "charset", "=", "charset_match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "return", "charset", ".", "decode", "(", "'ascii'", ")", "return", "None" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/utils.py#L44-L61
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/utils.py
python
convertToUnicode
(source, content_type, preferred_encodings)
return source.decode('utf-8'), 'utf-8'
Convert a binary 'source' to the unicode (text) type. Attempts to detect transport encoding from XML and html documents, falling back to preferred_encodings. Returns (unicode_str, source_encoding).
Convert a binary 'source' to the unicode (text) type. Attempts to detect transport encoding from XML and html documents, falling back to preferred_encodings. Returns (unicode_str, source_encoding).
[ "Convert", "a", "binary", "source", "to", "the", "unicode", "(", "text", ")", "type", ".", "Attempts", "to", "detect", "transport", "encoding", "from", "XML", "and", "html", "documents", "falling", "back", "to", "preferred_encodings", ".", "Returns", "(", "unicode_str", "source_encoding", ")", "." ]
def convertToUnicode(source, content_type, preferred_encodings): """ Convert a binary 'source' to the unicode (text) type. Attempts to detect transport encoding from XML and html documents, falling back to preferred_encodings. Returns (unicode_str, source_encoding). """ if content_type.startswith('text/xml'): encoding = encodingFromXMLPreamble(source) return source.decode(encoding), encoding elif content_type.startswith('text/html'): encoding = charsetFromMetaEquiv(source) if encoding: return source.decode(encoding), encoding # Try to detect the encoding by converting it unicode without raising # exceptions. There are some smarter Python-based sniffer methods # available however we have to check their licenses first before # including them into the Zope 2 core for enc in preferred_encodings: try: return source.decode(enc), enc except UnicodeDecodeError: continue # trigger a UnicodeDecodeError so we fail loudly return source.decode('utf-8'), 'utf-8'
[ "def", "convertToUnicode", "(", "source", ",", "content_type", ",", "preferred_encodings", ")", ":", "if", "content_type", ".", "startswith", "(", "'text/xml'", ")", ":", "encoding", "=", "encodingFromXMLPreamble", "(", "source", ")", "return", "source", ".", "decode", "(", "encoding", ")", ",", "encoding", "elif", "content_type", ".", "startswith", "(", "'text/html'", ")", ":", "encoding", "=", "charsetFromMetaEquiv", "(", "source", ")", "if", "encoding", ":", "return", "source", ".", "decode", "(", "encoding", ")", ",", "encoding", "# Try to detect the encoding by converting it unicode without raising", "# exceptions. There are some smarter Python-based sniffer methods", "# available however we have to check their licenses first before", "# including them into the Zope 2 core", "for", "enc", "in", "preferred_encodings", ":", "try", ":", "return", "source", ".", "decode", "(", "enc", ")", ",", "enc", "except", "UnicodeDecodeError", ":", "continue", "# trigger a UnicodeDecodeError so we fail loudly", "return", "source", ".", "decode", "(", "'utf-8'", ")", ",", "'utf-8'" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/utils.py#L64-L92
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Products/PageTemplates/expression.py
python
BoboAwareZopeTraverse.traverse
(cls, base, request, path_items)
return base
See ``zope.app.pagetemplate.engine``.
See ``zope.app.pagetemplate.engine``.
[ "See", "zope", ".", "app", ".", "pagetemplate", ".", "engine", "." ]
def traverse(cls, base, request, path_items): """See ``zope.app.pagetemplate.engine``.""" validate = getSecurityManager().validate path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if ITraversable.providedBy(base): base = getattr(base, cls.traverse_method)(name) else: found = traversePathElement(base, name, path_items, request=request) # If traverse_method is something other than # ``restrictedTraverse`` then traversal is assumed to be # unrestricted. This emulates ``unrestrictedTraverse`` if cls.traverse_method != 'restrictedTraverse': base = found continue # Special backwards compatibility exception for the name ``_``, # which was often used for translation message factories. # Allow and continue traversal. if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) base = found continue # All other names starting with ``_`` are disallowed. # This emulates what restrictedTraverse does. if name.startswith('_'): raise NotFound(name) # traversePathElement doesn't apply any Zope security policy, # so we validate access explicitly here. try: validate(base, base, name, found) base = found except Unauthorized: # Convert Unauthorized to prevent information disclosures raise NotFound(name) return base
[ "def", "traverse", "(", "cls", ",", "base", ",", "request", ",", "path_items", ")", ":", "validate", "=", "getSecurityManager", "(", ")", ".", "validate", "path_items", "=", "list", "(", "path_items", ")", "path_items", ".", "reverse", "(", ")", "while", "path_items", ":", "name", "=", "path_items", ".", "pop", "(", ")", "if", "ITraversable", ".", "providedBy", "(", "base", ")", ":", "base", "=", "getattr", "(", "base", ",", "cls", ".", "traverse_method", ")", "(", "name", ")", "else", ":", "found", "=", "traversePathElement", "(", "base", ",", "name", ",", "path_items", ",", "request", "=", "request", ")", "# If traverse_method is something other than", "# ``restrictedTraverse`` then traversal is assumed to be", "# unrestricted. This emulates ``unrestrictedTraverse``", "if", "cls", ".", "traverse_method", "!=", "'restrictedTraverse'", ":", "base", "=", "found", "continue", "# Special backwards compatibility exception for the name ``_``,", "# which was often used for translation message factories.", "# Allow and continue traversal.", "if", "name", "==", "'_'", ":", "warnings", ".", "warn", "(", "'Traversing to the name `_` is deprecated '", "'and will be removed in Zope 6.'", ",", "DeprecationWarning", ")", "base", "=", "found", "continue", "# All other names starting with ``_`` are disallowed.", "# This emulates what restrictedTraverse does.", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "raise", "NotFound", "(", "name", ")", "# traversePathElement doesn't apply any Zope security policy,", "# so we validate access explicitly here.", "try", ":", "validate", "(", "base", ",", "base", ",", "name", ",", "found", ")", "base", "=", "found", "except", "Unauthorized", ":", "# Convert Unauthorized to prevent information disclosures", "raise", "NotFound", "(", "name", ")", "return", "base" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Products/PageTemplates/expression.py#L58-L105
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/__init__.py
python
startup_wsgi
()
Initialize the Zope Package and provide a published module
Initialize the Zope Package and provide a published module
[ "Initialize", "the", "Zope", "Package", "and", "provide", "a", "published", "module" ]
def startup_wsgi(): """Initialize the Zope Package and provide a published module""" global _began_startup if _began_startup: # Already began (and maybe finished) startup, so don't run again return _began_startup = 1 _configure_wsgi() from Zope2.App.startup import startup as _startup _startup()
[ "def", "startup_wsgi", "(", ")", ":", "global", "_began_startup", "if", "_began_startup", ":", "# Already began (and maybe finished) startup, so don't run again", "return", "_began_startup", "=", "1", "_configure_wsgi", "(", ")", "from", "Zope2", ".", "App", ".", "startup", "import", "startup", "as", "_startup", "_startup", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/__init__.py#L27-L36
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/__init__.py
python
app
(*args, **kw)
return bobo_application(*args, **kw)
Utility for scripts to open a connection to the database
Utility for scripts to open a connection to the database
[ "Utility", "for", "scripts", "to", "open", "a", "connection", "to", "the", "database" ]
def app(*args, **kw): """Utility for scripts to open a connection to the database""" startup_wsgi() return bobo_application(*args, **kw)
[ "def", "app", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "startup_wsgi", "(", ")", "return", "bobo_application", "(", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/__init__.py#L39-L42
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/__init__.py
python
debug
(*args, **kw)
return ZPublisher.test('Zope2', *args, **kw)
Utility to try a Zope request using the interactive interpreter
Utility to try a Zope request using the interactive interpreter
[ "Utility", "to", "try", "a", "Zope", "request", "using", "the", "interactive", "interpreter" ]
def debug(*args, **kw): """Utility to try a Zope request using the interactive interpreter""" startup_wsgi() import ZPublisher return ZPublisher.test('Zope2', *args, **kw)
[ "def", "debug", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "startup_wsgi", "(", ")", "import", "ZPublisher", "return", "ZPublisher", ".", "test", "(", "'Zope2'", ",", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/__init__.py#L45-L49
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/run.py
python
configure_wsgi
(configfile)
return starter
Provide an API which allows scripts to configure Zope before attempting to do 'app = Zope2.app(). Should be used as follows: from Zope2.Startup.run import configure_wsgi; configure_wsgi('/path/to/configfile'); import Zope2; app = Zope2.app()
Provide an API which allows scripts to configure Zope before attempting to do 'app = Zope2.app(). Should be used as follows: from Zope2.Startup.run import configure_wsgi; configure_wsgi('/path/to/configfile'); import Zope2; app = Zope2.app()
[ "Provide", "an", "API", "which", "allows", "scripts", "to", "configure", "Zope", "before", "attempting", "to", "do", "app", "=", "Zope2", ".", "app", "()", ".", "Should", "be", "used", "as", "follows", ":", "from", "Zope2", ".", "Startup", ".", "run", "import", "configure_wsgi", ";", "configure_wsgi", "(", "/", "path", "/", "to", "/", "configfile", ")", ";", "import", "Zope2", ";", "app", "=", "Zope2", ".", "app", "()" ]
def configure_wsgi(configfile): """ Provide an API which allows scripts to configure Zope before attempting to do 'app = Zope2.app(). Should be used as follows: from Zope2.Startup.run import configure_wsgi; configure_wsgi('/path/to/configfile'); import Zope2; app = Zope2.app() """ import Zope2.Startup starter = Zope2.Startup.get_wsgi_starter() opts = _set_wsgi_config(configfile) starter.setConfiguration(opts.configroot) starter.setupSecurityOptions() return starter
[ "def", "configure_wsgi", "(", "configfile", ")", ":", "import", "Zope2", ".", "Startup", "starter", "=", "Zope2", ".", "Startup", ".", "get_wsgi_starter", "(", ")", "opts", "=", "_set_wsgi_config", "(", "configfile", ")", "starter", ".", "setConfiguration", "(", "opts", ".", "configroot", ")", "starter", ".", "setupSecurityOptions", "(", ")", "return", "starter" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/run.py#L16-L28
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/run.py
python
_set_wsgi_config
(configfile=None)
return opts
Configure a Zope instance based on ZopeWSGIOptions. Optionally accept a configfile argument (string path) in order to specify where the configuration file exists.
Configure a Zope instance based on ZopeWSGIOptions. Optionally accept a configfile argument (string path) in order to specify where the configuration file exists.
[ "Configure", "a", "Zope", "instance", "based", "on", "ZopeWSGIOptions", ".", "Optionally", "accept", "a", "configfile", "argument", "(", "string", "path", ")", "in", "order", "to", "specify", "where", "the", "configuration", "file", "exists", "." ]
def _set_wsgi_config(configfile=None): """ Configure a Zope instance based on ZopeWSGIOptions. Optionally accept a configfile argument (string path) in order to specify where the configuration file exists. """ from Zope2.Startup import handlers from Zope2.Startup import options opts = options.ZopeWSGIOptions(configfile=configfile)() handlers.handleWSGIConfig(opts.configroot, opts.confighandlers) import App.config App.config.setConfiguration(opts.configroot) return opts
[ "def", "_set_wsgi_config", "(", "configfile", "=", "None", ")", ":", "from", "Zope2", ".", "Startup", "import", "handlers", "from", "Zope2", ".", "Startup", "import", "options", "opts", "=", "options", ".", "ZopeWSGIOptions", "(", "configfile", "=", "configfile", ")", "(", ")", "handlers", ".", "handleWSGIConfig", "(", "opts", ".", "configroot", ",", "opts", ".", "confighandlers", ")", "import", "App", ".", "config", "App", ".", "config", ".", "setConfiguration", "(", "opts", ".", "configroot", ")", "return", "opts" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/run.py#L31-L41
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
simpleClassFactory
(jar, module, name, _silly=('__doc__',), _globals={})
return getattr(m, name)
Class factory.
Class factory.
[ "Class", "factory", "." ]
def simpleClassFactory(jar, module, name, _silly=('__doc__',), _globals={}): """Class factory. """ m = __import__(module, _globals, _globals, _silly) return getattr(m, name)
[ "def", "simpleClassFactory", "(", "jar", ",", "module", ",", "name", ",", "_silly", "=", "(", "'__doc__'", ",", ")", ",", "_globals", "=", "{", "}", ")", ":", "m", "=", "__import__", "(", "module", ",", "_globals", ",", "_globals", ",", "_silly", ")", "return", "getattr", "(", "m", ",", "name", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L262-L266
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
ZopeDatabase.getMountParams
(self, mount_path)
Returns (real_root, real_path, container_class) for a virtual mount path.
Returns (real_root, real_path, container_class) for a virtual mount path.
[ "Returns", "(", "real_root", "real_path", "container_class", ")", "for", "a", "virtual", "mount", "path", "." ]
def getMountParams(self, mount_path): """Returns (real_root, real_path, container_class) for a virtual mount path. """ for (virtual_path, real_root, real_path) in self.computeMountPaths(): if virtual_path == mount_path: container_class = self.config.container_class if not container_class and virtual_path != '/': # default to OFS.Folder.Folder for nonroot mounts # if one isn't specified in the config container_class = 'OFS.Folder.Folder' return (real_root, real_path, container_class) raise LookupError('Nothing known about mount path %s' % mount_path)
[ "def", "getMountParams", "(", "self", ",", "mount_path", ")", ":", "for", "(", "virtual_path", ",", "real_root", ",", "real_path", ")", "in", "self", ".", "computeMountPaths", "(", ")", ":", "if", "virtual_path", "==", "mount_path", ":", "container_class", "=", "self", ".", "config", ".", "container_class", "if", "not", "container_class", "and", "virtual_path", "!=", "'/'", ":", "# default to OFS.Folder.Folder for nonroot mounts", "# if one isn't specified in the config", "container_class", "=", "'OFS.Folder.Folder'", "return", "(", "real_root", ",", "real_path", ",", "container_class", ")", "raise", "LookupError", "(", "'Nothing known about mount path %s'", "%", "mount_path", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L172-L184
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
DBTab.listMountPaths
(self)
return list(self.mount_paths.items())
Returns a sequence of (virtual_mount_path, database_name).
Returns a sequence of (virtual_mount_path, database_name).
[ "Returns", "a", "sequence", "of", "(", "virtual_mount_path", "database_name", ")", "." ]
def listMountPaths(self): """Returns a sequence of (virtual_mount_path, database_name). """ return list(self.mount_paths.items())
[ "def", "listMountPaths", "(", "self", ")", ":", "return", "list", "(", "self", ".", "mount_paths", ".", "items", "(", ")", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L213-L216
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
DBTab.listDatabaseNames
(self)
return list(self.db_factories.keys())
Returns a sequence of names.
Returns a sequence of names.
[ "Returns", "a", "sequence", "of", "names", "." ]
def listDatabaseNames(self): """Returns a sequence of names. """ return list(self.db_factories.keys())
[ "def", "listDatabaseNames", "(", "self", ")", ":", "return", "list", "(", "self", ".", "db_factories", ".", "keys", "(", ")", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L218-L221
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
DBTab.hasDatabase
(self, name)
return name in self.db_factories
Returns true if name is the name of a configured database.
Returns true if name is the name of a configured database.
[ "Returns", "true", "if", "name", "is", "the", "name", "of", "a", "configured", "database", "." ]
def hasDatabase(self, name): """Returns true if name is the name of a configured database.""" return name in self.db_factories
[ "def", "hasDatabase", "(", "self", ",", "name", ")", ":", "return", "name", "in", "self", ".", "db_factories" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L223-L225
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/datatypes.py
python
DBTab.getDatabase
(self, mount_path=None, name=None, is_root=0)
return db
Returns an opened database. Requires either mount_path or name.
Returns an opened database. Requires either mount_path or name.
[ "Returns", "an", "opened", "database", ".", "Requires", "either", "mount_path", "or", "name", "." ]
def getDatabase(self, mount_path=None, name=None, is_root=0): """Returns an opened database. Requires either mount_path or name. """ if name is None: name = self.getName(mount_path) db = self.databases.get(name, None) if db is None: factory = self.getDatabaseFactory(name=name) db = factory.open(name, self.databases) return db
[ "def", "getDatabase", "(", "self", ",", "mount_path", "=", "None", ",", "name", "=", "None", ",", "is_root", "=", "0", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "getName", "(", "mount_path", ")", "db", "=", "self", ".", "databases", ".", "get", "(", "name", ",", "None", ")", "if", "db", "is", "None", ":", "factory", "=", "self", ".", "getDatabaseFactory", "(", "name", "=", "name", ")", "db", "=", "factory", ".", "open", "(", "name", ",", "self", ".", "databases", ")", "return", "db" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/datatypes.py#L237-L246
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/handlers.py
python
_name_to_ips
(host)
return [str(ip)]
Map a name *host* to the sequence of its IP addresses. Use *host* itself (as sequence) if it already is an IP address. Thus, if only a specific interface on a host is trusted, identify it by its IP (and not the host name).
Map a name *host* to the sequence of its IP addresses.
[ "Map", "a", "name", "*", "host", "*", "to", "the", "sequence", "of", "its", "IP", "addresses", "." ]
def _name_to_ips(host): """Map a name *host* to the sequence of its IP addresses. Use *host* itself (as sequence) if it already is an IP address. Thus, if only a specific interface on a host is trusted, identify it by its IP (and not the host name). """ if isinstance(host, bytes): host = host.decode('utf-8') try: ip = ipaddress.ip_address(host) except ValueError: return gethostbyaddr(host)[2] return [str(ip)]
[ "def", "_name_to_ips", "(", "host", ")", ":", "if", "isinstance", "(", "host", ",", "bytes", ")", ":", "host", "=", "host", ".", "decode", "(", "'utf-8'", ")", "try", ":", "ip", "=", "ipaddress", ".", "ip_address", "(", "host", ")", "except", "ValueError", ":", "return", "gethostbyaddr", "(", "host", ")", "[", "2", "]", "return", "[", "str", "(", "ip", ")", "]" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/handlers.py#L71-L84
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/serve.py
python
parse_vars
(args)
return result
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}``
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}``
[ "Given", "variables", "like", "[", "a", "=", "b", "c", "=", "d", "]", "turns", "it", "into", "{", "a", ":", "b", "c", ":", "d", "}" ]
def parse_vars(args): """ Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}`` """ result = {} for arg in args: if '=' not in arg: raise ValueError( 'Variable assignment %r invalid (no "=")' % arg) name, value = arg.split('=', 1) result[name] = value return result
[ "def", "parse_vars", "(", "args", ")", ":", "result", "=", "{", "}", "for", "arg", "in", "args", ":", "if", "'='", "not", "in", "arg", ":", "raise", "ValueError", "(", "'Variable assignment %r invalid (no \"=\")'", "%", "arg", ")", "name", ",", "value", "=", "arg", ".", "split", "(", "'='", ",", "1", ")", "result", "[", "name", "]", "=", "value", "return", "result" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/serve.py#L31-L44
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/Startup/serve.py
python
setup_logging
(config_uri, global_conf=None, # NOQA fileConfig=fileConfig, configparser=configparser)
Set up logging via :func:`logging.config.fileConfig` with the filename specified via ``config_uri`` (a string in the form ``filename#sectionname``). ConfigParser defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. Extra defaults can optionally be specified as a dict in ``global_conf``.
Set up logging via :func:`logging.config.fileConfig` with the filename specified via ``config_uri`` (a string in the form ``filename#sectionname``). ConfigParser defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. Extra defaults can optionally be specified as a dict in ``global_conf``.
[ "Set", "up", "logging", "via", ":", "func", ":", "logging", ".", "config", ".", "fileConfig", "with", "the", "filename", "specified", "via", "config_uri", "(", "a", "string", "in", "the", "form", "filename#sectionname", ")", ".", "ConfigParser", "defaults", "are", "specified", "for", "the", "special", "__file__", "and", "here", "variables", "similar", "to", "PasteDeploy", "config", "loading", ".", "Extra", "defaults", "can", "optionally", "be", "specified", "as", "a", "dict", "in", "global_conf", "." ]
def setup_logging(config_uri, global_conf=None, # NOQA fileConfig=fileConfig, configparser=configparser): """ Set up logging via :func:`logging.config.fileConfig` with the filename specified via ``config_uri`` (a string in the form ``filename#sectionname``). ConfigParser defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. Extra defaults can optionally be specified as a dict in ``global_conf``. """ path, _ = _getpathsec(config_uri, None) parser = configparser.ConfigParser() parser.read([path]) if parser.has_section('loggers'): config_file = os.path.abspath(path) full_global_conf = dict( __file__=config_file, here=os.path.dirname(config_file)) if global_conf: full_global_conf.update(global_conf) return fileConfig( config_file, full_global_conf, disable_existing_loggers=False)
[ "def", "setup_logging", "(", "config_uri", ",", "global_conf", "=", "None", ",", "# NOQA", "fileConfig", "=", "fileConfig", ",", "configparser", "=", "configparser", ")", ":", "path", ",", "_", "=", "_getpathsec", "(", "config_uri", ",", "None", ")", "parser", "=", "configparser", ".", "ConfigParser", "(", ")", "parser", ".", "read", "(", "[", "path", "]", ")", "if", "parser", ".", "has_section", "(", "'loggers'", ")", ":", "config_file", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "full_global_conf", "=", "dict", "(", "__file__", "=", "config_file", ",", "here", "=", "os", ".", "path", ".", "dirname", "(", "config_file", ")", ")", "if", "global_conf", ":", "full_global_conf", ".", "update", "(", "global_conf", ")", "return", "fileConfig", "(", "config_file", ",", "full_global_conf", ",", "disable_existing_loggers", "=", "False", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/Startup/serve.py#L57-L79
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/utilities/copyzopeskel.py
python
copyskel
(sourcedir, targetdir, uid, gid, **replacements)
This is an independent function because we'd like to import and call it from mkzopeinstance
This is an independent function because we'd like to import and call it from mkzopeinstance
[ "This", "is", "an", "independent", "function", "because", "we", "d", "like", "to", "import", "and", "call", "it", "from", "mkzopeinstance" ]
def copyskel(sourcedir, targetdir, uid, gid, **replacements): """ This is an independent function because we'd like to import and call it from mkzopeinstance """ # Create the top of the instance: if not os.path.exists(targetdir): os.makedirs(targetdir) # This is fairly ugly. The chdir() makes path manipulation in the # walk() callback a little easier (less magical), so we'll live # with it. pwd = os.getcwd() os.chdir(sourcedir) try: try: for root, dirs, files in os.walk(os.curdir): copydir(root, dirs, files, targetdir, replacements, uid, gid) finally: os.chdir(pwd) except OSError as msg: sys.stderr.write(msg) sys.exit(1)
[ "def", "copyskel", "(", "sourcedir", ",", "targetdir", ",", "uid", ",", "gid", ",", "*", "*", "replacements", ")", ":", "# Create the top of the instance:", "if", "not", "os", ".", "path", ".", "exists", "(", "targetdir", ")", ":", "os", ".", "makedirs", "(", "targetdir", ")", "# This is fairly ugly. The chdir() makes path manipulation in the", "# walk() callback a little easier (less magical), so we'll live", "# with it.", "pwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "sourcedir", ")", "try", ":", "try", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "curdir", ")", ":", "copydir", "(", "root", ",", "dirs", ",", "files", ",", "targetdir", ",", "replacements", ",", "uid", ",", "gid", ")", "finally", ":", "os", ".", "chdir", "(", "pwd", ")", "except", "OSError", "as", "msg", ":", "sys", ".", "stderr", ".", "write", "(", "msg", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/utilities/copyzopeskel.py#L167-L187
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/utilities/mkwsgiinstance.py
python
check_buildout
(script_path)
Are we running from within a buildout which supplies 'zopepy'?
Are we running from within a buildout which supplies 'zopepy'?
[ "Are", "we", "running", "from", "within", "a", "buildout", "which", "supplies", "zopepy", "?" ]
def check_buildout(script_path): """ Are we running from within a buildout which supplies 'zopepy'? """ buildout_cfg = os.path.join(os.path.dirname(script_path), 'buildout.cfg') if os.path.exists(buildout_cfg): parser = RawConfigParser() try: parser.read(buildout_cfg) return 'zopepy' in parser.sections() except ParsingError: # zc.buildout uses its own parser and it allows syntax that # ConfigParser does not like. Here's one really stupid workaround. # The alternative is using the zc.buildout parser, which would # introduce a hard dependency. zope_py = os.path.join(os.path.dirname(script_path), 'bin', 'zopepy') if os.path.isfile(zope_py) and os.access(zope_py, os.X_OK): return True
[ "def", "check_buildout", "(", "script_path", ")", ":", "buildout_cfg", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "script_path", ")", ",", "'buildout.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "buildout_cfg", ")", ":", "parser", "=", "RawConfigParser", "(", ")", "try", ":", "parser", ".", "read", "(", "buildout_cfg", ")", "return", "'zopepy'", "in", "parser", ".", "sections", "(", ")", "except", "ParsingError", ":", "# zc.buildout uses its own parser and it allows syntax that", "# ConfigParser does not like. Here's one really stupid workaround.", "# The alternative is using the zc.buildout parser, which would", "# introduce a hard dependency.", "zope_py", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "script_path", ")", ",", "'bin'", ",", "'zopepy'", ")", "if", "os", ".", "path", ".", "isfile", "(", "zope_py", ")", "and", "os", ".", "access", "(", "zope_py", ",", "os", ".", "X_OK", ")", ":", "return", "True" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/utilities/mkwsgiinstance.py#L196-L213
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/utilities/mkwsgiinstance.py
python
get_zope2path
(python)
return os.path.abspath(os.path.dirname(os.path.dirname(zope2file)))
Get Zope2 path from selected Python interpreter.
Get Zope2 path from selected Python interpreter.
[ "Get", "Zope2", "path", "from", "selected", "Python", "interpreter", "." ]
def get_zope2path(python): """ Get Zope2 path from selected Python interpreter. """ zope2file = '' try: output = subprocess.check_output( [python, '-c', 'import Zope2; print(Zope2.__file__)'], universal_newlines=True, # makes Python 3 return text, not bytes stderr=subprocess.PIPE) zope2file = output.strip() except subprocess.CalledProcessError: # fall back to current Python interpreter import Zope2 zope2file = Zope2.__file__ return os.path.abspath(os.path.dirname(os.path.dirname(zope2file)))
[ "def", "get_zope2path", "(", "python", ")", ":", "zope2file", "=", "''", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "python", ",", "'-c'", ",", "'import Zope2; print(Zope2.__file__)'", "]", ",", "universal_newlines", "=", "True", ",", "# makes Python 3 return text, not bytes", "stderr", "=", "subprocess", ".", "PIPE", ")", "zope2file", "=", "output", ".", "strip", "(", ")", "except", "subprocess", ".", "CalledProcessError", ":", "# fall back to current Python interpreter", "import", "Zope2", "zope2file", "=", "Zope2", ".", "__file__", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "zope2file", ")", ")", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/utilities/mkwsgiinstance.py#L216-L230
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/App/zcml.py
python
load_site
(force=False)
Load a Zope site by finding and loading the appropriate site configuration file.
Load a Zope site by finding and loading the appropriate site configuration file.
[ "Load", "a", "Zope", "site", "by", "finding", "and", "loading", "the", "appropriate", "site", "configuration", "file", "." ]
def load_site(force=False): """Load a Zope site by finding and loading the appropriate site configuration file.""" global _initialized if _initialized and not force: return _initialized = True # load instance site configuration file instancehome = getConfiguration().instancehome site_zcml = os.path.join(instancehome, "etc", "site.zcml") if not os.path.exists(site_zcml): # check for zope installation home skel during running unit tests import Zope2.utilities zope_utils = os.path.dirname(Zope2.utilities.__file__) site_zcml = os.path.join(zope_utils, "skel", "etc", "site.zcml") global _context _context = xmlconfig.file(site_zcml)
[ "def", "load_site", "(", "force", "=", "False", ")", ":", "global", "_initialized", "if", "_initialized", "and", "not", "force", ":", "return", "_initialized", "=", "True", "# load instance site configuration file", "instancehome", "=", "getConfiguration", "(", ")", ".", "instancehome", "site_zcml", "=", "os", ".", "path", ".", "join", "(", "instancehome", ",", "\"etc\"", ",", "\"site.zcml\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "site_zcml", ")", ":", "# check for zope installation home skel during running unit tests", "import", "Zope2", ".", "utilities", "zope_utils", "=", "os", ".", "path", ".", "dirname", "(", "Zope2", ".", "utilities", ".", "__file__", ")", "site_zcml", "=", "os", ".", "path", ".", "join", "(", "zope_utils", ",", "\"skel\"", ",", "\"etc\"", ",", "\"site.zcml\"", ")", "global", "_context", "_context", "=", "xmlconfig", ".", "file", "(", "site_zcml", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/App/zcml.py#L26-L45
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/App/zcml.py
python
load_config
(config, package=None, execute=True)
Load an additional ZCML file into the context. Use with extreme care.
Load an additional ZCML file into the context.
[ "Load", "an", "additional", "ZCML", "file", "into", "the", "context", "." ]
def load_config(config, package=None, execute=True): """Load an additional ZCML file into the context. Use with extreme care. """ global _context _context = xmlconfig.file(config, package, _context, execute=execute)
[ "def", "load_config", "(", "config", ",", "package", "=", "None", ",", "execute", "=", "True", ")", ":", "global", "_context", "_context", "=", "xmlconfig", ".", "file", "(", "config", ",", "package", ",", "_context", ",", "execute", "=", "execute", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/App/zcml.py#L48-L54
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/App/zcml.py
python
load_string
(s)
Load a snipped of ZCML into the context. Use with extreme care.
Load a snipped of ZCML into the context.
[ "Load", "a", "snipped", "of", "ZCML", "into", "the", "context", "." ]
def load_string(s): """Load a snipped of ZCML into the context. Use with extreme care. """ global _context _context = xmlconfig.string(s, _context)
[ "def", "load_string", "(", "s", ")", ":", "global", "_context", "_context", "=", "xmlconfig", ".", "string", "(", "s", ",", "_context", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/App/zcml.py#L57-L63
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/Zope2/App/startup.py
python
_load_custom_zodb
(location)
Return a module, or None.
Return a module, or None.
[ "Return", "a", "module", "or", "None", "." ]
def _load_custom_zodb(location): """Return a module, or None.""" target = os.path.join(location, 'custom_zodb.py') if os.path.exists(target): with open(target) as f: try: code_obj = compile(f.read(), target, mode='exec') except SyntaxError: return None module = types.ModuleType('Zope2.custom_zodb', 'Custom database') exec(code_obj, module.__dict__) sys.modules['Zope2.custom_zodb'] = module return module
[ "def", "_load_custom_zodb", "(", "location", ")", ":", "target", "=", "os", ".", "path", ".", "join", "(", "location", ",", "'custom_zodb.py'", ")", "if", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "with", "open", "(", "target", ")", "as", "f", ":", "try", ":", "code_obj", "=", "compile", "(", "f", ".", "read", "(", ")", ",", "target", ",", "mode", "=", "'exec'", ")", "except", "SyntaxError", ":", "return", "None", "module", "=", "types", ".", "ModuleType", "(", "'Zope2.custom_zodb'", ",", "'Custom database'", ")", "exec", "(", "code_obj", ",", "module", ".", "__dict__", ")", "sys", ".", "modules", "[", "'Zope2.custom_zodb'", "]", "=", "module", "return", "module" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/Zope2/App/startup.py#L48-L60
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/HTTPRequest.py
python
FileUpload.__bool__
(self)
return bool(self.filename)
FileUpload objects are considered false if their filename is empty.
FileUpload objects are considered false if their filename is empty.
[ "FileUpload", "objects", "are", "considered", "false", "if", "their", "filename", "is", "empty", "." ]
def __bool__(self): """FileUpload objects are considered false if their filename is empty. """ return bool(self.filename)
[ "def", "__bool__", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "filename", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPRequest.py#L1690-L1694
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/BeforeTraverse.py
python
registerBeforeTraverse
(container, object, app_handle, priority=99)
Register an object to be called before a container is traversed. 'app_handle' should be a string or other hashable value that distinguishes the application of this object, and which must be used in order to unregister the object. If the container will be pickled, the object must be a callable class instance, not a function or method. 'priority' is optional, and determines the relative order in which registered objects will be called.
Register an object to be called before a container is traversed.
[ "Register", "an", "object", "to", "be", "called", "before", "a", "container", "is", "traversed", "." ]
def registerBeforeTraverse(container, object, app_handle, priority=99): """Register an object to be called before a container is traversed. 'app_handle' should be a string or other hashable value that distinguishes the application of this object, and which must be used in order to unregister the object. If the container will be pickled, the object must be a callable class instance, not a function or method. 'priority' is optional, and determines the relative order in which registered objects will be called. """ btr = getattr(container, '__before_traverse__', {}) btr[(priority, app_handle)] = object rewriteBeforeTraverse(container, btr)
[ "def", "registerBeforeTraverse", "(", "container", ",", "object", ",", "app_handle", ",", "priority", "=", "99", ")", ":", "btr", "=", "getattr", "(", "container", ",", "'__before_traverse__'", ",", "{", "}", ")", "btr", "[", "(", "priority", ",", "app_handle", ")", "]", "=", "object", "rewriteBeforeTraverse", "(", "container", ",", "btr", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BeforeTraverse.py#L23-L38
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/BeforeTraverse.py
python
unregisterBeforeTraverse
(container, app_handle)
return objects
Unregister a __before_traverse__ hook object, given its 'app_handle'. Returns a list of unregistered objects.
Unregister a __before_traverse__ hook object, given its 'app_handle'.
[ "Unregister", "a", "__before_traverse__", "hook", "object", "given", "its", "app_handle", "." ]
def unregisterBeforeTraverse(container, app_handle): """Unregister a __before_traverse__ hook object, given its 'app_handle'. Returns a list of unregistered objects.""" btr = getattr(container, '__before_traverse__', {}) objects = [] for k in list(btr.keys()): if k[1] == app_handle: objects.append(btr[k]) del btr[k] if objects: rewriteBeforeTraverse(container, btr) return objects
[ "def", "unregisterBeforeTraverse", "(", "container", ",", "app_handle", ")", ":", "btr", "=", "getattr", "(", "container", ",", "'__before_traverse__'", ",", "{", "}", ")", "objects", "=", "[", "]", "for", "k", "in", "list", "(", "btr", ".", "keys", "(", ")", ")", ":", "if", "k", "[", "1", "]", "==", "app_handle", ":", "objects", ".", "append", "(", "btr", "[", "k", "]", ")", "del", "btr", "[", "k", "]", "if", "objects", ":", "rewriteBeforeTraverse", "(", "container", ",", "btr", ")", "return", "objects" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BeforeTraverse.py#L41-L53
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/BeforeTraverse.py
python
queryBeforeTraverse
(container, app_handle)
return objects
Find __before_traverse__ hook objects, given an 'app_handle'. Returns a list of (priority, object) pairs.
Find __before_traverse__ hook objects, given an 'app_handle'.
[ "Find", "__before_traverse__", "hook", "objects", "given", "an", "app_handle", "." ]
def queryBeforeTraverse(container, app_handle): """Find __before_traverse__ hook objects, given an 'app_handle'. Returns a list of (priority, object) pairs.""" btr = getattr(container, '__before_traverse__', {}) objects = [] for k in btr.keys(): if k[1] == app_handle: objects.append((k[0], btr[k])) return objects
[ "def", "queryBeforeTraverse", "(", "container", ",", "app_handle", ")", ":", "btr", "=", "getattr", "(", "container", ",", "'__before_traverse__'", ",", "{", "}", ")", "objects", "=", "[", "]", "for", "k", "in", "btr", ".", "keys", "(", ")", ":", "if", "k", "[", "1", "]", "==", "app_handle", ":", "objects", ".", "append", "(", "(", "k", "[", "0", "]", ",", "btr", "[", "k", "]", ")", ")", "return", "objects" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BeforeTraverse.py#L56-L65
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/BeforeTraverse.py
python
rewriteBeforeTraverse
(container, btr)
Rewrite the list of __before_traverse__ hook objects
Rewrite the list of __before_traverse__ hook objects
[ "Rewrite", "the", "list", "of", "__before_traverse__", "hook", "objects" ]
def rewriteBeforeTraverse(container, btr): """Rewrite the list of __before_traverse__ hook objects""" container.__before_traverse__ = btr hookname = '__before_publishing_traverse__' dic = hasattr(container.__class__, hookname) bpth = container.__dict__.get(hookname, None) if isinstance(bpth, MultiHook): bpth = bpth._prior bpth = MultiHook(hookname, bpth, dic) setattr(container, hookname, bpth) keys = list(btr.keys()) keys.sort() for key in keys: bpth.add(btr[key])
[ "def", "rewriteBeforeTraverse", "(", "container", ",", "btr", ")", ":", "container", ".", "__before_traverse__", "=", "btr", "hookname", "=", "'__before_publishing_traverse__'", "dic", "=", "hasattr", "(", "container", ".", "__class__", ",", "hookname", ")", "bpth", "=", "container", ".", "__dict__", ".", "get", "(", "hookname", ",", "None", ")", "if", "isinstance", "(", "bpth", ",", "MultiHook", ")", ":", "bpth", "=", "bpth", ".", "_prior", "bpth", "=", "MultiHook", "(", "hookname", ",", "bpth", ",", "dic", ")", "setattr", "(", "container", ",", "hookname", ",", "bpth", ")", "keys", "=", "list", "(", "btr", ".", "keys", "(", ")", ")", "keys", ".", "sort", "(", ")", "for", "key", "in", "keys", ":", "bpth", ".", "add", "(", "btr", "[", "key", "]", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BeforeTraverse.py#L68-L82
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/interfaces.py
python
IXmlrpcChecker.__call__
(request)
return true, when Zope's internal XML-RPC support should be used. Only called for a non-SOAP POST request whose `Content-Type` contains `text/xml` (any other request automatically does not use Zope's built-in XML-RPC). Note: this is called very early during request handling when most typical attributes of *request* are not yet set up -- e.g. it cannot rely on information in `form` or `other`. Usually, it will look up information in `request.environ` which at this time is guaranteed (only) to contain the typical CGI information, such as `PATH_INFO` and `QUERY_STRING`.
return true, when Zope's internal XML-RPC support should be used.
[ "return", "true", "when", "Zope", "s", "internal", "XML", "-", "RPC", "support", "should", "be", "used", "." ]
def __call__(request): """return true, when Zope's internal XML-RPC support should be used. Only called for a non-SOAP POST request whose `Content-Type` contains `text/xml` (any other request automatically does not use Zope's built-in XML-RPC). Note: this is called very early during request handling when most typical attributes of *request* are not yet set up -- e.g. it cannot rely on information in `form` or `other`. Usually, it will look up information in `request.environ` which at this time is guaranteed (only) to contain the typical CGI information, such as `PATH_INFO` and `QUERY_STRING`. """
[ "def", "__call__", "(", "request", ")", ":" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/interfaces.py#L87-L100
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/HTTPRangeSupport.py
python
parseRange
(header)
return ranges
RFC 2616 (HTTP 1.1) Range header parsing. Convert a range header to a list of slice indexes, returned as (start, end) tuples. If no end was given, end is None. Note that the RFC specifies the end offset to be inclusive, we return python convention indexes, where the end is exclusive. Syntactically incorrect headers are to be ignored, so if we encounter one we return None.
RFC 2616 (HTTP 1.1) Range header parsing.
[ "RFC", "2616", "(", "HTTP", "1", ".", "1", ")", "Range", "header", "parsing", "." ]
def parseRange(header): """RFC 2616 (HTTP 1.1) Range header parsing. Convert a range header to a list of slice indexes, returned as (start, end) tuples. If no end was given, end is None. Note that the RFC specifies the end offset to be inclusive, we return python convention indexes, where the end is exclusive. Syntactically incorrect headers are to be ignored, so if we encounter one we return None. """ ranges = [] add = ranges.append # First, clean out *all* whitespace. This is slightly more tolerant # than the spec asks for, but hey, it makes this function much easier. header = WHITESPACE.sub('', header) # A range header only can specify a byte range try: spec, sets = header.split('=') except ValueError: return None if spec != 'bytes': return None # The sets are delimited by commas. sets = sets.split(',') # Filter out empty values, things like ',,' are allowed in the spec sets = [_set for _set in sets if _set] # We need at least one set if not sets: return None for set in sets: try: start, end = set.split('-') except ValueError: return None # Catch empty sets if not start and not end: return None # Convert to integers or None (which will raise errors if # non-integers were used (which is what we want)). try: if start == '': start = None else: start = int(start) if end == '': end = None else: end = int(end) except ValueError: return None # Special case: No start means the suffix format was used, which # means the end value is actually a negative start value. # Convert this by making it absolute. # A -0 range is converted to sys.maxsize, which will result in a # Unsatisfiable response if no other ranges can by satisfied either. if start is None: start, end = -end, None if not start: start = sys.maxsize elif end is not None: end = end + 1 # Make the end of the range exclusive if end is not None and end <= start: return None # And store add((start, end)) return ranges
[ "def", "parseRange", "(", "header", ")", ":", "ranges", "=", "[", "]", "add", "=", "ranges", ".", "append", "# First, clean out *all* whitespace. This is slightly more tolerant", "# than the spec asks for, but hey, it makes this function much easier.", "header", "=", "WHITESPACE", ".", "sub", "(", "''", ",", "header", ")", "# A range header only can specify a byte range", "try", ":", "spec", ",", "sets", "=", "header", ".", "split", "(", "'='", ")", "except", "ValueError", ":", "return", "None", "if", "spec", "!=", "'bytes'", ":", "return", "None", "# The sets are delimited by commas.", "sets", "=", "sets", ".", "split", "(", "','", ")", "# Filter out empty values, things like ',,' are allowed in the spec", "sets", "=", "[", "_set", "for", "_set", "in", "sets", "if", "_set", "]", "# We need at least one set", "if", "not", "sets", ":", "return", "None", "for", "set", "in", "sets", ":", "try", ":", "start", ",", "end", "=", "set", ".", "split", "(", "'-'", ")", "except", "ValueError", ":", "return", "None", "# Catch empty sets", "if", "not", "start", "and", "not", "end", ":", "return", "None", "# Convert to integers or None (which will raise errors if", "# non-integers were used (which is what we want)).", "try", ":", "if", "start", "==", "''", ":", "start", "=", "None", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "==", "''", ":", "end", "=", "None", "else", ":", "end", "=", "int", "(", "end", ")", "except", "ValueError", ":", "return", "None", "# Special case: No start means the suffix format was used, which", "# means the end value is actually a negative start value.", "# Convert this by making it absolute.", "# A -0 range is converted to sys.maxsize, which will result in a", "# Unsatisfiable response if no other ranges can by satisfied either.", "if", "start", "is", "None", ":", "start", ",", "end", "=", "-", "end", ",", "None", "if", "not", "start", ":", "start", "=", "sys", ".", "maxsize", "elif", "end", "is", "not", "None", ":", "end", "=", "end", "+", "1", "# Make the end of the range exclusive", "if", "end", "is", "not", "None", "and", "end", "<=", "start", ":", "return", "None", "# And store", "add", "(", "(", "start", ",", "end", ")", ")", "return", "ranges" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPRangeSupport.py#L31-L107
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/HTTPRangeSupport.py
python
expandRanges
(ranges, size)
return expanded
Expand Range sets, given those sets and the length of the resource. Expansion means relative start values and open ends
Expand Range sets, given those sets and the length of the resource.
[ "Expand", "Range", "sets", "given", "those", "sets", "and", "the", "length", "of", "the", "resource", "." ]
def expandRanges(ranges, size): """Expand Range sets, given those sets and the length of the resource. Expansion means relative start values and open ends """ expanded = [] add = expanded.append for start, end in ranges: if start < 0: start = size + start end = end or size if end > size: end = size # Only use satisfiable ranges if start < size: add((start, end)) return expanded
[ "def", "expandRanges", "(", "ranges", ",", "size", ")", ":", "expanded", "=", "[", "]", "add", "=", "expanded", ".", "append", "for", "start", ",", "end", "in", "ranges", ":", "if", "start", "<", "0", ":", "start", "=", "size", "+", "start", "end", "=", "end", "or", "size", "if", "end", ">", "size", ":", "end", "=", "size", "# Only use satisfiable ranges", "if", "start", "<", "size", ":", "add", "(", "(", "start", ",", "end", ")", ")", "return", "expanded" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPRangeSupport.py#L110-L128
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/HTTPResponse.py
python
make_content_disposition
(disposition, file_name)
Create HTTP header for downloading a file with a UTF-8 filename. See this and related answers: https://stackoverflow.com/a/8996249/2173868.
Create HTTP header for downloading a file with a UTF-8 filename.
[ "Create", "HTTP", "header", "for", "downloading", "a", "file", "with", "a", "UTF", "-", "8", "filename", "." ]
def make_content_disposition(disposition, file_name): """Create HTTP header for downloading a file with a UTF-8 filename. See this and related answers: https://stackoverflow.com/a/8996249/2173868. """ header = f'{disposition}' try: file_name.encode('us-ascii') except UnicodeEncodeError: # the file cannot be encoded using the `us-ascii` encoding # which is advocated by RFC 7230 - 7237 # # a special header has to be crafted # also see https://tools.ietf.org/html/rfc6266#appendix-D encoded_file_name = file_name.encode('us-ascii', errors='ignore') header += f'; filename="{encoded_file_name}"' quoted_file_name = quote(file_name) header += f'; filename*=UTF-8\'\'{quoted_file_name}' return header else: header += f'; filename="{file_name}"' return header
[ "def", "make_content_disposition", "(", "disposition", ",", "file_name", ")", ":", "header", "=", "f'{disposition}'", "try", ":", "file_name", ".", "encode", "(", "'us-ascii'", ")", "except", "UnicodeEncodeError", ":", "# the file cannot be encoded using the `us-ascii` encoding", "# which is advocated by RFC 7230 - 7237", "#", "# a special header has to be crafted", "# also see https://tools.ietf.org/html/rfc6266#appendix-D", "encoded_file_name", "=", "file_name", ".", "encode", "(", "'us-ascii'", ",", "errors", "=", "'ignore'", ")", "header", "+=", "f'; filename=\"{encoded_file_name}\"'", "quoted_file_name", "=", "quote", "(", "file_name", ")", "header", "+=", "f'; filename*=UTF-8\\'\\'{quoted_file_name}'", "return", "header", "else", ":", "header", "+=", "f'; filename=\"{file_name}\"'", "return", "header" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L127-L148
zopefoundation/Zope
61260fab5776ea4c8bbbb0129d729d05eb183c4c
src/ZPublisher/HTTPResponse.py
python
encode_words
(value)
return Header(value, 'utf-8', 1000000).encode()
RFC 2047 word encoding. Note: treats *value* as unstructured data and therefore must not be applied for headers with a structured value (unless the structure is garanteed to only contain ISO-8859-1 chars).
RFC 2047 word encoding.
[ "RFC", "2047", "word", "encoding", "." ]
def encode_words(value): """RFC 2047 word encoding. Note: treats *value* as unstructured data and therefore must not be applied for headers with a structured value (unless the structure is garanteed to only contain ISO-8859-1 chars). """ return Header(value, 'utf-8', 1000000).encode()
[ "def", "encode_words", "(", "value", ")", ":", "return", "Header", "(", "value", ",", "'utf-8'", ",", "1000000", ")", ".", "encode", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1179-L1187