當前位置: 首頁>>代碼示例>>Python>>正文


Python mimetools.Message方法代碼示例

本文整理匯總了Python中mimetools.Message方法的典型用法代碼示例。如果您正苦於以下問題:Python mimetools.Message方法的具體用法?Python mimetools.Message怎麽用?Python mimetools.Message使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mimetools的用法示例。


在下文中一共展示了mimetools.Message方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: open_local_file

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def open_local_file(self, req):
        host = req.get_host()
        file = req.get_selector()
        localfile = url2pathname(file)
        stats = os.stat(localfile)
        size = stats[stat.ST_SIZE]
        modified = rfc822.formatdate(stats[stat.ST_MTIME])
        mtype = mimetypes.guess_type(file)[0]
        stats = os.stat(localfile)
        headers = mimetools.Message(StringIO(
            'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
            (mtype or 'text/plain', size, modified)))
        if host:
            host, port = splitport(host)
        if not host or \
           (not port and socket.gethostbyname(host) in self.get_names()):
            return addinfourl(open(localfile, 'rb'),
                              headers, 'file:'+file)
        raise URLError('file not on local host') 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:21,代碼來源:urllib2.py

示例2: read_multi

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def read_multi(self, environ, keep_blank_values, strict_parsing):
        """Internal: read a part that is itself multipart."""
        ib = self.innerboundary
        if not valid_boundary(ib):
            raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,)
        self.list = []
        if self.qs_on_post:
            for key, value in urlparse.parse_qsl(self.qs_on_post,
                                self.keep_blank_values, self.strict_parsing):
                self.list.append(MiniFieldStorage(key, value))
            FieldStorageClass = None

        klass = self.FieldStorageClass or self.__class__
        part = klass(self.fp, {}, ib,
                     environ, keep_blank_values, strict_parsing)
        # Throw first part away
        while not part.done:
            headers = rfc822.Message(self.fp)
            part = klass(self.fp, headers, ib,
                         environ, keep_blank_values, strict_parsing)
            self.list.append(part)
        self.skip_lines() 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:24,代碼來源:cgi.py

示例3: __init__

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def __init__(self, response_file=None, **kwds):
    """Initializer.

    Args:
      response_file: A file-like object that contains the full response
        generated by the user application request handler.  If present
        the headers and body are set from this value, although the values
        may be further overridden by the keyword parameters.
      kwds: All keywords are mapped to attributes of AppServerResponse.
    """
    self.status_code = 200
    self.status_message = 'Good to go'
    self.large_response = False

    if response_file:
      self.SetResponse(response_file)
    else:
      self.headers = mimetools.Message(cStringIO.StringIO())
      self.body = None

    for name, value in kwds.iteritems():
      setattr(self, name, value) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:24,代碼來源:dev_appserver.py

示例4: Errors

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def Errors(self):
    """A list containing the errors associated with the rejection.

    Intended to mimic those returned from an API in production in Google's API
    infrastructure.

    Returns:
      A list with a single element that is a dictionary containing the error
        information.
    """
    return [
        {
            'domain': 'global',
            'reason': 'invalidParameter',
            'message': self.Message(),
            'locationType': 'parameter',
            'location': self.parameter_name,
        },
    ] 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:21,代碼來源:dev_appserver_apiserver.py

示例5: getbodyparts

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def getbodyparts(self):
        """Only for multipart messages: return the message's body as a
        list of SubMessage objects.  Each submessage object behaves
        (almost) as a Message object."""
        if self.getmaintype() != 'multipart':
            raise Error, 'Content-Type is not multipart/*'
        bdry = self.getparam('boundary')
        if not bdry:
            raise Error, 'multipart/* without boundary param'
        self.fp.seek(self.startofbody)
        mf = multifile.MultiFile(self.fp)
        mf.push(bdry)
        parts = []
        while mf.next():
            n = "%s.%r" % (self.number, 1 + len(parts))
            part = SubMessage(self.folder, n, mf)
            parts.append(part)
        mf.pop()
        return parts 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:21,代碼來源:mhlib.py

示例6: ftp_open

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def ftp_open(self, req):
        host = req.get_host()
        if not host:
            raise IOError('ftp error', 'no host given')
        # XXX handle custom username & password
        try:
            host = socket.gethostbyname(host)
        except socket.error(msg):
            raise URLError(msg)
        host, port = splitport(host)
        if port is None:
            port = ftplib.FTP_PORT
        path, attrs = splitattr(req.get_selector())
        path = unquote(path)
        dirs = path.split('/')
        dirs, file = dirs[:-1], dirs[-1]
        if dirs and not dirs[0]:
            dirs = dirs[1:]
        user = passwd = '' # XXX
        try:
            fw = self.connect_ftp(user, passwd, host, port, dirs)
            type = file and 'I' or 'D'
            for attr in attrs:
                attr, value = splitattr(attr)
                if attr.lower() == 'type' and \
                   value in ('a', 'A', 'i', 'I', 'd', 'D'):
                    type = value.upper()
            fp, retrlen = fw.retrfile(file, type)
            headers = ""
            mtype = mimetypes.guess_type(req.get_full_url())[0]
            if mtype:
                headers += "Content-Type: %s\n" % mtype
            if retrlen is not None and retrlen >= 0:
                headers += "Content-Length: %d\n" % retrlen
            sf = StringIO(headers)
            headers = mimetools.Message(sf)
            return addinfourl(fp, headers, req.get_full_url())
        except ftplib.all_errors(msg):
            raise IOError(('ftp error', msg), sys.exc_info()[2]) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:41,代碼來源:urllib2.py

示例7: SetResponse

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def SetResponse(self, response_file):
    """Sets headers and body from the response file.

    Args:
      response_file: File like object to set body and headers from.
    """
    self.headers = mimetools.Message(response_file)
    self.body = response_file 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:10,代碼來源:dev_appserver.py

示例8: GetAllHeaders

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def GetAllHeaders(message, name):
  """Get all headers of a given name in a message.

  Args:
    message: A mimetools.Message object.
    name: The name of the header.

  Yields:
    A sequence of values of all headers with the given name.
  """
  for header_line in message.getallmatchingheaders(name):
    yield header_line.split(':', 1)[1].strip() 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:14,代碼來源:dev_appserver.py

示例9: Message

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def Message(self): raise NotImplementedError 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:3,代碼來源:dev_appserver_apiserver.py

示例10: BuildCGIRequest

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def BuildCGIRequest(base_env_dict, request, dev_appserver):
  """Build a CGI request to Call a method on an SPI backend.

  Args:
    base_env_dict: CGI environment dict
    request: ApiRequest to be converted to a CGI request
    dev_appserver: Handle to dev_appserver to generate CGI request.

  Returns:
    dev_appserver.AppServerRequest internal redirect object
  """
  if request.headers is None:
    request.headers = {}


  request.headers['Content-Type'] = 'application/json'
  url = SPI_ROOT_FORMAT % (request.port, request.path)
  base_env_dict['REQUEST_METHOD'] = 'POST'






  header_outfile = cStringIO.StringIO()
  body_outfile = cStringIO.StringIO()
  WriteHeaders(request.headers, header_outfile, len(request.body))
  body_outfile.write(request.body)
  header_outfile.seek(0)
  body_outfile.seek(0)
  return dev_appserver.AppServerRequest(
      url, None, mimetools.Message(header_outfile), body_outfile) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:34,代碼來源:dev_appserver_apiserver.py

示例11: open_local_file

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def open_local_file(self, req):
        import email.utils
        import mimetypes
        host = req.get_host()
        filename = req.get_selector()
        localfile = url2pathname(filename)
        try:
            stats = os.stat(localfile)
            size = stats.st_size
            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
            mtype = mimetypes.guess_type(filename)[0]
            headers = mimetools.Message(StringIO(
                'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
                (mtype or 'text/plain', size, modified)))
            if host:
                host, port = splitport(host)
            if not host or \
                (not port and _safe_gethostbyname(host) in self.get_names()):
                if host:
                    origurl = 'file://' + host + filename
                else:
                    origurl = 'file://' + filename
                return addinfourl(open(localfile, 'rb'), headers, origurl)
        except OSError, msg:
            # urllib2 users shouldn't expect OSErrors coming from urlopen()
            raise URLError(msg) 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:28,代碼來源:urllib2.py

示例12: noheaders

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def noheaders():
    """Return an empty mimetools.Message object."""
    global _noheaders
    if _noheaders is None:
        import mimetools
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        _noheaders = mimetools.Message(StringIO(), 0)
        _noheaders.fp.close()   # Recycle file descriptor
    return _noheaders


# Utility classes 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:17,代碼來源:urllib.py

示例13: serve

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def serve(port, callback=None, completer=None):
    import BaseHTTPServer, mimetools, select

    # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
    class Message(mimetools.Message):
        def __init__(self, fp, seekable=1):
            Message = self.__class__
            Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
            self.encodingheader = self.getheader('content-transfer-encoding')
            self.typeheader = self.getheader('content-type')
            self.parsetype()
            self.parseplist()

    class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def send_document(self, title, contents):
            try:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(html.page(title, contents))
            except IOError: pass

        def do_GET(self):
            path = self.path
            if path[-5:] == '.html': path = path[:-5]
            if path[:1] == '/': path = path[1:]
            if path and path != '.':
                try:
                    obj = locate(path, forceload=1)
                except ErrorDuringImport, value:
                    self.send_document(path, html.escape(str(value)))
                    return
                if obj:
                    self.send_document(describe(obj), html.document(obj, path))
                else:
                    self.send_document(path,
'no Python documentation found for %s' % repr(path))
            else: 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:40,代碼來源:pydoc.py

示例14: openmessage

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def openmessage(self, n):
        """Open a message -- returns a Message object."""
        return Message(self, n) 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:5,代碼來源:mhlib.py

示例15: __init__

# 需要導入模塊: import mimetools [as 別名]
# 或者: from mimetools import Message [as 別名]
def __init__(self, f, n, fp = None):
        """Constructor."""
        self.folder = f
        self.number = n
        if fp is None:
            path = f.getmessagefilename(n)
            fp = open(path, 'r')
        mimetools.Message.__init__(self, fp) 
開發者ID:glmcdona,項目名稱:meddle,代碼行數:10,代碼來源:mhlib.py


注:本文中的mimetools.Message方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。