示例#1
0
文件: rest.py 项目: fbrundu/bimp
    def GET(self, *paths, **params):

        try:
            # do query on buildings' database
            result, qdesc, qparams, internal_log = db.query(params, pbc)

            if internal_log:
                log.error(msg=internal_log, context='HTTP')

            # create response
            response = {
                "r_ver": QUERY_VERSION,
                "q_ts": datetime.datetime.now().isoformat(),
                "q_desc": qdesc,
                "q_par": qparams,
                "q_res": result
            }

            # result to json
            response = json.dumps(response).encode("utf8")
            ctype = "application/json;charset=utf-8"
            cherrypy.response.headers["Content-Type"] = ctype

            # return response
            return response
        except:
            return handle_error(500, "Internal Server Error")
示例#2
0
def handle_error(code, message):

    log.error(msg=message, context="HTTP", traceback=False)
    cherrypy.response.status = code
    ctype = "application/json;charset=utf-8"
    cherrypy.response.headers["Content-Type"] = ctype

    return json.dumps({"code": code, "message": message}).encode('utf8')
示例#3
0
 def get_info(self, catalog):
     if catalog.lower() in self.mocs:
         if not self.mocs[catalog.lower()].is_in(self.ra, self.dec):
             # Not covered
             return '0%s' % catalog
     try:
         result = self.catalogs[catalog].load_data(catalog,
                                                   self.ra, self.dec,
                                                   self.radius)
         return result
     except Exception as exc:
         cherrylog.error('Error for catalog: %s', catalog)
         cherrylog.error(str(exc))
示例#4
0
    def upload(self, dir, datafile, **kwargs):
        error = ''
        fn = ''
        if datafile:
            path = Path(op.join(datapath, dir))
            if not path:
                path.make()
            fn = path + datafile.filename
            if not fn.is_legal:
                error = "'%s' is not legal"
            if fn and 'overwrite' not in kwargs:
                error = "'%s' exists already, if you want to overwrite the old version, check allow overwrite" % fn.name

            # Buffer file for first check encoding and secondly upload file
            with BytesIO(datafile.file.read()) as filebuffer:
                # determine file encodings
                result = chardet.detect(filebuffer.read())

                # Reset file buffer
                filebuffer.seek(0)

                # if chardet can determine file encoding, check it and warn respectively
                # otherwise state not detecting
                # TODO: chardet cannot determine sufficent amount of encodings, such as utf-16-le
                if result['encoding']:
                    file_encoding = result['encoding'].lower()
                    # TODO: outsource valid encodings
                    if not (file_encoding in ['utf-8', 'ascii']
                            or 'utf-8' in file_encoding):
                        log.error("WARNING: encoding of file {} is {}".format(
                            datafile.filename, file_encoding))
                else:
                    msg = "WARNING: encoding of file {} is not detectable".format(
                        datafile.filename)
                    log.error(msg)

                try:
                    write_to_file(fn.absolute, filebuffer)
                    fn.setownergroup()
                except:
                    error += '\n' + traceback()
                    print(error)

        if "uploadimport" in kwargs and not error:
            url = '/download/to_db?filename=' + escape(fn.href)
        else:
            url = '/download?dir=' + escape(dir)
            if error:
                url += '&error=' + escape(error)
        raise web.HTTPRedirect(url)
示例#5
0
文件: rest.py 项目: fbrundu/dimc
def validate(headers):

    validated = False

    try:
        token = headers["X-Auth-Token"]
        url = (pbc["aurl"] + "/p3/serviceValidate?" +
               "service=bimServiceProvider&ticket=" + token)
        r = requests.get(url, verify=pbc["acert"])
        root = list(ElementTree.fromstring(r.content))
        validated = root[0].tag.endswith("authenticationSuccess")
    except Exception:
        log.error(msg="Validation Error", context="HTTP", traceback=True)
        validated = False

    return validated
示例#6
0
    def __new__(self):
        """
        Return an instance of the first subclass of
        :class:`braubuddy.envcontroller.IEnvController` for which a device is
        discovered.
        """

        log('Auto-discovering Environmental Controller.')
        try:
            envcontroller = Tosr0xEnvController()
            log('Tosr0x Environmental Controller detected.')
            return envcontroller
        except DeviceError:
            log('No Tosr0x Environmental Controllers detected.')
        log.error('No compatible Environmental Controllers detected. '
                  'Using Dummy device.')
        return (DummyEnvController())
示例#7
0
    def publish_status(self, target, temp, heater_percent, cooler_percent):

        if (datetime.now() - self._last_published).seconds < self._frequency:
            # Don't Tweet until the defined frequency has passed.
            return

        message = self._message.format(units=self.units, temp=temp,
                                       target=target, heat=heater_percent,
                                       cool=cooler_percent)
        if len(message) > 140:
            log.error('TwitterAPIOutput message exceeds 140 '
                      'characters: {0}'.format(message))
        try:
            self._api.statuses.update(status=message)
            self._last_published = datetime.now()
        except Exception as err:
            raise OutputError(
                'Error publishing to Twitter API: {0}'.format(err))
示例#8
0
    def __new__(self):
        """
        Return an instance of the first subclass of
        :class:`braubuddy.envcontroller.IEnvController` for which a device is
        discovered.
        """

        log('Auto-discovering Environmental Controller.')
        try:
            envcontroller = Tosr0xEnvController()
            log('Tosr0x Environmental Controller detected.')
            return envcontroller
        except DeviceError:
            log('No Tosr0x Environmental Controllers detected.')
        log.error(
            'No compatible Environmental Controllers detected. '
            'Using Dummy device.')
        return(DummyEnvController())
示例#9
0
文件: rest.py 项目: fbrundu/bimp
    def GET(self, *paths, **params):

        try:
            # get buildings as JSON array
            result, internal_log = get_json(params)

            if internal_log:
                log.error(msg=internal_log, context='HTTP')

            # result to json
            response = json.dumps(result, indent=2).encode("utf8")

            # return response
            ctype = "application/json;charset=utf-8"
            cherrypy.response.headers["Content-Type"] = ctype

            return response
        except:
            return handle_error(500, "Internal Server Error")
示例#10
0
    def publish_status(self, target, temp, heater_percent, cooler_percent):

        if (datetime.now() - self._last_published).seconds < self._frequency:
            # Don't Tweet until the defined frequency has passed.
            return

        message = self._message.format(units=self.units,
                                       temp=temp,
                                       target=target,
                                       heat=heater_percent,
                                       cool=cooler_percent)
        if len(message) > 140:
            log.error('TwitterAPIOutput message exceeds 140 '
                      'characters: {0}'.format(message))
        try:
            self._api.statuses.update(status=message)
            self._last_published = datetime.now()
        except Exception as err:
            raise OutputError(
                'Error publishing to Twitter API: {0}'.format(err))
示例#11
0
    def default( self, *args, **kwargs ):
        filename = os.path.join(rootdir, 'epolicademo.html')
        lcd = ''
        msg = []
        if 'lcd' in kwargs: lcd = kwargs['lcd']
        
        if ( len( args ) > 0 ):
          #ucitavanje stanje LCD-a - TODO: tijekom inicijalizacije
          try:
            readContent( lcd )
          except:
            print sys.exc_info()
          #TODO: ovaj sadrzaj LCD-a dodati nekako u url
          if ( 'lcd16x2.html' == args[0] ):
            log.error("lcdsmall")
            filename=os.path.join(rootdir, 'lcd16x2.html')
          elif ( 'lcd20x4.html' == args[0] ):
            log.error("lcdbig")
            filename=os.path.join(rootdir, 'lcd20x4.html')

        if 'row1' in kwargs: msg.append( kwargs['row1'] )
        if 'row2' in kwargs: msg.append( kwargs['row2'] )
        if 'row3' in kwargs: msg.append( kwargs['row3'] )
        if 'row4' in kwargs: msg.append( kwargs['row4'] )
        
        if len(lcd) > 0:
				try:
					screen = lcds['lcd%s'%lcd]
					if len(msg) > 0:
						# we have the message - print it
						screen.write( msg )
						
						#snimanje stanja LCD-a!
						lcdfile = 'lcd%s.txt'%lcd
						print lcdfile, msg
						f = open( lcdfile, 'w' )
						for line in msg:
						  f.write(line)
						  f.write('\n')
						f.close()
					#else:
						# read existing screen content and add it to web form
						# TODO: process serving file!!!
						#kwargs['row1']="aman"
				except KeyError:
					log.error("lcd%s not found"%lcd)
            
        log.error("Serving %s" % filename)
        return serve_file(filename, content_type='text/html')
示例#12
0
文件: auto.py 项目: mlpilla/braubuddy
    def __new__(self):
        """
        Return an instance of the first subclass of
        :class:`braubuddy.thermometer.IThermometer` for which a device is
        discovered.
        """

        log('Auto-discovering Thermometer.')
        try:
            thermometer = DS18B20Thermometer()
            log('DS18B20 Thermometer detected.')
            return thermometer
        except DeviceError:
            pass
            log('No DS18B20 Thermometers detected.')
        try:
            thermometer = TEMPerThermometer()
            log('TEMPer Thermometer detected.')
            return thermometer
        except DeviceError:
            log('No TEMPer Thermometers detected.')
        log.error('No compatible Thermometers detected. Using Dummy device.')
        return (DummyThermometer())
示例#13
0
    def __new__(self):
        """
        Return an instance of the first subclass of
        :class:`braubuddy.thermometer.IThermometer` for which a device is
        discovered.
        """

        log('Auto-discovering Thermometer.')
        try:
            thermometer = DS18B20Thermometer()
            log('DS18B20 Thermometer detected.')
            return thermometer
        except DeviceError:
            pass
            log('No DS18B20 Thermometers detected.')
        try:
            thermometer = TEMPerThermometer()
            log('TEMPer Thermometer detected.')
            return thermometer
        except DeviceError:
            log('No TEMPer Thermometers detected.')
        log.error('No compatible Thermometers detected. Using Dummy device.')
        return(DummyThermometer())
示例#14
0
# main
lcds = {}

if __name__ == '__main__':

    lcds = lcd.scan()

    for i in range (1, len(lcds)+1):
      msg = readContent(i)
      print msg
      screen = lcds['lcd%s'%i]
      screen.write( msg )
      #time.sleep(1)
      
    #web app setup
    rootdir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'html' )
    picdir = os.path.join(rootdir, 'pic')

    log.error( "Root dir: "+rootdir )
    log.error( "Pic dir: "+picdir )

    conf = {'/pic': {'tools.staticdir.on': True,
                     'tools.staticdir.dir': picdir,
                     'tools.staticdir.content_types': {'png': 'image/png',
                                                       'jpg': 'image/jpg'}}}

    cherrypy.config.update({'server.socket_host': '0.0.0.0', 'server.socket_port': 80,'log.screen': True})

    cherrypy.quickstart(WebRoot(), "/", config=conf)