本文整理汇总了Python中twext.web2.http_headers.MimeType类的典型用法代码示例。如果您正苦于以下问题:Python MimeType类的具体用法?Python MimeType怎么用?Python MimeType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MimeType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_MissingContentType
def test_MissingContentType(self):
test_files = (
("plain.txt", MimeType.fromString("text/plain"),),
("word.doc", MimeType.fromString("application/msword"),),
("markup.html", MimeType.fromString("text/html"),),
("octet", MimeType.fromString("application/octet-stream"),),
("bogus.bog", MimeType.fromString("application/octet-stream"),),
)
class FakeAttachment(object):
def __init__(self, name):
self._name = name
def name(self):
return self._name
for filename, result in test_files:
item = StorageTransportBase(FakeAttachment(filename), None, None)
self.assertEquals(item._contentType, result)
self.assertEquals(item._dispositionName, None)
item = StorageTransportBase(FakeAttachment(filename), result, filename)
self.assertEquals(item._contentType, result)
self.assertEquals(item._dispositionName, filename)
示例2: doPOSTGet
def doPOSTGet(self, request):
"""
Return the specified timezone data.
"""
tzid = request.args.get("tzid", ())
if len(tzid) != 1:
raise HTTPError(ErrorResponse(
responsecode.BAD_REQUEST,
(calendarserver_namespace, "valid-timezone"),
"Invalid tzid query parameter",
))
tzid = tzid[0]
try:
tzdata = readTZ(tzid)
except TimezoneException:
raise HTTPError(ErrorResponse(
responsecode.NOT_FOUND,
(calendarserver_namespace, "timezone-available"),
"Timezone not found",
))
response = Response()
response.stream = MemoryStream(tzdata)
response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
return response
示例3: test_timeoutOnPUT
def test_timeoutOnPUT(self):
"""
PUT gets a 503 on a lock timeout.
"""
# Create a fake lock
txn = self.transactionUnderTest()
yield NamedLock.acquire(txn, "ImplicitUIDLock:%s" % (hashlib.md5("uid1").hexdigest(),))
# PUT fails
request = SimpleStoreRequest(
self,
"PUT",
"/calendars/users/wsanchez/calendar/1.ics",
headers=Headers({"content-type": MimeType.fromString("text/calendar")}),
authid="wsanchez"
)
request.stream = MemoryStream("""BEGIN:VCALENDAR
CALSCALE:GREGORIAN
PRODID:-//Apple Computer\, Inc//iCal 2.0//EN
VERSION:2.0
BEGIN:VEVENT
UID:uid1
DTSTART;VALUE=DATE:20020101
DTEND;VALUE=DATE:20020102
DTSTAMP:20020101T121212Z
SUMMARY:New Year's Day
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"))
response = yield self.send(request)
self.assertEqual(response.code, responsecode.SERVICE_UNAVAILABLE)
示例4: report_urn_ietf_params_xml_ns_caldav_free_busy_query
def report_urn_ietf_params_xml_ns_caldav_free_busy_query(self, request, freebusy): #@UnusedVariable
"""
Generate a free-busy REPORT.
(CalDAV-access-09, section 7.8)
"""
if not self.isCollection():
log.err("freebusy report is only allowed on collection resources %s" % (self,))
raise HTTPError(StatusResponse(responsecode.FORBIDDEN, "Not a calendar collection"))
if freebusy.qname() != (caldavxml.caldav_namespace, "free-busy-query"):
raise ValueError("{CalDAV:}free-busy-query expected as root element, not %s." % (freebusy.sname(),))
timerange = freebusy.timerange
if not timerange.valid():
raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, "Invalid time-range specified"))
# First list is BUSY, second BUSY-TENTATIVE, third BUSY-UNAVAILABLE
fbinfo = ([], [], [])
matchcount = [0]
def generateFreeBusyInfo(calresource, uri): #@UnusedVariable
"""
Run a free busy report on the specified calendar collection
accumulating the free busy info for later processing.
@param calresource: the L{CalDAVFile} for a calendar collection.
@param uri: the uri for the calendar collecton resource.
"""
def _gotResult(result):
matchcount[0] = result
return True
d = report_common.generateFreeBusyInfo(request, calresource, fbinfo, timerange, matchcount[0])
d.addCallback(_gotResult)
return d
# Run report taking depth into account
try:
depth = request.headers.getHeader("depth", "0")
yield report_common.applyToCalendarCollections(self, request, request.uri, depth, generateFreeBusyInfo, (caldavxml.ReadFreeBusy(),))
except NumberOfMatchesWithinLimits:
log.err("Too many matching components in free-busy report")
raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, davxml.NumberOfMatchesWithinLimits()))
# Now build a new calendar object with the free busy info we have
fbcalendar = report_common.buildFreeBusyResult(fbinfo, timerange)
response = Response()
response.stream = MemoryStream(str(fbcalendar))
response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
returnValue(response)
示例5: _populate
def _populate(self):
"""
Execute necessary SQL queries to retrieve attributes.
@return: C{True} if this attachment exists, C{False} otherwise.
"""
rows = self._txn.execSQL(
"""
select CONTENT_TYPE, SIZE, MD5, extract(EPOCH from CREATED), extract(EPOCH from MODIFIED) from ATTACHMENT where PATH = %s
""", [self._pathValue()])
if not rows:
return False
self._contentType = MimeType.fromString(rows[0][0])
self._size = rows[0][1]
self._md5 = rows[0][2]
self._created = int(rows[0][3])
self._modified = int(rows[0][4])
return True
示例6: doGet
def doGet(self, request):
"""
Return the specified timezone data.
"""
tzids = request.args.get("tzid", ())
if len(tzids) != 1:
raise HTTPError(JSONResponse(
responsecode.BAD_REQUEST,
{
"error": "invalid-tzid",
"description": "Invalid tzid query parameter",
},
))
format = request.args.get("format", ("text/calendar",))
if len(format) != 1 or format[0] not in ("text/calendar", "text/plain",):
raise HTTPError(JSONResponse(
responsecode.BAD_REQUEST,
{
"error": "invalid-format",
"description": "Invalid format query parameter",
},
))
format = format[0]
calendar = self.timezones.getTimezone(tzids[0])
if calendar is None:
raise HTTPError(JSONResponse(
responsecode.NOT_FOUND,
{
"error": "missing-tzid",
"description": "Tzid could not be found",
}
))
tzdata = calendar.getText()
response = Response()
response.stream = MemoryStream(tzdata)
response.headers.setHeader("content-type", MimeType.fromString("%s; charset=utf-8" % (format,)))
return response
示例7: contentType
def contentType(self):
return MimeType.fromString("text/html; charset=utf-8")
示例8: contentType
def contentType(self):
"""
The content type of Calendar objects is text/calendar.
"""
return MimeType.fromString("text/calendar; charset=utf-8")
示例9: _defer
def _defer(data):
response = Response()
response.stream = MemoryStream(str(data))
response.headers.setHeader("content-type", MimeType.fromString("text/calendar"))
return response
示例10: test_upgradeAttachments
def test_upgradeAttachments(self):
"""
L{UpgradeToDatabaseService.startService} upgrades calendar attachments
as well.
"""
# Need to tweak config and settings to setup dropbox to work
self.patch(config, "EnableDropBox", True)
self.patch(config, "EnableManagedAttachments", False)
self.sqlStore.enableManagedAttachments = False
txn = self.sqlStore.newTransaction()
cs = schema.CALENDARSERVER
yield Delete(
From=cs,
Where=cs.NAME == "MANAGED-ATTACHMENTS"
).on(txn)
yield txn.commit()
txn = self.fileStore.newTransaction()
committed = []
def maybeCommit():
if not committed:
committed.append(True)
return txn.commit()
self.addCleanup(maybeCommit)
@inlineCallbacks
def getSampleObj():
home = (yield txn.calendarHomeWithUID("home1"))
calendar = (yield home.calendarWithName("calendar_1"))
object = (yield calendar.calendarObjectWithName("1.ics"))
returnValue(object)
inObject = yield getSampleObj()
someAttachmentName = "some-attachment"
someAttachmentType = MimeType.fromString("application/x-custom-type")
attachment = yield inObject.createAttachmentWithName(
someAttachmentName,
)
transport = attachment.store(someAttachmentType)
someAttachmentData = "Here is some data for your attachment, enjoy."
transport.write(someAttachmentData)
yield transport.loseConnection()
yield maybeCommit()
yield self.upgrader.stepWithResult(None)
committed = []
txn = self.sqlStore.newTransaction()
outObject = yield getSampleObj()
outAttachment = yield outObject.attachmentWithName(someAttachmentName)
allDone = Deferred()
class SimpleProto(Protocol):
data = ''
def dataReceived(self, data):
self.data += data
def connectionLost(self, reason):
allDone.callback(self.data)
self.assertEquals(outAttachment.contentType(), someAttachmentType)
outAttachment.retrieve(SimpleProto())
allData = yield allDone
self.assertEquals(allData, someAttachmentData)
示例11: HTTPError
depth = request.headers.getHeader("depth", "0")
yield report_common.applyToCalendarCollections(self, request, request.uri, depth, generateFreeBusyInfo, (caldavxml.ReadFreeBusy(),))
except NumberOfMatchesWithinLimits:
log.error("Too many matching components in free-busy report")
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
davxml.NumberOfMatchesWithinLimits(),
"Too many components"
))
except TimeRangeLowerLimit, e:
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
caldavxml.MinDateTime(),
"Time-range value too far in the past. Must be on or after %s." % (str(e.limit),)
))
except TimeRangeUpperLimit, e:
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
caldavxml.MaxDateTime(),
"Time-range value too far in the future. Must be on or before %s." % (str(e.limit),)
))
# Now build a new calendar object with the free busy info we have
fbcalendar = report_common.buildFreeBusyResult(fbinfo, timerange)
response = Response()
response.stream = MemoryStream(str(fbcalendar))
response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
returnValue(response)
示例12: mimeType
def mimeType(self):
return MimeType.fromString(str(self))
示例13: 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)
示例14: 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"),
"Invalid action parameter: %s" % (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"),
"Action not supported: %s" % (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))
# Filter any attendee hidden instances
caldata = HiddenInstanceFilter().filter(caldata)
if self.accessMode:
# Non DAV:owner's have limited access to the data
isowner = (yield self.isOwner(request))
# Now "filter" the resource calendar data
caldata = PrivateEventFilter(self.accessMode, isowner).filter(caldata)
response = Response()
response.stream = MemoryStream(caldata.getTextWithTimezones(includeTimezones=not config.EnableTimezonesByReference))
response.headers.setHeader("content-type", MimeType.fromString("text/calendar; charset=utf-8"))
# Add Schedule-Tag header if property is present
if self.scheduleTag:
response.headers.setHeader("Schedule-Tag", self.scheduleTag)
returnValue(response)
# Do normal GET behavior
response = (yield super(CalDAVResource, self).http_GET(request))
returnValue(response)
示例15: addUnicodeChild
def addUnicodeChild(davFile):
m = MetaDataMixin()
m.contentType = lambda: MimeType.fromString('text/plain')
m.resourceType = lambda: ResourceType()
m.isCollection = lambda: False
davFile.putChild(unicodeChildName, m)