当前位置: 首页>>代码示例>>Python>>正文


Python util.parentForURL函数代码示例

本文整理汇总了Python中twext.web2.dav.util.parentForURL函数的典型用法代码示例。如果您正苦于以下问题:Python parentForURL函数的具体用法?Python parentForURL怎么用?Python parentForURL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了parentForURL函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: checkForAddressBookAction

def checkForAddressBookAction(self, request):
    """
    Check to see whether the source or destination of the copy/move
    is an addressbook collection, since we need to do special processing
    if that is the case.
    @return: tuple::
        result:           True if special CalDAV processing required, False otherwise
            NB If there is any type of error with the request, return False
            and allow normal COPY/MOVE processing to return the error.
        sourceadbk:        True if source is in an addressbook collection, False otherwise
        sourceparent:     The parent resource for the source
        destination_uri:  The URI of the destination resource
        destination:      CalDAVResource of destination if special processing required,
        None otherwise
        destinationadbk:   True if the destination is in an addressbook collection,
            False otherwise
        destinationparent:The parent resource for the destination
        
    """
    
    result = False
    sourceadbk = False
    destinationadbk = False
    
    # Check the source path first
    if not self.exists():
        log.err("Resource not found: %s" % (self,))
        raise HTTPError(StatusResponse(
            responsecode.NOT_FOUND,
            "Source resource %s not found." % (request.uri,)
        ))

    # Check for parent addressbook collection
    sourceparent = (yield request.locateResource(parentForURL(request.uri)))
    if isAddressBookCollectionResource(sourceparent):
        result = True
        sourceadbk = True
    
    #
    # Find the destination resource
    #
    destination_uri = request.headers.getHeader("destination")

    if not destination_uri:
        msg = "No destination header in %s request." % (request.method,)
        log.err(msg)
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg))
    
    destination = (yield request.locateResource(destination_uri))

    # Check for parent addressbook collection
    destination_uri = urlsplit(destination_uri)[2]
    destinationparent = (yield request.locateResource(parentForURL(destination_uri)))
    if isAddressBookCollectionResource(destinationparent):
        result = True
        destinationadbk = True

    returnValue((result, sourceadbk, sourceparent, destination_uri, destination, destinationadbk, destinationparent))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:58,代码来源:copymove_contact.py

示例2: http_PROPFIND

def http_PROPFIND(self, request):
    """
    Respond to a PROPFIND request. (RFC 2518, section 8.1)
    """
    if not self.exists():
        # Return 403 if parent does not allow Bind
        parentURL = parentForURL(request.uri)
        parent = (yield request.locateResource(parentURL))
        yield parent.authorize(request, (davxml.Bind(),))

        log.error("Resource not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    #
    # Check authentication and access controls
    #
    yield self.authorize(request, (davxml.Read(),))

    #
    # Read request body
    #
    try:
        doc = (yield davXMLFromStream(request.stream))
    except ValueError, e:
        log.error("Error while handling PROPFIND body: %s" % (e,))
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e)))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:26,代码来源:propfind.py

示例3: http_DELETE

def http_DELETE(self, request):
    #
    # Override base DELETE request handling to ensure that the calendar
    # index file has the entry for the deleted calendar component removed.
    #

    if not self.exists():
        log.err("Resource not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    depth = request.headers.getHeader("depth", "infinity")

    #
    # Check authentication and access controls
    #
    parentURL = parentForURL(request.uri)
    parent = (yield request.locateResource(parentURL))

    yield parent.authorize(request, (davxml.Unbind(),))

    # Do smart delete taking into account the need to do implicit CANCELs etc
    deleter = DeleteResource(request, self, request.uri, parent, depth)
    response = (yield deleter.run())

    returnValue(response)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:25,代码来源:delete.py

示例4: authorize

def authorize(self, request):
    if self.exists():
        d = self.authorize(request, (davxml.Read(),))
    else:
        d = request.locateResource(parentForURL(request.uri))
        d.addCallback(lambda parent: parent.authorize(request, (davxml.Bind(),)))
    return d
开发者ID:jrossi,项目名称:twext,代码行数:7,代码来源:get.py

示例5: http_MKCOL

def http_MKCOL(self, request):
    """
    Respond to a MKCOL request. (RFC 2518, section 8.3)
    """
    parent = waitForDeferred(request.locateResource(parentForURL(request.uri)))
    yield parent
    parent = parent.getResult()

    x = waitForDeferred(parent.authorize(request, (davxml.Bind(),)))
    yield x
    x.getResult()

    if self.exists():
        log.err("Attempt to create collection where file exists: %s"
                % (self,))
        raise HTTPError(responsecode.NOT_ALLOWED)

    if not parent.isCollection():
        log.err("Attempt to create collection with non-collection parent: %s"
                % (self,))
        raise HTTPError(StatusResponse(
            responsecode.CONFLICT,
            "Parent resource is not a collection."
        ))

    #
    # Read request body
    #
    x = waitForDeferred(noDataFromStream(request.stream))
    yield x
    try:
        x.getResult()
    except ValueError, e:
        log.err("Error while handling MKCOL body: %s" % (e,))
        raise HTTPError(responsecode.UNSUPPORTED_MEDIA_TYPE)
开发者ID:jrossi,项目名称:twext,代码行数:35,代码来源:mkcol.py

示例6: http_PUT

def http_PUT(self, request):

    parentURL = parentForURL(request.uri)
    parent = (yield request.locateResource(parentURL))

    if isPseudoCalendarCollectionResource(parent):

        # Content-type check
        content_type = request.headers.getHeader("content-type")
        if content_type is not None and (content_type.mediaType, content_type.mediaSubtype) != ("text", "calendar"):
            log.err("MIME type %s not allowed in calendar collection" % (content_type,))
            raise HTTPError(ErrorResponse(
                responsecode.FORBIDDEN,
                (caldav_namespace, "supported-calendar-data"),
                "Invalid MIME type for calendar collection",
            ))

        # Read the calendar component from the stream
        try:
            calendardata = (yield allDataFromStream(request.stream))
            if not hasattr(request, "extendedLogItems"):
                request.extendedLogItems = {}
            request.extendedLogItems["cl"] = str(len(calendardata)) if calendardata else "0"

            # We must have some data at this point
            if calendardata is None:
                # Use correct DAV:error response
                raise HTTPError(ErrorResponse(
                    responsecode.FORBIDDEN,
                    (caldav_namespace, "valid-calendar-data"),
                    description="No calendar data"
                ))

            storer = StoreCalendarObjectResource(
                request=request,
                destination=self,
                destination_uri=request.uri,
                destinationcal=True,
                destinationparent=parent,
                calendar=calendardata,
            )
            result = (yield storer.run())

            # Look for Prefer header
            prefer = request.headers.getHeader("prefer", {})
            returnRepresentation = any([key == "return" and value == "representation" for key, value, _ignore_args in prefer])

            if returnRepresentation and result.code / 100 == 2:
                oldcode = result.code
                result = (yield self.http_GET(request))
                if oldcode == responsecode.CREATED:
                    result.code = responsecode.CREATED
                result.headers.setHeader("content-location", request.path)

            returnValue(result)

        except ValueError, e:
            log.err("Error while handling (calendar) PUT: %s" % (e,))
            raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e)))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:59,代码来源:put.py

示例7: http_COPY

def http_COPY(self, request):
    """
    Respond to a COPY request. (RFC 2518, section 8.8)
    """
    r = waitForDeferred(prepareForCopy(self, request))
    yield r
    r = r.getResult()

    destination, destination_uri, depth = r

    #
    # Check authentication and access controls
    #
    x = waitForDeferred(self.authorize(request, (davxml.Read(),), recurse=True))
    yield x
    x.getResult()

    if destination.exists():
        x = waitForDeferred(destination.authorize(
            request,
            (davxml.WriteContent(), davxml.WriteProperties()),
            recurse=True
        ))
        yield x
        x.getResult()
    else:
        destparent = waitForDeferred(request.locateResource(parentForURL(destination_uri)))
        yield destparent
        destparent = destparent.getResult()

        x = waitForDeferred(destparent.authorize(request, (davxml.Bind(),)))
        yield x
        x.getResult()

        # May need to add a location header
        addLocation(request, destination_uri)

    #x = waitForDeferred(copy(self.fp, destination.fp, destination_uri, depth))
    x = waitForDeferred(put_common.storeResource(request,
                                                 source=self,
                                                 source_uri=request.uri,
                                                 destination=destination,
                                                 destination_uri=destination_uri,
                                                 deletesource=False,
                                                 depth=depth
                                                 ))
    yield x
    yield x.getResult()
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:48,代码来源:copymove.py

示例8: hasCalendarResourceUIDSomewhereElse

    def hasCalendarResourceUIDSomewhereElse(self, check_resource, check_uri, type):
        """
        See if a calendar component with a matching UID exists anywhere in the calendar home of the
        current recipient owner and is not the resource being targeted.
        """

        # Don't care in some cases
        if self.internal_request or self.action == "remove":
            returnValue(None)

        # Get owner's calendar-home
        calendar_owner_principal = (yield self.resource.resourceOwnerPrincipal(self.request))
        calendar_home = calendar_owner_principal.calendarHome(self.request)

        check_parent_uri = parentForURL(check_uri)[:-1] if check_uri else None

        # FIXME: because of the URL->resource request mapping thing, we have to force the request
        # to recognize this resource
        self.request._rememberResource(calendar_home, calendar_home.url())

        # Run a UID query against the UID

        @inlineCallbacks
        def queryCalendarCollection(collection, collection_uri):
            rname = collection.index().resourceNameForUID(self.uid)
            if rname:
                child = (yield self.request.locateResource(joinURL(collection_uri, rname)))
                if child == check_resource:
                    returnValue(True)
                is_scheduling_object = (yield self.checkSchedulingObjectResource(child))
                matched_type = "schedule" if is_scheduling_object else "calendar"
                if (
                    collection_uri != check_parent_uri and
                    (type == "schedule" or matched_type == "schedule")
                ):
                    log.debug("Implicit - found component with same UID in a different collection: %s" % (check_uri,))
                    raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "unique-scheduling-object-resource")))

                # Here we can always return true as the unique UID in a calendar collection
                # requirement will already have been tested.

            returnValue(True)

        # NB We are by-passing privilege checking here. That should be OK as the data found is not
        # exposed to the user.
        yield report_common.applyToCalendarCollections(calendar_home, self.request, calendar_home.url(), "infinity", queryCalendarCollection, None)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:46,代码来源:implicit.py

示例9: preconditions_PUT

def preconditions_PUT(self, request):
    #
    # Check authentication and access controls
    #
    if self.exists():
        x = waitForDeferred(self.authorize(request, (davxml.WriteContent(),)))
        yield x
        x.getResult()
    else:
        parent = waitForDeferred(request.locateResource(parentForURL(request.uri)))
        yield parent
        parent = parent.getResult()

        if not parent.exists():
            raise HTTPError(
                StatusResponse(
                    responsecode.CONFLICT,
                    "cannot PUT to non-existent parent"))
        x = waitForDeferred(parent.authorize(request, (davxml.Bind(),)))
        yield x
        x.getResult()


    #
    # HTTP/1.1 (RFC 2068, section 9.6) requires that we respond with a Not
    # Implemented error if we get a Content-* header which we don't
    # recognize and handle properly.
    #
    for header, value in request.headers.getAllRawHeaders():
        if header.startswith("Content-") and header not in (
           #"Content-Base",     # Doesn't make sense in PUT?
           #"Content-Encoding", # Requires that we decode it?
            "Content-Language",
            "Content-Length",
           #"Content-Location", # Doesn't make sense in PUT?
            "Content-MD5",
           #"Content-Range",    # FIXME: Need to implement this
            "Content-Type",
        ):
            log.error("Client sent unrecognized content header in PUT request: %s"
                      % (header,))
            raise HTTPError(StatusResponse(
                responsecode.NOT_IMPLEMENTED,
                "Unrecognized content header %r in request." % (header,)
            ))
开发者ID:anemitz,项目名称:calendarserver,代码行数:45,代码来源:put.py

示例10: http_ACL

def http_ACL(self, request):
    #
    # Override base ACL request handling to ensure that the calendar/address book
    # homes cannot have ACL's set, and calendar/address object resources too.
    #

    if self.exists():
        if isinstance(self, CalendarHomeResource) or isinstance(self, AddressBookHomeResource):
            raise HTTPError(responsecode.NOT_ALLOWED)

        parentURL = parentForURL(request.uri)
        parent = (yield request.locateResource(parentURL))
        if isPseudoCalendarCollectionResource(parent) or isAddressBookCollectionResource(parent):
            raise HTTPError(responsecode.NOT_ALLOWED)

    # Do normal ACL behavior
    response = (yield super(CalDAVResource, self).http_ACL(request))
    returnValue(response)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:18,代码来源:acl.py

示例11: http_MKCALENDAR

def http_MKCALENDAR(self, request):
    """
    Respond to a MKCALENDAR request.
    (CalDAV-access-09, section 5.3.1)
    """

    #
    # Check authentication and access controls
    #
    parent = (yield request.locateResource(parentForURL(request.uri)))
    yield parent.authorize(request, (davxml.Bind(),))

    if self.exists():
        log.error("Attempt to create collection where resource exists: %s" % (self,))
        raise HTTPError(ErrorResponse(
            responsecode.FORBIDDEN,
            (davxml.dav_namespace, "resource-must-be-null"),
            "Resource already exists",
        ))

    if not parent.isCollection():
        log.error("Attempt to create collection with non-collection parent: %s"
                  % (self,))
        raise HTTPError(ErrorResponse(
            responsecode.CONFLICT,
            (caldavxml.caldav_namespace, "calendar-collection-location-ok"),
            "Cannot create calendar inside another calendar",
        ))

    #
    # Read request body
    #
    try:
        doc = (yield davXMLFromStream(request.stream))
        yield self.createCalendar(request)
    except ValueError, e:
        log.error("Error while handling MKCALENDAR: %s" % (e,))
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e)))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:38,代码来源:mkcalendar.py

示例12: http_DELETE

def http_DELETE(self, request):
    """
    Respond to a DELETE request. (RFC 2518, section 8.6)
    """
    if not self.exists():
        log.err("File not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    depth = request.headers.getHeader("depth", "infinity")

    #
    # Check authentication and access controls
    #
    parent = waitForDeferred(request.locateResource(parentForURL(request.uri)))
    yield parent
    parent = parent.getResult()

    x = waitForDeferred(parent.authorize(request, (davxml.Unbind(),)))
    yield x
    x.getResult()

    x = waitForDeferred(deleteResource(request, self, request.uri, depth))
    yield x
    yield x.getResult()
开发者ID:jrossi,项目名称:twext,代码行数:24,代码来源:delete.py

示例13: http_MOVE

def http_MOVE(self, request):
    """
    Respond to a MOVE request. (RFC 2518, section 8.9)
    """
    r = waitForDeferred(prepareForCopy(self, request))
    yield r
    r = r.getResult()

    destination, destination_uri, depth = r

    #
    # Check authentication and access controls
    #
    parentURL = parentForURL(request.uri)
    parent = waitForDeferred(request.locateResource(parentURL))
    yield parent
    parent = parent.getResult()

    x = waitForDeferred(parent.authorize(request, (davxml.Unbind(),)))
    yield x
    x.getResult()

    if destination.exists():
        x = waitForDeferred(destination.authorize(
            request,
            (davxml.Bind(), davxml.Unbind()),
            recurse=True
        ))
        yield x
        x.getResult()
    else:
        destparentURL = parentForURL(destination_uri)
        destparent = waitForDeferred(request.locateResource(destparentURL))
        yield destparent
        destparent = destparent.getResult()

        x = waitForDeferred(destparent.authorize(request, (davxml.Bind(),)))
        yield x
        x.getResult()

        # May need to add a location header
        addLocation(request, destination_uri)

    #
    # RFC 2518, section 8.9 says that we must act as if the Depth header is set
    # to infinity, and that the client must omit the Depth header or set it to
    # infinity.
    #
    # This seems somewhat at odds with the notion that a bad request should be
    # rejected outright; if the client sends a bad depth header, the client is
    # broken, and section 8 suggests that a bad request should be rejected...
    #
    # Let's play it safe for now and ignore broken clients.
    #
    if self.isCollection() and depth != "infinity":
        msg = "Client sent illegal depth header value for MOVE: %s" % (depth,)
        log.err(msg)
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg))

    # Lets optimise a move within the same directory to a new resource as a simple move
    # rather than using the full transaction based storeResource api. This allows simple
    # "rename" operations to work quickly.
    if (not destination.exists()) and destparent == parent:
        x = waitForDeferred(move(self.fp, request.uri, destination.fp, destination_uri, depth))
    else:
        x = waitForDeferred(put_common.storeResource(request,
                                                     source=self,
                                                     source_uri=request.uri,
                                                     destination=destination,
                                                     destination_uri=destination_uri,
                                                     deletesource=True,
                                                     depth=depth))
    yield x
    yield x.getResult()
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:74,代码来源:copymove.py

示例14: run

    def run(self):
        """
        Function that does common PUT/COPY/MOVE behavior.

        @return: a Deferred with a status response result.
        """

        try:
            reservation = None
            
            # Handle all validation operations here.
            yield self.fullValidation()

            # Reservation and UID conflict checking is next.
            if self.destinationadbk:    
                # Reserve UID
                self.destination_index = self.destinationparent.index()
                reservation = StoreAddressObjectResource.UIDReservation(
                    self.destination_index, self.uid, self.destination_uri
                )
                if self.indexdestination:
                    yield reservation.reserve()
            
                # UID conflict check - note we do this after reserving the UID to avoid a race condition where two requests
                # try to write the same vcard data to two different resource URIs.
                result, message, rname = self.noUIDConflict(self.uid)
                if not result:
                    log.err(message)
                    raise HTTPError(ErrorResponse(responsecode.FORBIDDEN,
                        NoUIDConflict(davxml.HRef.fromString(joinURL(parentForURL(self.destination_uri), rname.encode("utf-8"))))
                    ))
            
            # Get current quota state.
            yield self.checkQuota()

            # Do the actual put or copy
            response = (yield self.doStore())
            
            # Remember the resource's content-type.
            if self.destinationadbk:
                content_type = self.request.headers.getHeader("content-type")
                if content_type is None:
                    content_type = MimeType("text", "vcard",
                                            params={"charset":"utf-8"})
                self.destination.writeDeadProperty(
                    davxml.GETContentType.fromString(generateContentType(content_type))
                )

            # Delete the original source if needed.
            if self.deletesource:
                yield self.doSourceQuotaCheck()

            # Do quota check on destination
            if self.destquota is not None:
                yield self.doDestinationQuotaCheck()
    
            if reservation:
                yield reservation.unreserve()
    
            returnValue(response)
    
        except Exception, err:

            if reservation:
                yield reservation.unreserve()
    
            # FIXME: transaction needs to be rolled back.

            raise err
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:69,代码来源:put_addressbook_common.py

示例15: http_GET

def http_GET(self, request):

    if self.exists():
        # Special sharing request on a calendar or address book
        if self.isCalendarCollection() or self.isAddressBookCollection():
            
            # Check for action=share
            if request.args:
                action = request.args.get("action", ("",))
                if len(action) != 1:
                    raise HTTPError(ErrorResponse(responsecode.BAD_REQUEST, (calendarserver_namespace, "valid-action")))
                action = action[0]
                    
                dispatch = {
                    "share"   : self.directShare,
                }.get(action, None)
                
                if dispatch is None:
                    raise HTTPError(ErrorResponse(responsecode.BAD_REQUEST, (calendarserver_namespace, "supported-action")))
        
                response = (yield dispatch(request))
                returnValue(response)
        
        else:
            # Look for calendar access restriction on existing resource.
            parentURL = parentForURL(request.uri)
            parent = (yield request.locateResource(parentURL))
            if isPseudoCalendarCollectionResource(parent):
        
                # Check authorization first
                yield self.authorize(request, (davxml.Read(),))
    
                caldata = (yield self.iCalendarForUser(request))
    
                try:
                    access = self.readDeadProperty(TwistedCalendarAccessProperty)
                except HTTPError:
                    access = None
                    
                if access:
            
                    # Non DAV:owner's have limited access to the data
                    isowner = (yield self.isOwner(request, adminprincipals=True, readprincipals=True))
                    
                    # Now "filter" the resource calendar data
                    caldata = PrivateEventFilter(access, isowner).filter(caldata)
        
                response = Response()
                response.stream = MemoryStream(str(caldata))
                response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
        
                # Add Schedule-Tag header if property is present
                if self.hasDeadProperty(ScheduleTag):
                    scheduletag = self.readDeadProperty(ScheduleTag)
                    if scheduletag:
                        response.headers.setHeader("Schedule-Tag", str(scheduletag))
            
                returnValue(response)

    # Do normal GET behavior
    response = (yield super(CalDAVResource, self).http_GET(request))
    returnValue(response)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:62,代码来源:get.py


注:本文中的twext.web2.dav.util.parentForURL函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。