コード例 #1
0
	def structure(self,**kwargs):
		print_out(str(kwargs))
		if "current_doc" not in kwargs:
			return '<script>document.location.href="open";</script>'
		elif "screenshot" in kwargs:
			cherrypy.response.headers['Content-Type'] = "image/png"
			cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="' + kwargs["current_doc"] + '.png"'
			if sys.version_info[0] == 2:
				return file_generator(StringIO(structure_main("local", "3", 'local', **kwargs)))
			else:
				return file_generator(BytesIO(b64decode(structure_main("local", "3", 'local', **kwargs))))
		else:
			return structure_main("local","3",'local',**kwargs)
コード例 #2
0
 def key(self, url, headers=None):
     r = self.make_request(url, True, headers)[1]
     buffer = StringIO.StringIO()
     for chunk in r.iter_content(16):
         buffer.write(chunk)
     buffer.seek(0)
     return file_generator(buffer)
コード例 #3
0
 def index(self):
     im = getRPiCameraImage()
     im_data = StringIO.StringIO()
     im.save(im_data, format="JPEG")
     im_data.seek(0)
     cherrypy.response.headers['Content-Type'] = "image/jpeg"
     return file_generator(im_data)
コード例 #4
0
ファイル: actionHistory.py プロジェクト: uh-joan/UHCore
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        from PIL import Image
        fileName, fileExtension = os.path.splitext(args[0])
        if fileExtension=='.jpg':
            #path = os.path.join(self._basePath, args[0])
            data = Image.open(os.path.join(self._basePath, args[0]))
            img = {
                   'data': None,
                   'meta': {
                            'type': '',
                            'name': ''
                            }
                   }
        else:
            img = self._dao.getBinary(args[0])

        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
コード例 #5
0
    def __set__(self, obj, value):
        # Convert the given value to an iterable object.
        if py3k and isinstance(value, str):
            raise ValueError(self.unicode_err)

        if isinstance(value, basestring):
            # strings get wrapped in a list because iterating over a single
            # item list is much faster than iterating over every character
            # in a long string.
            if value:
                value = [value]
            else:
                # [''] doesn't evaluate to False, so replace it with [].
                value = []
        elif py3k and isinstance(value, list):
            # every item in a list must be bytes...
            for i, item in enumerate(value):
                if isinstance(item, str):
                    raise ValueError(self.unicode_err)
        # Don't use isinstance here; io.IOBase which has an ABC takes
        # 1000 times as long as, say, isinstance(value, str)
        elif hasattr(value, "read"):
            value = file_generator(value)
        elif value is None:
            value = []
        obj._body = value
コード例 #6
0
ファイル: currentMap.py プロジェクト: UH-msalem/UHCore
    def GET(self, *args, **kwargs):
        #if len(args) < 1:
            #raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor(self._emptyMap)
        sensors = self._sr.resolveStates(self._dao.findSensors())
        #sensors = self._sr.appendSensorMetadata(sensors, self._emptyMap) #adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
               'icon':self._dao.sensors.getSensorIconByName('robot')['id'], 
               'name':cob['robotName'], 
               'xCoord': cob['xCoord'],
               'yCoord': cob['yCoord'],
               'orientation': '%sd' % cob['orientation'],
               'id':'r%s' % (cob['robotId'])
               }

        elements = []
        elements.extend(sensors)
        #important to put robot last as z-order is determined by render order in svg and we want the robot icon
        #to always be on top
        elements.append(robot)
        
        img = mp.buildMap(elements)
        
        data = io.BytesIO(img)
        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
        return file_generator(data)
コード例 #7
0
    def export_participants(self, id):
        """Exports xlsx file with event participants

        Args:
            id (int): event id
        """
        id = int(id)
        req = cherrypy.request
        orm_session = req.orm_session

        # Retrieve event object
        event = api.find_event_by_id(orm_session, id)
        if event is None:
            raise HTTPError(404)

        # Set appropriate headers
        filename = re.compile(r'[^\w-]').sub('', event.title.replace(' ', '_'))

        cherrypy.response.headers['Content-Type'] = (
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        cherrypy.response.headers['Content-Disposition'] = (
            'attachment; filename={}-{}-{}-participants.xlsx'.format(
                event.id, filename, event.date,
            )
        )

        # Retrieve participation data
        participations = api.find_participants_by_event(orm_session, event)

        return file_generator(gen_participants_xlsx(participations))
コード例 #8
0
ファイル: _cprequest.py プロジェクト: iduque/ThesisModules
    def __set__(self, obj, value):
        # Convert the given value to an iterable object.
        if py3k and isinstance(value, str):
            raise ValueError(self.unicode_err)

        if isinstance(value, basestring):
            # strings get wrapped in a list because iterating over a single
            # item list is much faster than iterating over every character
            # in a long string.
            if value:
                value = [value]
            else:
                # [''] doesn't evaluate to False, so replace it with [].
                value = []
        elif py3k and isinstance(value, list):
            # every item in a list must be bytes...
            for i, item in enumerate(value):
                if isinstance(item, str):
                    raise ValueError(self.unicode_err)
        # Don't use isinstance here; io.IOBase which has an ABC takes
        # 1000 times as long as, say, isinstance(value, str)
        elif hasattr(value, 'read'):
            value = file_generator(value)
        elif value is None:
            value = []
        obj._body = value
コード例 #9
0
ファイル: aimcam.py プロジェクト: lrosengreen/asterpi
 def index(self):
     im = getRPiCameraImage()
     im_data = StringIO.StringIO()
     im.save(im_data, format="JPEG")
     im_data.seek(0)
     cherrypy.response.headers['Content-Type'] = "image/jpeg"
     return file_generator(im_data)
コード例 #10
0
ファイル: currentMap.py プロジェクト: uh-adapsys/UHCore
    def GET(self, *args, **kwargs):
        #if len(args) < 1:
            #raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor(self._emptyMap)
        sensors = self._sr.resolveStates(self._dao.findSensors())
        #sensors = self._sr.appendSensorMetadata(sensors, self._emptyMap) #adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
               'icon':self._dao.sensors.getSensorIconByName('robot')['id'], 
               'name':cob['robotName'], 
               'xCoord': cob['xCoord'],
               'yCoord': cob['yCoord'],
               'orientation': '%sd' % cob['orientation'],
               'id':'r%s' % (cob['robotId'])
               }

        elements = []
        elements.extend(sensors)
        #important to put robot last as z-order is determined by render order in svg and we want the robot icon
        #to always be on top
        elements.append(robot)
        
        img = mp.buildMap(elements)
        
        data = io.BytesIO(img)
        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
        cherrypy.response.headers['Cache-Control'] = "max-age=0, no-cache, must-revalidate"
        cherrypy.response.headers['Pragma'] = "no-cache"
        # In the past to prevent browser caching
        cherrypy.response.headers['Expires'] = (datetime.datetime.utcnow() - datetime.timedelta(hours=1)).strftime('%a, %d %b %Y %H:%M:%S GMT')
        return file_generator(data)
コード例 #11
0
    def GET(self, *args, **kwargs):
        #if len(args) < 1:
        #raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor()
        sensors = self._sr.resolveStates(self._dao.findSensors())
        sensors = self._sr.appendSensorMetadata(
            sensors)  #adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
            'type':
            'robot',
            'name':
            cob['robotName'],
            'location':
            (cob['xCoord'], cob['yCoord'], '%sd' % (cob['orientation'] * -1)
             ),  #svg rotates opposite of our cooridnate system
            'id':
            'r%s' % (cob['robotId'])
        }

        elements = []
        elements.extend(sensors)
        #important to put robot last as z-order is determined by render order in svg and we want the robot icon
        #to always be on top
        elements.append(robot)

        img = mp.buildMap(elements)

        data = io.BytesIO(img)
        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
            'img.svg')[0]
        return file_generator(data)
コード例 #12
0
    def export_participants(self, id):
        """Exports xlsx file with event participants

        Args:
            id (int): event id
        """
        id = int(id)
        req = cherrypy.request
        orm_session = req.orm_session

        # Retrieve event object
        event = api.find_event_by_id(orm_session, id)
        if event is None:
            raise HTTPError(404)

        # Set appropriate headers
        filename = re.compile(r'[^\w-]').sub('', event.title.replace(' ', '_'))

        cherrypy.response.headers['Content-Type'] = (
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        cherrypy.response.headers['Content-Disposition'] = (
            'attachment; filename={}-{}-{}-participants.xlsx'.format(
                event.id,
                filename,
                event.date,
            ))

        # Retrieve participation data
        participations = api.find_participants_by_event(orm_session, event)

        return file_generator(gen_participants_xlsx(participations))
コード例 #13
0
ファイル: handlers.py プロジェクト: iduque/UHCore
 def GET(self, *args, **kwargs):
     if os.path.isfile(self._file):
         f = open(self._file, 'rb')
         cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(self._file)[0]
         return file_generator(f)
     else:
         raise cherrypy.HTTPError(404)
コード例 #14
0
ファイル: currentMap.py プロジェクト: ipa320/accompany
    def GET(self, *args, **kwargs):
        # if len(args) < 1:
        # raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor()
        sensors = self._sr.resolveStates(self._dao.findSensors())
        sensors = self._sr.appendSensorMetadata(sensors)  # adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
            "type": "robot",
            "name": cob["robotName"],
            "location": (
                cob["xCoord"],
                cob["yCoord"],
                "%sd" % (cob["orientation"] * -1),
            ),  # svg rotates opposite of our cooridnate system
            "id": "r%s" % (cob["robotId"]),
        }

        elements = []
        elements.extend(sensors)
        # important to put robot last as z-order is determined by render order in svg and we want the robot icon
        # to always be on top
        elements.append(robot)

        img = mp.buildMap(elements)

        data = io.BytesIO(img)
        cherrypy.response.headers["Content-Type"] = mimetypes.guess_type("img.svg")[0]
        return file_generator(data)
コード例 #15
0
ファイル: root.py プロジェクト: rranshous/mostsplendiferous
    def guest_list_report(self):
        guests = m.Guest.query.order_by(m.Guest.name).all()
        csv_data = []
        header = ['Guest','Party Size','RSVPd','Attending','Comment',
                  'Guests Requested', 'Guests Allowed',
                  'Guests Attending','Total']
        for guest in guests:
            d = []
            d.append(guest.name)
            d.append(guest.party_size)
            d.append('1' if guest.rsvpd else '0')
            d.append('1' if guest.attending else '0')
            d.append(guest.comment or '')
            d.append(guest.guests_requested)
            d.append(guest.guests_allowed)
            d.append(guest.guests_coming)
            if guest.rsvpd:
                d.append(guest.party_size + guest.guests_coming)
            else:
                d.append(0)
            csv_data.append(d)
        csv_buffer = StringIO.StringIO()
        csv_report = csv.writer(csv_buffer)
#        csv_report.writeheader(header)
        csv_report.writerow(header)
        csv_report.writerows(csv_data)
        csv_buffer.seek(0)
        cherrypy.response.headers['Content-type'] = 'application/xls'
        cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="guest_list.csv"'
        return file_generator(csv_buffer)
コード例 #16
0
ファイル: webserver.py プロジェクト: ticalcster/efos
 def barcode(self, data, scale=4):
     """ """
     cherrypy.response.headers['Content-Type'] = "image/png"
     buffer = StringIO.StringIO()
     code = pyqrcode.create(data)
     code.png(buffer, scale=scale)
     buffer.seek(0)
     return file_generator(buffer)
コード例 #17
0
ファイル: handlers.py プロジェクト: ninghang/accompany
 def GET(self, *args, **kwargs):
     if os.path.isfile(self._file):
         f = open(self._file, 'rb')
         cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
             self._file)[0]
         return file_generator(f)
     else:
         raise cherrypy.HTTPError(404)
コード例 #18
0
    def plot_graph(self, data, urlparams):
        line_data = []
        pie_data = []

        limit = int(urlparams.limit)
        if urlparams.graphtype == 'pie' and len(data) > limit and limit > 1:    # formulate an artificial 'other' group with values > 'limit'
            sum = 0L
            for k, v in data[limit-1:]:
                sum += v
            data[limit-1:] = [('Other', sum)]

        if urlparams.output_format == 'graph':
            if urlparams.graphtype == 'line':
                line_data = fill_timeline_holes(data, urlparams.graphbucket, urlparams.db_uniq)
                line_data = [(int(time.mktime(p[0].timetuple()) * 1000), p[1]) for p in line_data]
                line_data = json.dumps(line_data)
            elif urlparams.graphtype == 'pie':
                for d in data:
                    pie_data.append({'label': str(d[0]), 'data': [d[1]]})
                pie_data = json.dumps(pie_data)

            tmpl = env.get_template('graph.html')
            return tmpl.render(line_data=line_data, pie_data=pie_data, graph_type=urlparams.graphtype, table=urlparams.table,
                               graph_key=urlparams.graphkey, graph_bucket=urlparams.graphbucket)
        elif urlparams.output_format == 'png':
            chart = None
            if urlparams.graphtype == 'line':
                line_data = fill_timeline_holes(data, urlparams.graphbucket, urlparams.db_uniq)
                import pygal
                chart = pygal.Line(width=1000)
                chart.title = 'Counts of {} over 1{} slots'.format(urlparams.graphkey, urlparams.graphbucket)
                labels = []
                mod_constant = 10 if len(line_data) < 100 else (30 if len(line_data) < 1000 else 1000)
                for i, d in enumerate(line_data):
                    if i == 0 or i == len(line_data)-1:
                        labels.append(d[0].strftime('%m-%d %H:%M'))
                        continue
                    if i % mod_constant == 0:
                        labels.append(d[0].strftime('%m-%d %H:%M'))
                chart.x_labels = labels
                chart.add('Count', [v for t, v in line_data])
            elif urlparams.graphtype == 'pie':
                import pygal
                chart = pygal.Pie()
                chart.title = 'Distribution of {} values'.format(urlparams.graphkey)
                for key, count in data:
                    chart.add(str(key), count)

            random_file_path = '/tmp/pgzebra{}.png'.format(random.random())
            chart.render_to_png(random_file_path)
            output = StringIO.StringIO(open(random_file_path).read())   # should be possible to skip this step also?
            os.unlink(random_file_path)

            cherrypy.response.headers['Content-Type'] = 'image/png'
            return file_generator(output)
コード例 #19
0
 def __set__(self, obj, value):
     if isinstance(value, basestring):
         if value:
             value = [value]
         else:
             value = []
     elif hasattr(value, 'read'):
         value = file_generator(value)
     elif value is None:
         value = []
     obj._body = value
コード例 #20
0
 def __set__(self, obj, value):
     if isinstance(value, basestring):
         if value:
             value = [value]
         else:
             value = []
     elif hasattr(value, 'read'):
         value = file_generator(value)
     elif value is None:
         value = []
     obj._body = value
コード例 #21
0
    def __call__(self, *args, **kwargs):
        response = cherrypy.serving.response
        self.body = self.oldhandler(*args, **kwargs)

        if isinstance(self.body, basestring):
            # strings get wrapped in a list because iterating over a single
            # item list is much faster than iterating over every character
            # in a long string.
            if self.body:
                self.body = [self.body]
            else:
                # [''] doesn't evaluate to False, so replace it with [].
                self.body = []
        elif hasattr(self.body, 'read'):
            self.body = file_generator(self.body)
        elif self.body is None:
            self.body = []

        ct = response.headers.elements("Content-Type")
        if self.debug:
            cherrypy.log('Content-Type: %r' % [str(h) for h in ct],
                         'TOOLS.ENCODE')
        if ct:
            ct = ct[0]
            if self.text_only:
                if ct.value.lower().startswith("text/"):
                    if self.debug:
                        cherrypy.log(
                            'Content-Type %s starts with "text/"' % ct,
                            'TOOLS.ENCODE')
                    do_find = True
                else:
                    if self.debug:
                        cherrypy.log(
                            'Not finding because Content-Type %s does '
                            'not start with "text/"' % ct, 'TOOLS.ENCODE')
                    do_find = False
            else:
                if self.debug:
                    cherrypy.log('Finding because not text_only',
                                 'TOOLS.ENCODE')
                do_find = True

            if do_find:
                # Set "charset=..." param on response Content-Type header
                ct.params['charset'] = self.find_acceptable_charset()
                if self.add_charset:
                    if self.debug:
                        cherrypy.log('Setting Content-Type %s' % ct,
                                     'TOOLS.ENCODE')
                    response.headers["Content-Type"] = str(ct)

        return self.body
コード例 #22
0
ファイル: main.py プロジェクト: ryanmccartney/timelapsePi
        def getImage(self):
            cherrypy.response.headers['Content-Type'] = "image/jpeg"
            self.startCamera()
            stream = BytesIO()
            #stream = StringIO.StringIO()
            try:
                self.camera.capture(stream, format='jpeg')
                stream.seek(0)
            except:
                self.log("Could not get an image from camera.", 0)

            return file_generator(stream)
コード例 #23
0
ファイル: encoding.py プロジェクト: Southpaw-TACTIC/TACTIC
    def __call__(self, *args, **kwargs):
        response = cherrypy.serving.response
        self.body = self.oldhandler(*args, **kwargs)

        if isinstance(self.body, text_or_bytes):
            # strings get wrapped in a list because iterating over a single
            # item list is much faster than iterating over every character
            # in a long string.
            if self.body:
                self.body = [self.body]
            else:
                # [''] doesn't evaluate to False, so replace it with [].
                self.body = []
        elif hasattr(self.body, 'read'):
            self.body = file_generator(self.body)
        elif self.body is None:
            self.body = []

        ct = response.headers.elements('Content-Type')
        if self.debug:
            cherrypy.log('Content-Type: %r' % [str(h)
                         for h in ct], 'TOOLS.ENCODE')
        if ct and self.add_charset:
            ct = ct[0]
            if self.text_only:
                if ct.value.lower().startswith('text/'):
                    if self.debug:
                        cherrypy.log(
                            'Content-Type %s starts with "text/"' % ct,
                            'TOOLS.ENCODE')
                    do_find = True
                else:
                    if self.debug:
                        cherrypy.log('Not finding because Content-Type %s '
                                     'does not start with "text/"' % ct,
                                     'TOOLS.ENCODE')
                    do_find = False
            else:
                if self.debug:
                    cherrypy.log('Finding because not text_only',
                                 'TOOLS.ENCODE')
                do_find = True

            if do_find:
                # Set "charset=..." param on response Content-Type header
                ct.params['charset'] = self.find_acceptable_charset()
                if self.debug:
                    cherrypy.log('Setting Content-Type %s' % ct,
                                 'TOOLS.ENCODE')
                response.headers['Content-Type'] = str(ct)

        return self.body
コード例 #24
0
ファイル: start_local_docker.py プロジェクト: arne-cl/rstWeb
 def structure(self, **kwargs):
     print_out(str(kwargs))
     if "current_doc" not in kwargs:
         return '<script>document.location.href="open";</script>'
     elif "screenshot" in kwargs:
         cherrypy.response.headers['Content-Type'] = "image/png"
         cherrypy.response.headers[
             'Content-Disposition'] = 'attachment; filename="' + kwargs[
                 "current_doc"] + '.png"'
         if sys.version_info[0] == 2:
             return file_generator(
                 StringIO(structure_main("local", "3", 'local', **kwargs)))
         else:
             return file_generator(
                 BytesIO(
                     b64decode(
                         structure_main("local", "3", 'local', **kwargs))))
     else:
         CORS(
         )  # This should not be necessary since the function is registered
         # as cherrypy's 'before_handler', but for some reason the CORS
         # header does not get set unless this is called explicitly.
         return structure_main("local", "3", 'local', **kwargs)
コード例 #25
0
ファイル: handlers.py プロジェクト: iduque/UHCore
    def GET(self, *args, **kwargs):
        path = ''
        for arg in args:
            path = os.path.join(path, arg)

        if path == '':
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')
        
        ospath = os.path.join(self._root, path)
        if os.path.isfile(ospath):
            f = open(ospath, 'rb')
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(ospath)[0]
            return file_generator(f)
        else:
            raise cherrypy.HTTPError(404, ospath)
コード例 #26
0
ファイル: actionHistory.py プロジェクト: ipa-rmb/accompany
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        key = args[0]
        
        sensorHist = self._dao.getSensorHistory(key)        
        if len(sensorHist) > 0:
            mp = MapProcessor()
            s = StateResolver()
            sensors = s.resolveStates(sensorHist)     
            img = mp.buildMap(sensors)
            data = io.BytesIO(img)
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
            return file_generator(data)
コード例 #27
0
 def __set__(self, obj, value):
     # Convert the given value to an iterable object.
     if isinstance(value, basestring):
         # strings get wrapped in a list because iterating over a single
         # item list is much faster than iterating over every character
         # in a long string.
         if value:
             value = [value]
         else:
             # [''] doesn't evaluate to False, so replace it with [].
             value = []
     elif isinstance(value, types.FileType):
         value = file_generator(value)
     elif value is None:
         value = []
     obj._body = value
コード例 #28
0
ファイル: handlers.py プロジェクト: ninghang/accompany
    def GET(self, *args, **kwargs):
        path = ''
        for arg in args:
            path = os.path.join(path, arg)

        if path == '':
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        ospath = os.path.join(self._root, path)
        if os.path.isfile(ospath):
            f = open(ospath, 'rb')
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
                ospath)[0]
            return file_generator(f)
        else:
            raise cherrypy.HTTPError(404)
コード例 #29
0
ファイル: _cprequest.py プロジェクト: brunogola/skink
 def __set__(self, obj, value):
     # Convert the given value to an iterable object.
     if isinstance(value, basestring):
         # strings get wrapped in a list because iterating over a single
         # item list is much faster than iterating over every character
         # in a long string.
         if value:
             value = [value]
         else:
             # [''] doesn't evaluate to False, so replace it with [].
             value = []
     elif isinstance(value, types.FileType):
         value = file_generator(value)
     elif value is None:
         value = []
     obj._body = value
コード例 #30
0
ファイル: actionHistory.py プロジェクト: iduque/UHCore
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        key = args[0]
        
        sensorHist = self._dao.getSensorHistory(key)        
        if len(sensorHist) > 0:
            mp = MapProcessor()
            s = StateResolver()
            sensors = s.resolveStates(sensorHist)
            #[{'id': sensor['sensorId'], 'value': sensor['value'], 'state':'on'},]
            sensors = s.appendSensorMetadata(sensors) #adds location and type            
            img = mp.buildMap(sensors)
            data = io.BytesIO(img)
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
            return file_generator(data)
コード例 #31
0
ファイル: actionHistory.py プロジェクト: ipa-rmb/accompany
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        img = self._dao.getBinary(args[0])
        
        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
コード例 #32
0
ファイル: server.py プロジェクト: ruuk/speech.server
 def wav(self,engine=None,voice=None,rate=None,pitch=None,volume=None,text=None):
     TTS.setEngine(engine,True)
     TTS.setVoice(voice)
     TTS.setRate(rate)
     TTS.setPitch(pitch)
     TTS.setVolume(volume)
     TTS.update()
     wav = TTS.getWavStream(text)
     if not wav:
         if not text:
             raise cherrypy.HTTPError(status=400)
         else:
             raise cherrypy.HTTPError(status=500)
     util.LOG('[{0}] {1} - WAV: {2}'.format(cherrypy.request.remote.ip,TTS.backend.provider,text.decode('utf-8')))
     wav.seek(0)
     cherrypy.response.headers['Content-Type'] = "audio/x-wav"
     return file_generator(wav)
コード例 #33
0
 def __set__(self, obj, value):
     # Convert the given value to an iterable object.
     if isinstance(value, basestring):
         # strings get wrapped in a list because iterating over a single
         # item list is much faster than iterating over every character
         # in a long string.
         if value:
             value = [value]
         else:
             # [''] doesn't evaluate to False, so replace it with [].
             value = []
     # Don't use isinstance here; io.IOBase which has an ABC takes
     # 1000 times as long as, say, isinstance(value, str)
     elif hasattr(value, 'read'):
         value = file_generator(value)
     elif value is None:
         value = []
     obj._body = value
コード例 #34
0
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        img = self._dao.getBinary(args[0])

        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
            img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
コード例 #35
0
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        key = args[0]

        sensorHist = self._dao.getSensorHistory(key)
        if len(sensorHist) > 0:
            mp = MapProcessor()
            s = StateResolver()
            sensors = s.resolveStates(sensorHist)
            #[{'id': sensor['sensorId'], 'value': sensor['value'], 'state':'on'},]
            sensors = s.appendSensorMetadata(sensors)  #adds location and type
            img = mp.buildMap(sensors)
            data = io.BytesIO(img)
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
                'img.svg')[0]
            return file_generator(data)
コード例 #36
0
 def __call__(self, *args, **kwargs):
     response = cherrypy.serving.response
     self.body = self.oldhandler(*args, **kwargs)
     if isinstance(self.body, basestring):
         if self.body:
             self.body = [self.body]
         else:
             self.body = []
     elif hasattr(self.body, 'read'):
         self.body = file_generator(self.body)
     elif self.body is None:
         self.body = []
     ct = response.headers.elements('Content-Type')
     if self.debug:
         cherrypy.log('Content-Type: %r' % [str(h) for h in ct],
                      'TOOLS.ENCODE')
     if ct:
         ct = ct[0]
         if self.text_only:
             if ct.value.lower().startswith('text/'):
                 if self.debug:
                     cherrypy.log(
                         'Content-Type %s starts with "text/"' % ct,
                         'TOOLS.ENCODE')
                 do_find = True
             else:
                 if self.debug:
                     cherrypy.log(
                         'Not finding because Content-Type %s does not start with "text/"'
                         % ct, 'TOOLS.ENCODE')
                 do_find = False
         else:
             if self.debug:
                 cherrypy.log('Finding because not text_only',
                              'TOOLS.ENCODE')
             do_find = True
         if do_find:
             ct.params['charset'] = self.find_acceptable_charset()
             if self.add_charset:
                 if self.debug:
                     cherrypy.log('Setting Content-Type %s' % ct,
                                  'TOOLS.ENCODE')
                 response.headers['Content-Type'] = str(ct)
     return self.body
コード例 #37
0
def prepare_iter(value):
    """
    Ensure response body is iterable and resolves to False when empty.
    """
    if isinstance(value, text_or_bytes):
        # strings get wrapped in a list because iterating over a single
        # item list is much faster than iterating over every character
        # in a long string.
        if value:
            value = [value]
        else:
            # [''] doesn't evaluate to False, so replace it with [].
            value = []
    # Don't use isinstance here; io.IOBase which has an ABC takes
    # 1000 times as long as, say, isinstance(value, str)
    elif hasattr(value, 'read'):
        value = file_generator(value)
    elif value is None:
        value = []
    return value
コード例 #38
0
    def default(self, attr=''):
        if os.path.isfile(NEW_MAIN_IMAGE_PATH):
            log('New main image')
            try:
                os.remove(MAIN_IMAGE_PATH)
            except:
                pass
            os.rename(NEW_MAIN_IMAGE_PATH, MAIN_IMAGE_PATH)
            self._im = None
        if not self._im:
            log('Load main image')
            try:
                self._im = load_main_image(MAIN_IMAGE_PATH)
            except:
                self._im = None
        if self._im:
            cherrypy.response.headers['Content-type'] = 'image/png'
            return file_generator(image_stream(self._im))

        return 'Oops!'
コード例 #39
0
ファイル: encoding.py プロジェクト: cherrypy/cherrypy
def prepare_iter(value):
    """
    Ensure response body is iterable and resolves to False when empty.
    """
    if isinstance(value, text_or_bytes):
        # strings get wrapped in a list because iterating over a single
        # item list is much faster than iterating over every character
        # in a long string.
        if value:
            value = [value]
        else:
            # [''] doesn't evaluate to False, so replace it with [].
            value = []
    # Don't use isinstance here; io.IOBase which has an ABC takes
    # 1000 times as long as, say, isinstance(value, str)
    elif hasattr(value, 'read'):
        value = file_generator(value)
    elif value is None:
        value = []
    return value
コード例 #40
0
ファイル: encoding.py プロジェクト: Pluckyduck/eve
 def __call__(self, *args, **kwargs):
     response = cherrypy.serving.response
     self.body = self.oldhandler(*args, **kwargs)
     if isinstance(self.body, basestring):
         if self.body:
             self.body = [self.body]
         else:
             self.body = []
     elif hasattr(self.body, 'read'):
         self.body = file_generator(self.body)
     elif self.body is None:
         self.body = []
     ct = response.headers.elements('Content-Type')
     if self.debug:
         cherrypy.log('Content-Type: %r' % [ str(h) for h in ct ], 'TOOLS.ENCODE')
     if ct:
         ct = ct[0]
         if self.text_only:
             if ct.value.lower().startswith('text/'):
                 if self.debug:
                     cherrypy.log('Content-Type %s starts with "text/"' % ct, 'TOOLS.ENCODE')
                 do_find = True
             else:
                 if self.debug:
                     cherrypy.log('Not finding because Content-Type %s does not start with "text/"' % ct, 'TOOLS.ENCODE')
                 do_find = False
         else:
             if self.debug:
                 cherrypy.log('Finding because not text_only', 'TOOLS.ENCODE')
             do_find = True
         if do_find:
             ct.params['charset'] = self.find_acceptable_charset()
             if self.add_charset:
                 if self.debug:
                     cherrypy.log('Setting Content-Type %s' % ct, 'TOOLS.ENCODE')
                 response.headers['Content-Type'] = str(ct)
     return self.body
コード例 #41
0
ファイル: pd_web.py プロジェクト: aheilbut/pdmouse
    def render_figure(self, probeset, fig_type, format, r=None):

        if fig_type == "scatter":
            probeset = urllib.unquote_plus(probeset)
            # generate figure 
            fig = Figure()
            fig.set_size_inches(16, 6)
            
            ax_cp73 = fig.add_subplot(121)
            ax_cp101 = fig.add_subplot(122)

            if r == "a": # auto range 
                xlim = None
            elif r == "f":  # full range
                xlim = (0, 15)
            
            pda.plotProbe(pd_all, pd_covar, probeset, "CP73", ax_cp73, legend=False, xlim=xlim)
            pda.plotProbe(pd_all, pd_covar, probeset, "CP101", ax_cp101, legend=True, xlim=xlim)

            fig.tight_layout(rect=[0, 0, 0.7, 1], h_pad=0.5)
            fig.set_facecolor('w')
            canvas = FigureCanvas(fig)
        # render

        if fig_type == "boxplot":
            probeset = urllib.unquote_plus(probeset)

            fig = Figure()
            fig.set_size_inches(15, 8)
            
            ax_cp73 = fig.add_subplot(121)
            ax_cp101 = fig.add_subplot(122)
            
            cp73_groups = [("ASC / chronic saline", ss.ss_cp73_ascorbate_saline.filenames),
                           ("OHDA / chronic saline", ss.cp73_chronic_saline.filenames),
                           ("OHDA / acute saline", ss.ss_cp73_acuteSaline.filenames),
                           ("OHDA / acute High L-DOPA", ss.ss_cp73_acuteHigh.filenames),
                           ("OHDA / chronic Low L-DOPA", ss.ss_cp73_chronicLow.filenames),
                           ("OHDA / chronic High L-DOPA", ss.ss_cp73_chronicHigh.filenames)
                           ]
            
            cp101_groups = [("ASC / chronic saline", ss.ss_cp101_ascorbate_saline.filenames),
                           ("OHDA / chronic saline", ss.cp101_chronic_saline.filenames),
                           ("OHDA / chronic Low L-DOPA", ss.ss_cp101_chronicLow.filenames),
                           ("OHDA / chronic High L-DOPA", ss.ss_cp101_chronicHigh.filenames)
                           ]
        
            pda.probe_boxPlots(probeset, pd_all, cp73_groups, "CP73", ax_cp73)
            pda.probe_boxPlots(probeset, pd_all, cp101_groups, "CP101", ax_cp101)
            
            fig.tight_layout(rect=[0, 0, 0.7, 1], h_pad=0.5)
            fig.set_facecolor('w')
            canvas = FigureCanvas(fig)
        
        if format == "png":
            cherrypy.response.headers['Content-Type'] = "image/png"
            buffer = StringIO.StringIO()
            canvas.print_png(buffer)
            buffer.seek(0)

            return file_generator(buffer)
コード例 #42
0
 def photo(self, mathematician_id):
     session = DBSession()
     mathematician = session.query(Mathematician).get(mathematician_id)
     return file_generator(io.BytesIO(mathematician.image))
コード例 #43
0
ファイル: pd_web.py プロジェクト: aheilbut/pdmouse
    def result_table(self, result_set, format="HTML", sort_field=0, sort_dir="DESC", rows=100, dimlist=None, page=0, cell_type=None, contrast=None):
        if result_set == "cp73":
            s = cp73_wide_info
        elif result_set == "cp101":
            s = cp101_wide_info
        elif result_set == "t2_up":
            s = t2_up[cell_type][contrast]		
        elif result_set == "t2_down":
            s = t2_down[cell_type][contrast]      


        if sort_dir == "ASC":
            sort_asc = True
        else:
            sort_asc = False

        if sort_field is not None:
            s = s.sort([s.columns.values[int(sort_field)]], ascending=sort_asc)
        else:
            s = s


        if format == "txt":
            cherrypy.response.headers['Content-Type'] = "application/octet-stream"
            filename = "PDAIMS_2013_%s_%s_%s.txt" % (result_set, cell_type, contrast) 
            cherrypy.response.headers["Content-Disposition"] = "attachment; filename=%s" % filename
            buffer = StringIO.StringIO()
            s.to_csv(buffer, sep="\t")
            buffer.seek(0)

            return file_generator(buffer)

        s["probe_img"] = ["<img width=350 src='/probeset/figure/%s/scatter/png'/>" % urllib.quote_plus(probe_id) for probe_id in s.probe_id]

        s["probe_id"] = ["<a target='_detail'  href='/probeset/%s'>%s</a>" % (urllib.quote_plus(probe_id), probe_id) for probe_id in s.probe_id]
        s["symbol"] = ["<a target='_ncbi' href='http://www.ncbi.nlm.nih.gov/gene/?term=%s'>%s</a>" % (sym, sym) for sym in s.symbol]


#        c = [s.columns[-1]]
#        c.extend(s.columns[0:-1])
#        s = s[c]
        row_start = int(page) * 100
        #print 

        t = tl.get_template("result_table.html")

        if dimlist is None:
            dimarray = range(0, len(s.columns)-1)
            dimlist = ",".join([str(q) for q in dimarray])
        else:
            dimarray = [int(i) for i in dimlist.split(",")]
            dimarray.sort()


        if dimarray is not None:
            column_list = s.columns[dimarray]
        else:
            column_list = s.columns

        return t.render_unicode( fulltable = s.ix[s.index[row_start:row_start + 100],:],
                                 displaytable = s.ix[s.index[row_start:row_start + 100], column_list],
                                 page=int(page), 
                                 col_widths={"gene_name" : "300px"},
                                 sort_field=int(sort_field),
                                 sort_dir=sort_dir,
                                 dimlist=dimlist,
                                 dimarray=dimarray,
                                 dim_descriptions=dim_descriptions,
                                 result_set=result_set,
                                 cell_type=cell_type,
                                 contrast=contrast)
コード例 #44
0
    def render_figure(self, probeset, fig_type, format, r=None):

        if fig_type == "scatter":
            probeset = urllib.unquote_plus(probeset)
            # generate figure
            fig = Figure()
            fig.set_size_inches(16, 6)

            ax_cp73 = fig.add_subplot(121)
            ax_cp101 = fig.add_subplot(122)

            if r == "a":  # auto range
                xlim = None
            elif r == "f":  # full range
                xlim = (0, 15)

            pda.plotProbe(pd_all,
                          pd_covar,
                          probeset,
                          "CP73",
                          ax_cp73,
                          legend=False,
                          xlim=xlim)
            pda.plotProbe(pd_all,
                          pd_covar,
                          probeset,
                          "CP101",
                          ax_cp101,
                          legend=True,
                          xlim=xlim)

            fig.tight_layout(rect=[0, 0, 0.7, 1], h_pad=0.5)
            fig.set_facecolor('w')
            canvas = FigureCanvas(fig)
        # render

        if fig_type == "boxplot":
            probeset = urllib.unquote_plus(probeset)

            fig = Figure()
            fig.set_size_inches(15, 8)

            ax_cp73 = fig.add_subplot(121)
            ax_cp101 = fig.add_subplot(122)

            cp73_groups = [
                ("ASC / chronic saline",
                 ss.ss_cp73_ascorbate_saline.filenames),
                ("OHDA / chronic saline", ss.cp73_chronic_saline.filenames),
                ("OHDA / acute saline", ss.ss_cp73_acuteSaline.filenames),
                ("OHDA / acute High L-DOPA", ss.ss_cp73_acuteHigh.filenames),
                ("OHDA / chronic Low L-DOPA", ss.ss_cp73_chronicLow.filenames),
                ("OHDA / chronic High L-DOPA",
                 ss.ss_cp73_chronicHigh.filenames)
            ]

            cp101_groups = [("ASC / chronic saline",
                             ss.ss_cp101_ascorbate_saline.filenames),
                            ("OHDA / chronic saline",
                             ss.cp101_chronic_saline.filenames),
                            ("OHDA / chronic Low L-DOPA",
                             ss.ss_cp101_chronicLow.filenames),
                            ("OHDA / chronic High L-DOPA",
                             ss.ss_cp101_chronicHigh.filenames)]

            pda.probe_boxPlots(probeset, pd_all, cp73_groups, "CP73", ax_cp73)
            pda.probe_boxPlots(probeset, pd_all, cp101_groups, "CP101",
                               ax_cp101)

            fig.tight_layout(rect=[0, 0, 0.7, 1], h_pad=0.5)
            fig.set_facecolor('w')
            canvas = FigureCanvas(fig)

        if format == "png":
            cherrypy.response.headers['Content-Type'] = "image/png"
            buffer = StringIO.StringIO()
            canvas.print_png(buffer)
            buffer.seek(0)

            return file_generator(buffer)
コード例 #45
0
    def result_table(self,
                     result_set,
                     format="HTML",
                     sort_field=0,
                     sort_dir="DESC",
                     rows=100,
                     dimlist=None,
                     page=0,
                     cell_type=None,
                     contrast=None):
        if result_set == "cp73":
            s = cp73_wide_info
        elif result_set == "cp101":
            s = cp101_wide_info
        elif result_set == "t2_up":
            s = t2_up[cell_type][contrast]
        elif result_set == "t2_down":
            s = t2_down[cell_type][contrast]

        if sort_dir == "ASC":
            sort_asc = True
        else:
            sort_asc = False

        if sort_field is not None:
            s = s.sort([s.columns.values[int(sort_field)]], ascending=sort_asc)
        else:
            s = s

        if format == "txt":
            cherrypy.response.headers[
                'Content-Type'] = "application/octet-stream"
            filename = "PDAIMS_2013_%s_%s_%s.txt" % (result_set, cell_type,
                                                     contrast)
            cherrypy.response.headers[
                "Content-Disposition"] = "attachment; filename=%s" % filename
            buffer = StringIO.StringIO()
            s.to_csv(buffer, sep="\t")
            buffer.seek(0)

            return file_generator(buffer)

        s["probe_img"] = [
            "<img width=350 src='/probeset/figure/%s/scatter/png'/>" %
            urllib.quote_plus(probe_id) for probe_id in s.probe_id
        ]

        s["probe_id"] = [
            "<a target='_detail'  href='/probeset/%s'>%s</a>" %
            (urllib.quote_plus(probe_id), probe_id) for probe_id in s.probe_id
        ]
        s["symbol"] = [
            "<a target='_ncbi' href='http://www.ncbi.nlm.nih.gov/gene/?term=%s'>%s</a>"
            % (sym, sym) for sym in s.symbol
        ]

        #        c = [s.columns[-1]]
        #        c.extend(s.columns[0:-1])
        #        s = s[c]
        row_start = int(page) * 100
        #print

        t = tl.get_template("result_table.html")

        if dimlist is None:
            dimarray = range(0, len(s.columns) - 1)
            dimlist = ",".join([str(q) for q in dimarray])
        else:
            dimarray = [int(i) for i in dimlist.split(",")]
            dimarray.sort()

        if dimarray is not None:
            column_list = s.columns[dimarray]
        else:
            column_list = s.columns

        return t.render_unicode(
            fulltable=s.ix[s.index[row_start:row_start + 100], :],
            displaytable=s.ix[s.index[row_start:row_start + 100], column_list],
            page=int(page),
            col_widths={"gene_name": "300px"},
            sort_field=int(sort_field),
            sort_dir=sort_dir,
            dimlist=dimlist,
            dimarray=dimarray,
            dim_descriptions=dim_descriptions,
            result_set=result_set,
            cell_type=cell_type,
            contrast=contrast)