⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.py

📁 Mod_python is an Apache module that embeds the Python interpreter within the server. With mod_python
💻 PY
📖 第 1 页 / 共 2 页
字号:
 # vim: set sw=4 expandtab : # # Copyright 2004 Apache Software Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License.  You # may obtain a copy of the License at # #      http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied.  See the License for the specific language governing # permissions and limitations under the License. # # Originally developed by Gregory Trubetskoy. # # $Id: util.py 478129 2006-11-22 11:15:54Z grahamd $import _apacheimport apacheimport cStringIOimport tempfileimport refrom types import *from exceptions import *parse_qs = _apache.parse_qsparse_qsl = _apache.parse_qsl# Maximum line length for reading. (64KB)# Fixes memory error when upload large files such as 700+MB ISOs.readBlockSize = 65368""" The classes below are a (almost) a drop-in replacement for the    standard cgi.py FieldStorage class. They should have pretty much the    same functionality.    These classes differ in that unlike cgi.FieldStorage, they are not    recursive. The class FieldStorage contains a list of instances of    Field class. Field class is incapable of storing anything in it.    These objects should be considerably faster than the ones in cgi.py    because they do not expect CGI environment, and are    optimized specifically for Apache and mod_python."""class Field:    def __init__(self, name, *args, **kwargs):        self.name = name        # Some third party packages such as Trac create        # instances of the Field object and insert it        # directly into the list of form fields. To        # maintain backward compatibility check for        # where more than just a field name is supplied        # and invoke an additional initialisation step        # to process the arguments. Ideally, third party        # code should use the add_field() method of the        # form, but if they need to maintain backward        # compatibility with older versions of mod_python        # they will not have a choice but to use old        # way of doing things and thus we need this code        # for the forseeable future to cope with that.        if args or kwargs:            self.__bc_init__(*args, **kwargs)    def __bc_init__(self, file, ctype, type_options,                    disp, disp_options, headers = {}):       self.file = file       self.type = ctype       self.type_options = type_options       self.disposition = disp       self.disposition_options = disp_options       if disp_options.has_key("filename"):           self.filename = disp_options["filename"]       else:           self.filename = None       self.headers = headers    def __repr__(self):        """Return printable representation."""        return "Field(%s, %s)" % (`self.name`, `self.value`)    def __getattr__(self, name):        if name != 'value':            raise AttributeError, name        if self.file:            self.file.seek(0)            value = self.file.read()            self.file.seek(0)        else:            value = None        return value    def __del__(self):        self.file.close()class StringField(str):    """ This class is basically a string with    added attributes for compatibility with std lib cgi.py. Basically, this    works the opposite of Field, as it stores its data in a string, but creates    a file on demand. Field creates a value on demand and stores data in a file.    """    filename = None    headers = {}    ctype = "text/plain"    type_options = {}    disposition = None    disp_options = None        # I wanted __init__(name, value) but that does not work (apparently, you    # cannot subclass str with a constructor that takes >1 argument)    def __init__(self, value):        '''Create StringField instance. You'll have to set name yourself.'''        str.__init__(self, value)        self.value = value    def __getattr__(self, name):        if name != 'file':            raise AttributeError, name        self.file = cStringIO.StringIO(self.value)        return self.file            def __repr__(self):        """Return printable representation (to pass unit tests)."""        return "Field(%s, %s)" % (`self.name`, `self.value`)class FieldList(list):    def __init__(self):        self.__table = None        list.__init__(self)    def table(self):        if self.__table is None:            self.__table = {}            for item in self:                if item.name in self.__table:                    self.__table[item.name].append(item)                else:                    self.__table[item.name] = [item]        return self.__table    def __delitem__(self, *args):        self.__table = None        return list.__delitem__(self, *args)    def __delslice__(self, *args):        self.__table = None        return list.__delslice__(self, *args)    def __iadd__(self, *args):        self.__table = None        return list.__iadd__(self, *args)    def __imul__(self, *args):        self.__table = None        return list.__imul__(self, *args)    def __setitem__(self, *args):        self.__table = None        return list.__setitem__(self, *args)    def __setslice__(self, *args):        self.__table = None        return list.__setslice__(self, *args)    def append(self, *args):        self.__table = None        return list.append(self, *args)    def extend(self, *args):        self.__table = None        return list.extend(self, *args)    def insert(self, *args):        self.__table = None        return list.insert(self, *args)    def pop(self, *args):        self.__table = None        return list.pop(self, *args)    def remove(self, *args):        self.__table = None        return list.remove(self, *args)class FieldStorage:    def __init__(self, req, keep_blank_values=0, strict_parsing=0, file_callback=None, field_callback=None):        #        # Whenever readline is called ALWAYS use the max size EVEN when        # not expecting a long line. - this helps protect against        # malformed content from exhausting memory.        #        self.list = FieldList()        # always process GET-style parameters        if req.args:            pairs = parse_qsl(req.args, keep_blank_values)            for pair in pairs:                self.add_field(pair[0], pair[1])        if req.method != "POST":            return        try:            clen = int(req.headers_in["content-length"])        except (KeyError, ValueError):            # absent content-length is not acceptable            raise apache.SERVER_RETURN, apache.HTTP_LENGTH_REQUIRED        if not req.headers_in.has_key("content-type"):            ctype = "application/x-www-form-urlencoded"        else:            ctype = req.headers_in["content-type"]        if ctype.startswith("application/x-www-form-urlencoded"):            pairs = parse_qsl(req.read(clen), keep_blank_values)            for pair in pairs:                self.add_field(pair[0], pair[1])            return        if not ctype.startswith("multipart/"):            # we don't understand this content-type            raise apache.SERVER_RETURN, apache.HTTP_NOT_IMPLEMENTED        # figure out boundary        try:            i = ctype.lower().rindex("boundary=")            boundary = ctype[i+9:]            if len(boundary) >= 2 and boundary[0] == boundary[-1] == '"':                boundary = boundary[1:-1]            boundary = re.compile("--" + re.escape(boundary) + "(--)?\r?\n")         except ValueError:            raise apache.SERVER_RETURN, apache.HTTP_BAD_REQUEST        # read until boundary        self.read_to_boundary(req, boundary, None)        end_of_stream = False        while not end_of_stream: # jjj JIM BEGIN WHILE            ## parse headers            ctype, type_options = "text/plain", {}            disp, disp_options = None, {}            headers = apache.make_table()            line = req.readline(readBlockSize)            match = boundary.match(line)            if (not line) or match:                # we stop if we reached the end of the stream or a stop                # boundary (which means '--' after the boundary) we                # continue to the next part if we reached a simple                # boundary in either case this would mean the entity is                # malformed, but we're tolerating it anyway.                end_of_stream = (not line) or (match.group(1) is not None)                continue              skip_this_part = False            while line not in ('\r','\r\n'):                nextline = req.readline(readBlockSize)                while nextline and nextline[0] in [ ' ', '\t']:                    line = line + nextline                    nextline = req.readline(readBlockSize)                # we read the headers until we reach an empty line                # NOTE : a single \n would mean the entity is malformed, but                # we're tolerating it anyway                h, v = line.split(":", 1)                headers.add(h, v)                h = h.lower()                if h == "content-disposition":                    disp, disp_options = parse_header(v)                elif h == "content-type":                    ctype, type_options = parse_header(v)                    #                    # NOTE: FIX up binary rubbish sent as content type                    # from Microsoft IE 6.0 when sending a file which                    # does not have a suffix.                    #                    if ctype.find('/') == -1:                        ctype = 'application/octet-stream'

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -