Пример #1
0
 def generate_chunk(self, data):
     bufsize = 1024
     io = StringIO(data)
     while True:
         buf = io.read(bufsize)
         if not buf:
             return
         yield buf
     io.close()
Пример #2
0
 def write_xls(file_name, sheet_name, headings, data, heading_xf, data_xfs, kinds):
     book = xlwt.Workbook(encoding='utf8')
     sheet = book.add_sheet(sheet_name)
     rowx = 0
     for colx, value in enumerate(headings):
         sheet.write(rowx, colx, value, heading_xf)
     sheet.set_panes_frozen(True) # frozen headings instead of split panes
     sheet.set_horz_split_pos(rowx+1) # in general, freeze after last heading row
     sheet.set_remove_splits(True) # if user does unfreeze, don't leave a split there
     sheet.set_col_default_width(True)
     color_charts = {}
     for state, color in state_color_map.iteritems() :
         color_charts[state] = xlwt.easyxf("""font:
                      height 180,
                      name Times New Roman,
                      colour_index %s,
                      bold on;
                  align:
                      wrap on,
                      vert centre,
                      horiz center
                  """ % color)
     
     for row in data:
         rowx += 1
         for colx, value in enumerate(row) :
             style = data_xfs[colx]
             if file_name == "requisitions" and kinds[colx] != 'money' :
                 state = row[-1]
                 style = color_charts[state]
             sheet.write(rowx, colx, (value not in ('None', '0.00') and value) or '', style)
     # book.save(file_name)
     
     # ene hesgiig huulav
     from StringIO import StringIO
     result = StringIO()
     book.save(result)
     result.seek(0)
     
     response = HttpResponse(result.read(), mimetype='application/ms-excel')
     if file_name:
         response['Content-Disposition'] = 'attachment; filename='+file_name+".xls"
     else:
         response['Content-Disposition'] = 'attachment; filename=export.xls' 
     return response
Пример #3
0
class SOAPRequestHandler(BaseSOAPRequestHandler):
    '''SOAP handler.
    '''
    def _read_chunk_size(self):
        current_size = ""
        while '\n' not in current_size:
            current_size += self.rfile.read(1)
        current_size = int(current_size, 16)
        return current_size

    def _fix_chunked_encoding(self):
        from StringIO import StringIO
        if self.headers.get('transfer-encoding', '') != 'chunked':
            return
        full_data = ""
        while True:
            current_size = self._read_chunk_size()
            if current_size == 0:
                break
            full_data += self.rfile.read(current_size)
            self.rfile.read(2)  # CRLF after chunk

        self.rfile = StringIO(full_data)
        self.headers['content-length'] = str(len(full_data))
        return full_data

    def do_POST(self):
        '''The POST command.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        self._fix_chunked_encoding()

        logger.debug("Request Host: {}".format(self.client_address))
        logger.debug("Request URI: {}".format(self.requestline))
        for key, value in self.headers.items():
            logger.debug("Request Header: {}: {}".format(key, value))
        content_type = self.headers.get("content-type", '')
        action_matchobj = re.search("action=\"(urn:\w+)\"", content_type)
        if action_matchobj is not None:
            # SOAP 1.2
            soapAction = action_matchobj.group(1)
        else:
            # SOAP 1.1
            soapAction = self.headers.getheader('SOAPAction')
            if soapAction:
                soapAction = soapAction.strip('\'"')
        self._soapAction = soapAction
        post = self.path
        if not post:
            raise PostNotSpecified, 'HTTP POST not specified in request'
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                xml = self.rfile.read(length)
                logger.debug("Request Body: {}".format(xml))
                ps = ParsedSoap(xml)
        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
Пример #4
0
class SOAPRequestHandler(BaseSOAPRequestHandler):
    '''SOAP handler.
    '''
    
    def _read_chunk_size(self):
        current_size = ""
        while '\n' not in current_size:
            current_size += self.rfile.read(1)
        current_size = int(current_size, 16)
        return current_size
    
    def _fix_chunked_encoding(self):
        from StringIO import StringIO
        if self.headers.get('transfer-encoding', '') != 'chunked':
            return
        full_data = ""
        while True:
            current_size = self._read_chunk_size()
            if current_size == 0:
                break
            full_data += self.rfile.read(current_size)
            self.rfile.read(2)  # CRLF after chunk
        
        self.rfile = StringIO(full_data)
        self.headers['content-length'] = str(len(full_data))
        return full_data
    
    def do_POST(self):
        '''The POST command.
        action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
        '''
        self._fix_chunked_encoding()
        
        logger.debug("Request Host: {}".format(self.client_address))
        logger.debug("Request URI: {}".format(self.requestline))
        for key, value in self.headers.items():
            logger.debug("Request Header: {}: {}".format(key, value))
        content_type = self.headers.get("content-type", '')
        action_matchobj = re.search("action=\"(urn:\w+)\"", content_type)
        if action_matchobj is not None:
            # SOAP 1.2
            soapAction = action_matchobj.group(1)
        else:
            # SOAP 1.1
            soapAction = self.headers.getheader('SOAPAction')
            if soapAction:
                soapAction = soapAction.strip('\'"')
        self._soapAction = soapAction
        post = self.path
        if not post:
            raise PostNotSpecified, 'HTTP POST not specified in request'
        post = post.strip('\'"')
        try:
            ct = self.headers['content-type']
            if ct.startswith('multipart/'):
                cid = resolvers.MIMEResolver(ct, self.rfile)
                xml = cid.GetSOAPPart()
                ps = ParsedSoap(xml, resolver=cid.Resolve)
            else:
                length = int(self.headers['content-length'])
                xml = self.rfile.read(length)
                logger.debug("Request Body: {}".format(xml))
                ps = ParsedSoap(xml)
        except ParseException, e:
            self.send_fault(FaultFromZSIException(e))
        except Exception, e:
            # Faulted while processing; assume it's in the header.
            self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
Пример #5
0
Файл: c3d.py Проект: cadop/pyCGM
    def __init__(self, handle):
        '''Initialize this C3D file by reading header and parameter data.

        Arguments
        ---------
        handle : file handle
            Read metadata and C3D motion frames from the given file handle. This
            handle is assumed to be `seek`-able and `read`-able. The handle must
            remain open for the life of the `Reader` instance. The `Reader` does
            not `close` the handle.

        Raises
        ------
        ValueError, if the processor metadata in the C3D file is anything other
        than 84 (Intel format) or 85 (DEC format).
        '''
        super(Reader, self).__init__(Header(handle))

        self._handle = handle
        self._handle.seek((self.header.parameter_block - 1) * 512)

        # metadata header
        buf = self._handle.read(4)
        _, _, parameter_blocks, processor = struct.unpack('BBBB', buf)
        if processor != PROCESSOR_INTEL:
            raise ValueError(
                'we only read Intel C3D files (got processor {})'.format(
                    processor))

        # read all parameter blocks as a single chunk to avoid block
        # boundary issues.
        bytes = self._handle.read(512 * parameter_blocks - 4)
        while bytes:
            buf = FileIO(bytes)

            chars_in_name, group_id = struct.unpack('bb', buf.read(2))
            if group_id == 0 or chars_in_name == 0:
                # we've reached the end of the parameter section.
                break

            name = buf.read(abs(chars_in_name)).upper()
            offset_to_next, = struct.unpack('<h', buf.read(2))

            if group_id > 0:
                # we've just started reading a parameter. if its group doesn't
                # exist, create a blank one. add the parameter to the group.
                self.setdefault(group_id, Group()).add_param(name, handle=buf)
            else:
                # we've just started reading a group. if a group with the
                # appropriate id exists already (because we've already created
                # it for a parameter), just set the name of the group.
                # otherwise, add a new group.
                group_id = abs(group_id)
                size, = struct.unpack('B', buf.read(1))
                desc = size and buf.read(size) or ''
                group = self.get(group_id)
                if group is not None:
                    group.name = name
                    group.desc = desc
                    self[name] = group
                else:
                    self.add_group(group_id, name, desc)

            bytes = bytes[2 + abs(chars_in_name) + offset_to_next:]

        self.check_metadata()