Download Shareware and Freeware Software for Windows, Linux, Macintosh, PDA

line Home  |  About Us  |  Link To Us  |  FAQ  |  Contact

Serving Software Downloads in 976 Categories, Downloaded 32.290.860 Times

zope.mimetype 1.3.1

Company: Zope Corporation and Contributors
Date Added: June 08, 2013  |  Visits: 295


Report Broken Link
Printer Friendly Version

Product Homepage
Download (16 downloads)

This package provides a way to work with MIME content types. There are several interfaces defined here, many of which are used primarily to look things up based on different bits of information.<br /><br />The basic idea behind this is that content objects should provide an interface based on the actual content type they implement. For example, objects that represent text/xml or application/xml documents should be marked mark with the IContentTypeXml interface. This can allow additional views to be registered based on the content type, or subscribers may be registered to perform other actions based on the content type.<br /><br />One aspect of the content type that's important for all documents is that the content type interface determines whether the object data is interpreted as an encoded text document. Encoded text documents, in particular, can be decoded to obtain a single Unicode string. The content type intefaces for encoded text must derive from IContentTypeEncoded. (All content type interfaces derive from IContentType and directly provide IContentTypeInterface.)<br /><br />The default configuration provides direct support for a variety of common document types found in office environments.<br />Supported lookups<br /><br />Several different queries are supported by this package:<br /><br /> *<br /><br /> Given a MIME type expressed as a string, the associated interface, if any, can be retrieved using:<br /><br /> # `mimeType` is the MIME type as a string<br /> interface = queryUtility(IContentTypeInterface, mimeType)<br /><br /> *<br /><br /> Given a charset name, the associated ICodec instance can be retrieved using:<br /><br /> # `charsetName` is the charset name as a string<br /> codec = queryUtility(ICharsetCodec, charsetName)<br /><br /> *<br /><br /> Given a codec, the preferred charset name can be retrieved using:<br /><br /> # `codec` is an `ICodec` instance:<br /> charsetName = getUtility(ICodecPreferredCharset,<br /><br /> *<br /><br /> Given any combination of a suggested file name, file data, and content type header, a guess at a reasonable MIME type can be made using:<br /><br /> # `filename` is a suggested file name, or None<br /> # `data` is uploaded data, or None<br /> # `content_type` is a Content-Type header value, or None<br /> #<br /> mimeType = getUtility(IMimeTypeGetter)(<br /> name=filename, data=data, content_type=content_type)<br /><br /> *<br /><br /> Given any combination of a suggested file name, file data, and content type header, a guess at a reasonable charset name can be made using:<br /><br /> # `filename` is a suggested file name, or None<br /> # `data` is uploaded data, or None<br /> # `content_type` is a Content-Type header value, or None<br /> #<br /> charsetName = getUtility(ICharsetGetter)(<br /> name=filename, data=data, content_type=content_type)<br /><br />Retrieving Content Type Information<br />MIME Types<br /><br />We'll start by initializing the interfaces and registrations for the content type interfaces. This is normally done via ZCML.<br /><br /> >>> from zope.mimetype import types<br /> >>> types.setup()<br /><br />A utility is used to retrieve MIME types.<br /><br /> >>> from zope import component<br /> >>> from zope.mimetype import typegetter<br /> >>> from zope.mimetype.interfaces import IMimeTypeGetter<br /> >>> component.provideUtility(typegetter.smartMimeTypeGuesser,<br /> ... provides=IMimeTypeGetter)<br /> >>> mime_getter = component.getUtility(IMimeTypeGetter)<br /><br />To map a particular file name, file contents, and content type to a MIME type.<br /><br /> >>> mime_getter(name='file.txt', data='A text file.',<br /> ... content_type='text/plain')<br /> 'text/plain'<br /><br />In the default implementation if not enough information is given to discern a MIME type, None is returned.<br /><br /> >>> mime_getter() is None<br /> True<br /><br />Character Sets<br /><br />A utility is also used to retrieve character sets (charsets).<br /><br /> >>> from zope.mimetype.interfaces import ICharsetGetter<br /> >>> component.provideUtility(typegetter.charsetGetter,<br /> ... provides=ICharsetGetter)<br /> >>> charset_getter = component.getUtility(ICharsetGetter)<br /><br />To map a particular file name, file contents, and content type to a charset.<br /><br /> >>> charset_getter(name='file.txt', data='This is a text file.',<br /> ... content_type='text/plain;charset=ascii')<br /> 'ascii'<br /><br />In the default implementation if not enough information is given to discern a charset, None is returned.<br /><br /> >>> charset_getter() is None<br /> True<br /><br />Finding Interfaces<br /><br />Given a MIME type we need to be able to find the appropriate interface.<br /><br /> >>> from zope.mimetype.interfaces import IContentTypeInterface<br /> >>> component.getUtility(IContentTypeInterface, name=u'text/plain')<br /> <InterfaceClass zope.mimetype.types.IContentTypeTextPlain><br /><br />It is also possible to enumerate all content type interfaces.<br /><br /> >>> utilities = list(component.getUtilitiesFor(IContentTypeInterface))<br /><br />If you want to find an interface from a MIME string, you can use the utilityies.<br /><br /> >>> component.getUtility(IContentTypeInterface, name='text/plain')<br /> <InterfaceClass zope.mimetype.types.IContentTypeTextPlain><br /><br />Codec handling<br /><br />We can create codecs programatically. Codecs are registered as utilities for ICodec with the name of their python codec.<br /><br /> >>> from zope import component<br /> >>> from zope.mimetype.interfaces import ICodec<br /> >>> from zope.mimetype.codec import addCodec<br /> >>> sorted(component.getUtilitiesFor(ICodec))<br /> []<br /> >>> addCodec('iso8859-1', 'Western (ISO-8859-1)')<br /> >>> codec = component.getUtility(ICodec, name='iso8859-1')<br /> >>> codec<br /> <zope.mimetype.codec.Codec instance at ...><br /> >>><br /> 'iso8859-1'<br /> >>> addCodec('utf-8', 'Unicode (UTF-8)')<br /> >>> codec2 = component.getUtility(ICodec, name='utf-8')<br /><br />We can programmatically add charsets to a given codec. This registers each charset as a named utility for ICharset. It also registers the codec as a utility for ICharsetCodec with the name of the charset.<br /><br /> >>> from zope.mimetype.codec import addCharset<br /> >>> from zope.mimetype.interfaces import ICharset, ICharsetCodec<br /> >>> sorted(component.getUtilitiesFor(ICharset))<br /> []<br /> >>> sorted(component.getUtilitiesFor(ICharsetCodec))<br /> []<br /> >>> addCharset(, 'latin1')<br /> >>> charset = component.getUtility(ICharset, name='latin1')<br /> >>> charset<br /> <zope.mimetype.codec.Charset instance at ...><br /> >>><br /> 'latin1'<br /> >>> component.getUtility(ICharsetCodec, name='latin1') is codec<br /> True<br /><br />When adding a charset we can state that we want that charset to be the preferred charset for its codec.<br /><br /> >>> addCharset(, 'iso8859-1', preferred=True)<br /> >>> addCharset(, 'utf-8', preferred=True)<br /><br />A codec can have at most one preferred charset.<br /><br /> >>> addCharset(, 'test', preferred=True)<br /> Traceback (most recent call last):<br /> ...<br /> ValueError: Codec already has a preferred charset.<br /><br />Preferred charsets are registered as utilities for ICodecPreferredCharset under the name of the python codec.<br /><br /> >>> from zope.mimetype.interfaces import ICodecPreferredCharset<br /> >>> preferred = component.getUtility(ICodecPreferredCharset, name='iso8859-1')<br /> >>> preferred<br /> <zope.mimetype.codec.Charset instance at ...><br /> >>><br /> 'iso8859-1'<br /> >>> sorted(component.getUtilitiesFor(ICodecPreferredCharset))<br /> [(u'iso8859-1', <zope.mimetype.codec.Charset instance at ...>),<br /> (u'utf-8', <zope.mimetype.codec.Charset instance at ...>)]<br /><br />We can look up a codec by the name of its charset:<br /><br /> >>> component.getUtility(ICharsetCodec, name='latin1') is codec<br /> True<br /> >>> component.getUtility(ICharsetCodec, name='utf-8') is codec2<br /> True<br /><br />Or we can look up all codecs:<br /><br /> >>> sorted(component.getUtilitiesFor(ICharsetCodec))<br /> [(u'iso8859-1', <zope.mimetype.codec.Codec instance at ...>),<br /> (u'latin1', <zope.mimetype.codec.Codec instance at ...>),<br /> (u'test', <zope.mimetype.codec.Codec instance at ...>),<br /> (u'utf-8', <zope.mimetype.codec.Codec instance at ...>)]<br /><br />Constraint Functions for Interfaces<br /><br />The zope.mimetype.interfaces module defines interfaces that use some helper functions to define constraints on the accepted data. These helpers are used to determine whether values conform to the what's allowed for parts of a MIME type specification and other parts of a Content-Type header as specified in RFC 2045.<br />Single Token<br /><br />The first is the simplest: the tokenConstraint() function returns True if the ASCII string it is passed conforms to the token production in section 5.1 of the RFC. Let's import the function:<br /><br />>>> from zope.mimetype.interfaces import tokenConstraint<br /><br />Typical token are the major and minor parts of the MIME type and the parameter names for the Content-Type header. The function should return True for these values:<br /><br />>>> tokenConstraint("text")<br />True<br />>>> tokenConstraint("plain")<br />True<br />>>> tokenConstraint("charset")<br />True<br /><br />The function should also return True for unusual but otherwise normal token that may be used in some situations:<br /><br />>>> tokenConstraint("not-your-fathers-token")<br />True<br /><br />It must also allow extension tokens and vendor-specific tokens:<br /><br />>>> tokenConstraint("x-magic")<br />True<br /><br />>>> tokenConstraint("vnd.zope.special-data")<br />True<br /><br />Since we expect input handlers to normalize values to lower case, upper case text is not allowed:<br /><br />>>> tokenConstraint("Text")<br />False<br /><br />Non-ASCII text is also not allowed:<br /><br />>>> tokenConstraint("x80")<br />False<br />>>> tokenConstraint("xC8")<br />False<br />>>> tokenConstraint("xFF")<br />False<br /><br />Note that lots of characters are allowed in tokens, and there are no constraints that the token "look like" something a person would want to read:<br /><br />>>> tokenConstraint(".-.-.-.")<br />True<br /><br />Other characters are disallowed, however, including all forms of whitespace:<br /><br />>>> tokenConstraint("foo bar")<br />False<br />>>> tokenConstraint("footbar")<br />False<br />>>> tokenConstraint("foonbar")<br />False<br />>>> tokenConstraint("foorbar")<br />False<br />>>> tokenConstraint("foox7Fbar")<br />False<br /><br />Whitespace before or after the token is not accepted either:<br /><br />>>> tokenConstraint(" text")<br />False<br />>>> tokenConstraint("plain ")<br />False<br /><br />Other disallowed characters are defined in the tspecials production from the RFC (also in section 5.1):<br /><br />>>> tokenConstraint("(")<br />False<br />>>> tokenConstraint(")")<br />False<br />>>> tokenConstraint("<")<br />False<br />>>> tokenConstraint(">")<br />False<br />>>> tokenConstraint("@")<br />False<br />>>> tokenConstraint(",")<br />False<br />>>> tokenConstraint(";")<br />False<br />>>> tokenConstraint(":")<br />False<br />>>> tokenConstraint("\")<br />False<br />>>> tokenConstraint('"')<br />False<br />>>> tokenConstraint("/")<br />False<br />>>> tokenConstraint("[")<br />False<br />>>> tokenConstraint("]")<br />False<br />>>> tokenConstraint("?")<br />False<br />>>> tokenConstraint("=")<br />False<br /><br />A token must contain at least one character, so tokenConstraint() returns false for an empty string:<br /><br />>>> tokenConstraint("")<br />False<br /><br />MIME Type<br /><br />A MIME type is specified using two tokens separated by a slash; whitespace between the tokens and the slash must be normalized away in the input handler.<br /><br />The mimeTypeConstraint() function is available to test a normalized MIME type value; let's import that function now:<br /><br />>>> from zope.mimetype.interfaces import mimeTypeConstraint<br /><br />Let's test some common MIME types to make sure the function isn't obviously insane:<br /><br />>>> mimeTypeConstraint("text/plain")<br />True<br />>>> mimeTypeConstraint("application/xml")<br />True<br />>>> mimeTypeConstraint("image/svg+xml")<br />True<br /><br />If parts of the MIME type are missing, it isn't accepted:<br /><br />>>> mimeTypeConstraint("text")<br />False<br />>>> mimeTypeConstraint("text/")<br />False<br />>>> mimeTypeConstraint("/plain")<br />False<br /><br />As for individual tokens, whitespace is not allowed:<br /><br />>>> mimeTypeConstraint("foo bar/plain")<br />False<br />>>> mimeTypeConstraint("text/foo bar")<br />False<br /><br />Whitespace is not accepted around the slash either:<br /><br />>>> mimeTypeConstraint("text /plain")<br />False<br />>>> mimeTypeConstraint("text/ plain")<br />False<br /><br />Surrounding whitespace is also not accepted:<br /><br />>>> mimeTypeConstraint(" text/plain")<br />False<br />>>> mimeTypeConstraint("text/plain ")<br />False<br /><br />Minimal IContentInfo Implementation<br /><br />The zope.mimetype.contentinfo module provides a minimal IContentInfo implementation that adds no information to what's provided by a content object. This represents the most conservative content-type policy that might be useful.<br /><br />Let's take a look at how this operates by creating a couple of concrete content-type interfaces:<br /><br />>>> from zope.mimetype import interfaces<br /><br />>>> class ITextPlain(interfaces.IContentTypeEncoded):<br />... """text/plain"""<br /><br />>>> class IApplicationOctetStream(interfaces.IContentType):<br />... """application/octet-stream"""<br /><br />Now, we'll create a minimal content object that provide the necessary information:<br /><br />>>> import zope.interface<br /><br />>>> class Content(object):<br />... zope.interface.implements(interfaces.IContentTypeAware)<br />...<br />... def __init__(self, mimeType, charset=None):<br />... self.mimeType = mimeType<br />... self.parameters = {}<br />... if charset:<br />... self.parameters["charset"] = charset<br /><br />We can now create examples of both encoded and non-encoded content:<br /><br />>>> encoded = Content("text/plain", "utf-8")<br />>>> zope.interface.alsoProvides(encoded, ITextPlain)<br /><br />>>> unencoded = Content("application/octet-stream")<br />>>> zope.interface.alsoProvides(unencoded, IApplicationOctetStream)<br /><br />The minimal IContentInfo implementation only exposes the information available to it from the base content object. Let's take a look at the unencoded content first:<br /><br />>>> from zope.mimetype import contentinfo<br />>>> ci = contentinfo.ContentInfo(unencoded)<br />>>> ci.effectiveMimeType<br />'application/octet-stream'<br />>>> ci.effectiveParameters<br />{}<br />>>> ci.contentType<br />'application/octet-stream'<br /><br />For unencoded content, there is never a codec:<br /><br />>>> print ci.getCodec()<br />None<br /><br />It is also disallowed to try decoding such content:<br /><br />>>> ci.decode("foo")<br />Traceback (most recent call last):<br />...<br />ValueError: no matching codec found<br /><br />Attemping to decode data using an uncoded object causes an exception to be raised:<br /><br />>>> print ci.decode("data")<br />Traceback (most recent call last):<br />...<br />ValueError: no matching codec found<br /><br />If we try this with encoded data, we get somewhat different behavior:<br /><br />>>> ci = contentinfo.ContentInfo(encoded)<br />>>> ci.effectiveMimeType<br />'text/plain'<br />>>> ci.effectiveParameters<br />{'charset': 'utf-8'}<br />>>> ci.contentType<br />'text/plain;charset=utf-8'<br /><br />The getCodec() and decode() methods can be used to handle encoded data using the encoding indicated by the charset parameter. Let's store some UTF-8 data in a variable:<br /><br />>>> utf8_data = unicode("xABxBB", "iso-8859-1").encode("utf-8")<br />>>> utf8_data<br />'xc2xabxc2xbb'<br /><br />We want to be able to decode the data using the IContentInfo object. Let's try getting the corresponding ICodec object using getCodec():<br /><br />>>> codec = ci.getCodec()<br />Traceback (most recent call last):<br />...<br />ValueError: unsupported charset: 'utf-8'<br /><br />So, we can't proceed without some further preparation. What we need is to register an ICharset for UTF-8. The ICharset will need a reference (by name) to a ICodec for UTF-8. So let's create those objects and register them:<br /><br />>>> import codecs<br />>>> from zope.mimetype.i18n import _<br /><br />>>> class Utf8Codec(object):<br />... zope.interface.implements(interfaces.ICodec)<br />...<br />... name = "utf-8"<br />... title = _("UTF-8")<br />...<br />... def __init__(self):<br />... ( self.encode,<br />... self.decode,<br />... self.reader,<br />... self.writer<br />... ) = codecs.lookup(<br /><br />>>> utf8_codec = Utf8Codec()<br /><br />>>> class Utf8Charset(object):<br />... zope.interface.implements(interfaces.ICharset)<br />...<br />... name =<br />... encoding = name<br /><br />>>> utf8_charset = Utf8Charset()<br /><br />>>> import zope.component<br /><br />>>> zope.component.provideUtility(<br />... utf8_codec, interfaces.ICodec,<br />>>> zope.component.provideUtility(<br />... utf8_charset, interfaces.ICharset,<br /><br />Now that that's been initialized, let's try getting the codec again:<br /><br />>>> codec = ci.getCodec()<br />>>><br />'utf-8'<br /><br />>>> codec.decode(utf8_data)<br />(u'xabxbb', 4)<br /><br />We can now check that the decode() method of the IContentInfo will decode the entire data, returning the Unicode representation of the text:<br /><br />>>> ci.decode(utf8_data)<br />u'xabxbb'<br /><br />Another possibilty, of course, is that you have content that you know is encoded text of some sort, but you don't actually know what encoding it's in:<br /><br />>>> encoded2 = Content("text/plain")<br />>>> zope.interface.alsoProvides(encoded2, ITextPlain)<br /><br />>>> ci = contentinfo.ContentInfo(encoded2)<br />>>> ci.effectiveMimeType<br />'text/plain'<br />>>> ci.effectiveParameters<br />{}<br />>>> ci.contentType<br />'text/plain'<br /><br />>>> ci.getCodec()<br />Traceback (most recent call last):<br />...<br />ValueError: charset not known<br /><br />It's also possible that the initial content type information for an object is incorrect for some reason. If the browser provides a content type of "text/plain; charset=utf-8", the content will be seen as encoded. A user correcting this content type using UI elements can cause the content to be considered un-encoded. At this point, there should no longer be a charset parameter to the content type, and the content info object should reflect this, though the previous encoding information will be retained in case the content type should be changed to an encoded type in the future.<br /><br />Let's see how this behavior will be exhibited in this API. We'll start by creating some encoded content:<br /><br />>>> content = Content("text/plain", "utf-8")<br />>>> zope.interface.alsoProvides(content, ITextPlain)<br /><br />We can see that the encoding information is included in the effective MIME type information provided by the content-info object:<br /><br />>>> ci = contentinfo.ContentInfo(content)<br />>>> ci.effectiveMimeType<br />'text/plain'<br />>>> ci.effectiveParameters<br />{'charset': 'utf-8'}<br /><br />We now change the content type information for the object:<br /><br />>>> ifaces = zope.interface.directlyProvidedBy(content)<br />>>> ifaces -= ITextPlain<br />>>> ifaces += IApplicationOctetStream<br />>>> zope.interface.directlyProvides(content, *ifaces)<br />>>> content.mimeType = 'application/octet-stream'<br /><br />At this point, a content type object would provide different information:<br /><br />>>> ci = contentinfo.ContentInfo(content)<br />>>> ci.effectiveMimeType<br />'application/octet-stream'<br />>>> ci.effectiveParameters<br />{}<br /><br />The underlying content type parameters still contain the original encoding information, however:<br /><br />>>> content.parameters<br />{'charset': 'utf-8'}<br /><br />Events and content-type changes<br /><br />The IContentTypeChangedEvent is fired whenever an object's IContentTypeInterface is changed. This includes the cases when a content type interface is applied to an object that doesn't have one, and when the content type interface is removed from an object.<br /><br />Let's start the demonstration by defining a subscriber for the event that simply prints out the information from the event object:<br /><br />>>> def handler(event):<br />... print "changed content type interface:"<br />... print " from:", event.oldContentType<br />... print " to:", event.newContentType<br /><br />We'll also define a simple content object:<br /><br />>>> import zope.interface<br /><br />>>> class IContent(zope.interface.Interface):<br />... pass<br /><br />>>> class Content(object):<br />...<br />... zope.interface.implements(IContent)<br />...<br />... def __str__(self):<br />... return "<MyContent>"<br /><br />>>> obj = Content()<br /><br />We'll also need a couple of content type interfaces:<br /><br />>>> from zope.mimetype import interfaces<br /><br />>>> class ITextPlain(interfaces.IContentTypeEncoded):<br />... """text/plain"""<br />>>> ITextPlain.setTaggedValue("mimeTypes", ["text/plain"])<br />>>> ITextPlain.setTaggedValue("extensions", [".txt"])<br />>>> zope.interface.directlyProvides(<br />... ITextPlain, interfaces.IContentTypeInterface)<br /><br />>>> class IOctetStream(interfaces.IContentType):<br />... """application/octet-stream"""<br />>>> IOctetStream.setTaggedValue("mimeTypes", ["application/octet-stream"])<br />>>> IOctetStream.setTaggedValue("extensions", [".bin"])<br />>>> zope.interface.directlyProvides(<br />... IOctetStream, interfaces.IContentTypeInterface)<br /><br />Let's register our subscriber:<br /><br />>>> import zope.component<br />>>> import zope.component.interfaces<br />>>> zope.component.provideHandler(<br />... handler,<br />... (zope.component.interfaces.IObjectEvent,))<br /><br />Changing the content type interface on an object is handled by the zope.mimetype.event.changeContentType() function. Let's import that module and demonstrate that the expected event is fired appropriately:<br /><br />>>> from zope.mimetype import event<br /><br />Since the object currently has no content type interface, "removing" the interface does not affect the object and the event is not fired:<br /><br />>>> event.changeContentType(obj, None)<br /><br />Setting a content type interface on an object that doesn't have one will cause the event to be fired, with the .oldContentType attribute on the event set to None:<br /><br />>>> event.changeContentType(obj, ITextPlain)<br />changed content type interface:<br /> from: None<br /> to: <InterfaceClass __builtin__.ITextPlain><br /><br />Calling the changeContentType() function again with the same "new" content type interface causes no change, so the event is not fired again:<br /><br />>>> event.changeContentType(obj, ITextPlain)<br /><br />Providing a new interface does cause the event to be fired again:<br /><br />>>> event.changeContentType(obj, IOctetStream)<br />changed content type interface:<br /> from: <InterfaceClass __builtin__.ITextPlain><br /> to: <InterfaceClass __builtin__.IOctetStream><br /><br />Similarly, removing the content type interface triggers the event as well:<br /><br />>>> event.changeContentType(obj, None)<br />changed content type interface:<br /> from: <InterfaceClass __builtin__.IOctetStream><br /> to: None<br /><br />MIME type and character set extraction<br /><br />The zope.mimetype.typegetter module provides a selection of MIME type extractors and charset extractors. These may be used to determine what the MIME type and character set for uploaded data should be.<br /><br />These two interfaces represent the site policy regarding interpreting upload data in the face of missing or inaccurate input.<br /><br />Let's go ahead and import the module:<br /><br />>>> from zope.mimetype import typegetter<br /><br />MIME types<br /><br />There are a number of interesting MIME-type extractors:<br /><br />mimeTypeGetter()<br /> A minimal extractor that never attempts to guess.<br />mimeTypeGuesser()<br /> An extractor that tries to guess the content type based on the name and data if the input contains no content type information.<br />smartMimeTypeGuesser()<br /> An extractor that checks the content for a variety of constructs to try and refine the results of the mimeTypeGuesser(). This is able to do things like check for XHTML that's labelled as HTML in upload data.<br /><br />mimeTypeGetter()<br /><br />We'll start with the simplest, which does no content-based guessing at all, but uses the information provided by the browser directly. If the browser did not provide any content-type information, or if it cannot be parsed, the extractor simply asserts a "safe" MIME type of application/octet-stream. (The rationale for selecting this type is that since there's really nothing productive that can be done with it other than download it, it's impossible to mis-interpret the data.)<br /><br />When there's no information at all about the content, the extractor returns None:<br /><br />>>> print typegetter.mimeTypeGetter()<br />None<br /><br />Providing only the upload filename or data, or both, still produces None, since no guessing is being done:<br /><br />>>> print typegetter.mimeTypeGetter(name="file.html")<br />None<br /><br />>>> print typegetter.mimeTypeGetter(data="<html>...</html>")<br />None<br /><br />>>> print typegetter.mimeTypeGetter(<br />... name="file.html", data="<html>...</html>")<br />None<br /><br />If a content type header is available for the input, that is used since that represents explicit input from outside the application server. The major and minor parts of the content type are extracted and returned as a single string:<br /><br />>>> typegetter.mimeTypeGetter(content_type="text/plain")<br />'text/plain'<br /><br />>>> typegetter.mimeTypeGetter(content_type="text/plain; charset=utf-8")<br />'text/plain'<br /><br />If the content-type information is provided but malformed (not in conformance with RFC 2822), it is ignored, since the intent cannot be reliably guessed:<br /><br />>>> print typegetter.mimeTypeGetter(content_type="foo bar")<br />None<br /><br />This combines with ignoring the other values that may be provided as expected:<br /><br />>>> print typegetter.mimeTypeGetter(<br />... name="file.html", data="<html>...</html>", content_type="foo bar")<br />None<br /><br />mimeTypeGuesser()<br /><br />A more elaborate extractor that tries to work around completely missing information can be found as the mimeTypeGuesser() function. This function will only guess if there is no usable content type information in the input. This extractor can be thought of as having the following pseudo-code:<br /><br />def mimeTypeGuesser(name=None, data=None, content_type=None):<br /> type = mimeTypeGetter(name=name, data=data, content_type=content_type)<br /> if type is None:<br /> type = guess the content type<br /> return type<br /><br />Let's see how this affects the results we saw earlier. When there's no input to use, we still get None:<br /><br />>>> print typegetter.mimeTypeGuesser()<br />None<br /><br />Providing only the upload filename or data, or both, now produces a non-None guess for common content types:<br /><br />>>> typegetter.mimeTypeGuesser(name="file.html")<br />'text/html'<br /><br />>>> typegetter.mimeTypeGuesser(data="<html>...</html>")<br />'text/html'<br /><br />>>> typegetter.mimeTypeGuesser(name="file.html", data="<html>...</html>")<br />'text/html'<br /><br />Note that if the filename and data provided separately produce different MIME types, the result of providing both will be one of those types, but which is unspecified:<br /><br />>>> mt_1 = typegetter.mimeTypeGuesser(name="file.html")<br />>>> mt_1<br />'text/html'<br /><br />>>> mt_2 = typegetter.mimeTypeGuesser(data="<?xml version='1.0'?>...")<br />>>> mt_2<br />'text/xml'<br /><br />>>> mt = typegetter.mimeTypeGuesser(<br />... data="<?xml version='1.0'?>...", name="file.html")<br />>>> mt in (mt_1, mt_2)<br />True<br /><br />If a content type header is available for the input, that is used in the same way as for the mimeTypeGetter() function:<br /><br />>>> typegetter.mimeTypeGuesser(content_type="text/plain")<br />'text/plain'<br /><br />>>> typegetter.mimeTypeGuesser(content_type="text/plain; charset=utf-8")<br />'text/plain'<br /><br />If the content-type information is provided but malformed, it is ignored:<br /><br />>>> print typegetter.mimeTypeGetter(content_type="foo bar")<br />None<br /><br />When combined with values for the filename or content data, those are still used to provide reasonable guesses for the content type:<br /><br />>>> typegetter.mimeTypeGuesser(name="file.html", content_type="foo bar")<br />'text/html'<br /><br />>>> typegetter.mimeTypeGuesser(<br />... data="<html>...</html>", content_type="foo bar")<br />'text/html'<br /><br />Information from a parsable content-type is still used even if a guess from the data or filename would provide a different or more-refined result:<br /><br />>>> typegetter.mimeTypeGuesser(<br />... data="GIF89a...", content_type="application/octet-stream")<br />'application/octet-stream'<br /><br />smartMimeTypeGuesser()<br /><br />The smartMimeTypeGuesser() function applies more knowledge to the process of determining the MIME-type to use. Essentially, it takes the result of the mimeTypeGuesser() function and attempts to refine the content-type based on various heuristics.<br /><br />We still see the basic behavior that no input produces None:<br /><br />>>> print typegetter.smartMimeTypeGuesser()<br />None<br /><br />An unparsable content-type is still ignored:<br /><br />>>> print typegetter.smartMimeTypeGuesser(content_type="foo bar")<br />None<br /><br />The interpretation of uploaded data will be different in at least some interesting cases. For instance, the mimeTypeGuesser() function provides these results for some XHTML input data:<br /><br />>>> typegetter.mimeTypeGuesser(<br />... data="<?xml version='1.0' encoding='utf-8'?><html>...</html>",<br />... name="file.html")<br />'text/html'<br /><br />The smart extractor is able to refine this into more usable data:<br /><br />>>> typegetter.smartMimeTypeGuesser(<br />... data="<?xml version='1.0' encoding='utf-8'?>...",<br />... name="file.html")<br />'application/xhtml+xml'<br /><br />In this case, the smart extractor has refined the information determined from the filename using information from the uploaded data. The specific approach taken by the extractor is not part of the interface, however.<br />charsetGetter()<br /><br />If you're interested in the character set of textual data, you can use the charsetGetter function (which can also be registered as the ICharsetGetter utility):<br /><br />The simplest case is when the character set is already specified in the content type.<br /><br /> >>> typegetter.charsetGetter(content_type='text/plain; charset=mambo-42')<br /> 'mambo-42'<br /><br />Note that the charset name is lowercased, because all the default ICharset and ICharsetCodec utilities are registered for lowercase names.<br /><br /> >>> typegetter.charsetGetter(content_type='text/plain; charset=UTF-8')<br /> 'utf-8'<br /><br />If it isn't, charsetGetter can try to guess by looking at actual data<br /><br /> >>> typegetter.charsetGetter(content_type='text/plain', data='just text')<br /> 'ascii'<br /><br /> >>> typegetter.charsetGetter(content_type='text/plain', data='xe2x98xba')<br /> 'utf-8'<br /><br /> >>> import codecs<br /> >>> typegetter.charsetGetter(data=codecs.BOM_UTF16_BE + 'x12x34')<br /> 'utf-16be'<br /><br /> >>> typegetter.charsetGetter(data=codecs.BOM_UTF16_LE + 'x12x34')<br /> 'utf-16le'<br /><br />If the character set cannot be determined, charsetGetter returns None.<br /><br /> >>> typegetter.charsetGetter(content_type='text/plain', data='xff')<br /> >>> typegetter.charsetGetter()<br /><br />Source for MIME type interfaces<br /><br />Some sample interfaces have been created in the zope.mimetype.tests module for use in this test. Let's import them:<br /><br />>>> from zope.mimetype.tests import (<br />... ISampleContentTypeOne, ISampleContentTypeTwo)<br /><br />The source should only include IContentTypeInterface interfaces that have been registered. Let's register one of these two interfaces so we can test this:<br /><br />>>> import zope.component<br />>>> from zope.mimetype.interfaces import IContentTypeInterface<br /><br />>>> zope.component.provideUtility(<br />... ISampleContentTypeOne, IContentTypeInterface, name="type/one")<br /><br />>>> zope.component.provideUtility(<br />... ISampleContentTypeOne, IContentTypeInterface, name="type/two")<br /><br />We should see that these interfaces are included in the source:<br /><br />>>> from zope.mimetype import source<br /><br />>>> s = source.ContentTypeSource()<br /><br />>>> ISampleContentTypeOne in s<br />True<br />>>> ISampleContentTypeTwo in s<br />False<br /><br />Interfaces that do not implement the IContentTypeInterface are not included in the source:<br /><br />>>> import zope.interface<br />>>> class ISomethingElse(zope.interface.Interface):<br />... """This isn't a content type interface."""<br /><br />>>> ISomethingElse in s<br />False<br /><br />The source is iterable, so we can get a list of the values:<br /><br />>>> values = list(s)<br /><br />>>> len(values)<br />1<br />>>> values[0] is ISampleContentTypeOne<br />True<br /><br />We can get terms for the allowed values:<br /><br />>>> terms = source.ContentTypeTerms(s, None)<br />>>> t = terms.getTerm(ISampleContentTypeOne)<br />>>> terms.getValue(t.token) is ISampleContentTypeOne<br />True<br /><br />Interfaces that are not in the source cause an error when a term is requested:<br /><br />>>> terms.getTerm(ISomethingElse)<br />Traceback (most recent call last):<br />...<br />LookupError: value is not an element in the source<br /><br />The term provides a token based on the module name of the interface:<br /><br />>>> t.token<br />'zope.mimetype.tests.ISampleContentTypeOne'<br /><br />The term also provides the title based on the "title" tagged value from the interface:<br /><br />>>> t.title<br />u'Type One'<br /><br />Each interface provides a list of MIME types with which the interface is associated. The term object provides access to this list:<br /><br />>>> t.mimeTypes<br />['type/one', 'type/foo']<br /><br />A list of common extensions for files of this type is also available, though it may be empty:<br /><br />>>> t.extensions<br />[]<br /><br />The term's value, of course, is the interface passed in:<br /><br />>>> t.value is ISampleContentTypeOne<br />True<br /><br />This extended term API is defined by the IContentTypeTerm interface:<br /><br />>>> from zope.mimetype.interfaces import IContentTypeTerm<br />>>> IContentTypeTerm.providedBy(t)<br />True<br /><br />The value can also be retrieved using the getValue() method:<br /><br />>>> iface = terms.getValue('zope.mimetype.tests.ISampleContentTypeOne')<br />>>> iface is ISampleContentTypeOne<br />True<br /><br />Attempting to retrieve an interface that isn't in the source using the terms object generates a LookupError:<br /><br />>>> terms.getValue('zope.mimetype.tests.ISampleContentTypeTwo')<br />Traceback (most recent call last):<br />...<br />LookupError: token does not represent an element in the source<br /><br />Attempting to look up a junk token also generates an error:<br /><br />>>> terms.getValue('')<br />Traceback (most recent call last):<br />...<br />LookupError: could not import module for token<br /><br />TranslatableSourceSelectWidget<br /><br />TranslatableSourceSelectWidget is a SourceSelectWidget that translates and sorts the choices.<br /><br />We will borrow the boring set up code from the SourceSelectWidget test (source.txt in zope.formlib).<br /><br /> >>> import zope.interface<br /> >>> import zope.component<br /> >>> import zope.schema<br /> >>> import zope.schema.interfaces<br /><br /> >>> class SourceList(list):<br /> ... zope.interface.implements(zope.schema.interfaces.IIterableSource)<br /><br /> >>> import zope.publisher.interfaces.browser<br /> >>> from zope.browser.interfaces import ITerms<br /> >>> from zope.schema.vocabulary import SimpleTerm<br /> >>> class ListTerms:<br /> ...<br /> ... zope.interface.implements(ITerms)<br /> ...<br /> ... def __init__(self, source, request):<br /> ... pass # We don't actually need the source or the request :)<br /> ...<br /> ... def getTerm(self, value):<br /> ... title = unicode(value)<br /> ... try:<br /> ... token = title.encode('base64').strip()<br /> ... except binascii.Error:<br /> ... raise LookupError(token)<br /> ... return SimpleTerm(value, token=token, title=title)<br /> ...<br /> ... def getValue(self, token):<br /> ... return token.decode('base64')<br /><br /> >>> zope.component.provideAdapter(<br /> ... ListTerms,<br /> ... (SourceList, zope.publisher.interfaces.browser.IBrowserRequest))<br /><br /> >>> dog = zope.schema.Choice(<br /> ... __name__ = 'dog',<br /> ... title=u"Dogs",<br /> ... source=SourceList(['spot', 'bowser', 'prince', 'duchess', 'lassie']),<br /> ... )<br /> >>> dog = dog.bind(object())<br /><br />Now that we have a field and a working source, we can construct and render a widget.<br /><br /> >>> from zope.mimetype.widget import TranslatableSourceSelectWidget<br /> >>> from zope.publisher.browser import TestRequest<br /> >>> request = TestRequest()<br /> >>> widget = TranslatableSourceSelectWidget(<br /> ... dog, dog.source, request)<br /><br /> >>> print widget()<br /> <div><br /> <div class="value"><br /> <select id="" name="" size="5" ><br /> <option value="Ym93c2Vy">bowser</option><br /> <option value="ZHVjaGVzcw==">duchess</option><br /> <option value="bGFzc2ll">lassie</option><br /> <option value="cHJpbmNl">prince</option><br /> <option value="c3BvdA==">spot</option><br /> </select><br /> </div><br /> <input name="" type="hidden" value="1" /><br /> </div><br /><br />Note that the options are ordered alphabetically.<br /><br />If the field is not required, we will also see a special choice labeled "(nothing selected)" at the top of the list<br /><br /> >>> dog.required = False<br /> >>> print widget()<br /> <div><br /> <div class="value"><br /> <select id="" name="" size="5" ><br /> <option selected="selected" value="">(nothing selected)</option><br /> <option value="Ym93c2Vy">bowser</option><br /> <option value="ZHVjaGVzcw==">duchess</option><br /> <option value="bGFzc2ll">lassie</option><br /> <option value="cHJpbmNl">prince</option><br /> <option value="c3BvdA==">spot</option><br /> </select><br /> </div><br /> <input name="" type="hidden" value="1" /><br /> </div><br /><br />The utils module contains various helpers for working with data goverened by MIME content type information, as found in the HTTP Content-Type header: mime types and character sets.<br /><br />The decode function takes a string and an IANA character set name and returns a unicode object decoded from the string, using the codec associated with the character set name. Errors will generally arise from the unicode conversion rather than the mapping of character set to codec, and will be LookupErrors (the character set did not cleanly convert to a codec that Python knows about) or UnicodeDecodeErrors (the string included characters that were not in the range of the codec associated with the character set).<br /><br /> >>> original = 'This is an o with a slash through it: xb8.'<br /> >>> charset = 'Latin-7' # Baltic Rim or iso-8859-13<br /> >>> from zope.mimetype import utils<br /> >>> utils.decode(original, charset)<br /> u'This is an o with a slash through it: xf8.'<br /> >>> utils.decode(original, 'foo bar baz')<br /> Traceback (most recent call last):<br /> ...<br /> LookupError: unknown encoding: foo bar baz<br /> >>> utils.decode(original, 'iso-ir-6') # alias for ASCII<br /> ... # doctest: +ELLIPSIS<br /> Traceback (most recent call last):<br /> ...<br /> UnicodeDecodeError: 'ascii' codec can't decode...

Requirements: No special requirements
Platforms: *nix, Linux
Keyword: Character Charset Class Codec Content Function Gtgtgt Import Information Input Instance Interface Interfaces Ltoption Object Print Recent Token Zopemimetypeinterfaces
Users rating: 0/10

License: Freeware Size: 61.44 KB
Miscellaneous  -  Extract a inner function from a class 1.1
This function can extract a inner function from a class or a function. It may be useful when writing a unit test code.
Libraries  -  Gtk2::Ex::MindMapView::Content 0.000001
Gtk2::Ex::MindMapView::Content is a base class for content objects. SYNOPSIS use base Gtk2::Ex::MindMapView::Content; This module is internal to Gtk2::Ex::MindMapView. It is the base class for objects that show content and offers several...
50.18 KB  
Programming  -  dolmen.forms.base 1.0 Beta 2
dolmen.forms.base is a package in charge of providing basic functionalities to work with zeam.form Forms. From the form to the field dolmen.forms.base provides few functions dedicated to the task of applying dict datas to object...
10.24 KB  
Programming  -  megrok.layout 1.2.0
The megrok.layout package provides a simple way to write view components which can be included into a defined layout. It turns around two main components : the Page and the Layout. Layout The layout is a component allowing you to...
20.48 KB  
Content Management  -  Frog CMS for Scripts 0.9.5
Frog is a small and simple CMS for everyone that need only a CMS without all other big thing that we don't need. You can manage all you pages with a unlimited multi-level structure. The url is really nice displayed for search engine. This is a...
542.72 KB  
Libraries  -  Class::CGI 0.20
Class::CGI is a Perl module to fetch objects from your CGI object. SYNOPSIS use Class::CGI handlers => { customer_id => My::Customer::Handler }; my $cgi = Class::CGI->new; my $customer = $cgi->param(customer_id); my $name =...
17.41 KB  
Libraries  -  Class::InsideOut 1.02
Class::InsideOut is a Perl module with a safe, simple inside-out object construction kit. SYNOPSIS package My::Class; use Class::InsideOut qw( public private register id ); public name => my %name; # accessor: name() private age => my...
48.13 KB  
Content Management  -  Caravel 3.2
Caravel is a enterprise-level Content Management System with an intuitive user interface, designed to allow non-technical users to maintain website content. Caravel allows admins to centrally maintain thousands of sites off one code-base. You can...
Development Tools  -  Fuzzy Approximation 1.0
Here we have an unknown function but we can have every value of function respect to every input. so there I used a fuzzy approximation method Ito approximate the function, here I used sin function to compare answers.there is a function "isinrange"...
10 KB  
Development Tools  -  configInputParser 1.0
This function loads an XML file and yields an inputParser object configured according to its contents.All R2007a inputParser configurable properties and argument types and options are handled.Typical usage:>> myIp = configInputParser('myConfig.xml);
10 KB  
Linux Software  -  wpCache® WordPress HTTP Cache 1.9
wpCache® is a high-performance, distributed object, caching system application, generic in nature, but intended for use in speeding up dynamic web applications, by decreasing database load time. wpCache® decreases dramatically the page...
3.51 MB  
Linux Software  -  Polling Autodialer Software 3.4
ICTBroadcast Auto Dialer software has a survey campaign for telephone surveys and polls. This auto dialer software automatically dials a list of numbers and asks them a set of questions that they can respond to, by using their telephone keypad....
488 B  
Linux Software  -  Total Video Converter Mac Free 3.5.5
Total Video Converter Mac Free developed by EffectMatrix Ltd is the official legal version of Total Video Converter which was a globally recognized brand since 2006. Total Video Converter Mac Free is a free but powerful all-in-one video...
17.7 MB  
Linux Software  -  Skeith mod_log_sql Analyzer 2.10beta2
Skeith is a php based front end for analyzing logs for Apache using mod_log_sql.
47.5 KB  
Linux Software  -  SLAX 6.0+
Slax is a modern, portable, small and fast Linux operating system with a modular approach and outstanding design. Despite its small size, Slax provides a wide collection of pre-installed software for daily use, including a well organized graphical...
190 KB  
Network & Internet  -  Free WiFi Hotspot 3.3.1
Free WiFi Hotspot is a super easy solution to turn your laptop or notebook into a portable Wi-Fi hotspot, wirelessly sharing your internet connections like DSL, Cable, Bluetooth, Mobile Broadband Card, Dial-Up, etc. through the built-in wireless...
1.04 MB  
Network & Internet  -  Easy Uploads 1.8
Easy uploads is a file storage media streaming application designed by Filestreamers that allows you to upload, store, and stream your files from their virtually unlimited file storage server. Easy Uploads can backup,share, and stream your files...
615.97 KB  
Network & Internet  -  PacketFence ZEN 3.1.0
PacketFence is a fully supported, trusted, Free and Open Source network access control (NAC) system. Boosting an impressive feature set including a captive-portal for registration and remediation, centralized wired and wireless management, 802.1X...
1024 MB  
Network & Internet  -  django-dbstorage 1.3
A Django file storage backend for files in the database.
10.24 KB  
Network & Internet  -  SQL Inject Me 0.4.5
SQL Inject Me is a Firefox extension used to test for SQL Injection vulnerabilities. The tool works by submitting your HTML forms and substituting the form value with strings that are representative of an SQL Injection attack.
133.12 KB