def get(self): """REST GET implementation for the URI: http://<server>:<port>/information/product Parameters ---------- Raises: ------ """ product = OrderedDict() product[CONTACT_KEY] = Product.get_contact() product[COPYRIGHT_KEY] = Product.get_copyright() product[NAME_KEY] = Product.get_project_name() product[VERSION_KEY] = Product.get_version() product[AUTHOR_KEY] = Product.get_author() product[DATE_KEY] = Product.get_date() if (ini_config.getboolean("SqlLite", "SQLITE_DB_ENABLE")): product[DATABASE_KEY] = "SQLite 3" elif (ini_config.getboolean("MongoDB", "MONGO_DB_ENABLE")): product[DATABASE_KEY] = "MongoDB 3.0.6" response = OrderedDict() response[STATUS_KEY] = STATUS_SUCCESS response[PRODUCT_KEY] = product logging.debug("Generating information about the software product [{0}]" .format(product)) ordered_response = jsonify(response) return ordered_response
def run(): """ daemon run function. This function should be called to start the system. """ from rgapps.utils.utility import get_log_file_handles logger_fds = get_log_file_handles(logging.getLogger()) logging.debug("Logger file handles fileno [{0}]".format(logger_fds)) system = platform.system() if system == "Linux": logging.info("Server running on Linux.") pid_file = ini_config.getboolean("Sensor", "SENSOR_PID_FILE") working_dir = ini_config.getboolean("Logging", "WORKING_DIR") logging.debug("Instantiating daemon with pid_file [{0}] " "and working_dir [{1}]" .format(pid_file, working_dir)) import daemon.pidfile daemon_context = daemon.DaemonContext( working_directory=working_dir, umask=0o002, pidfile=daemon.pidfile.PIDLockFile(pid_file)) logging.debug("Setting up daemon signal map") daemon_context.signal_map = { signal.SIGTERM: program_cleanup } logging.debug("daemon signal map has been setup") if (logger_fds): logging.debug("setting files_preserve for the log file " "descriptor [{0}]".format(logger_fds)) daemon_context.files_preserve = logger_fds logging.debug("Starting daemon by opening its context.") daemon_context.open() logging.info("Calling subscribe_sensor_data....") subscribe_sensor_data() logging.debug("Closing the daemon context.") daemon_context.close() else: logging.info("Server running on Windows system ...") subscribe_sensor_data()
def get_measurement(self): """ concrete implementation of abstract method in Sensor """ is_testing = ini_config.getboolean("Flask", "TESTING") if is_testing is True: logging.debug("Using a testing temperature from sensor [{0}].".format(self.serial)) temperature = 100 utc_time = "2001-07-09T00:00:01.105000+00:00" else: logging.debug("Reading temperature from sensor [{0}].".format(self.serial)) temperature = self.__get_sensor_temperature(self.serial) utc = arrow.utcnow() utc_time = str(utc) logging.debug("Sensor temperature in [{0}] is [{1}]".format(DEFAULT_TEMPERATURE_UNIT.name, temperature)) # use pint to represent temperature unit_reg = UnitRegistry(autoconvert_offset_to_baseunit=True) temperature_qty = temperature * unit_reg(DEFAULT_TEMPERATURE_UNIT.name) # restrict results to 2 decimal places. decimals = decimal_places(temperature_qty.magnitude) if decimals > 2: temperature_result = round(temperature_qty.magnitude, 2) else: temperature_result = temperature_qty.magnitude reading = Measurement(temperature_result, DEFAULT_TEMPERATURE_UNIT.name, utc_time) return reading
def teardown_request(exception): sql_enabled = ini_config.getboolean("SqlLite", "SQLITE_DB_ENABLE") sql_db = ini_config.get("SqlLite", "SQLITE_DB") # disconnect DB connection only if DB is enabled if sql_enabled and hasattr(g, 'db'): g.db.close() logging.debug("Disconnected from DB [{0}]".format(sql_db)) return
def write_to_file(msg, fileToWrite): """ Simple utility to write to file. It is to replace the following that has been deprecated in Python 3.4: print >> file, "some text Parameters ---------- msg: string (optional) A text message fileToWrite: file (required) An existing writeable file Returns ------- Nothing """ if not fileToWrite: raise IllegalArgumentException("fileToWrite is required.") if not hasattr(fileToWrite, "read"): raise IllegalArgumentException("fileToWrite is not a file object.") is_debug = ini_config.getboolean("Flask", "DEBUG") if is_debug: for attr in dir(fileToWrite): try: thing = getattr(fileToWrite, attr) logging.debug("fileToWrite.{0} = {1}" .format(attr, thing)) except AttributeError: logging.warning("attr [{0}] not found in fileToWrite" .format(attr)) else: logging.error("error getting attr [{0}] from fileToWrite" .format(attr)) if not fileToWrite.closed: logging.debug("writing [{0}] to file" .format(msg)) fileToWrite.write(msg) logging.debug("writing was successful.") else: logging.warning("msg [{0}] NOT written: file closed." .format(msg)) return
def before_request(): """ Handler to be run at the beginning of every single request to ensure that the income request is compliant to the existing REST API. For example, it checks to ensure that the ACCEPT HTTP Header contains the Content Type support by the REST API. """ url = request.url logging.debug("Requested URL [{0}]".format(url)) accept = request.headers.get('Accept') logging.debug("HTTP Request Header Accept [{0}]".format(accept)) accept_language = request.headers.get('Accept-Language') logging.debug("HTTP Request Header Accept-Language [{0}]" .format(accept_language)) content_length = request.headers.get('Content-Length') logging.debug("HTTP Request Content-Length [{0}]" .format(content_length)) ip = request.remote_addr logging.debug("Client IP Address [{0}]".format(ip)) user_agent = request.headers.get('User-Agent') logging.debug("HTTP Client User-Agent [{0}]" .format(user_agent)) date = request.headers.get("Date") logging.debug("HTTP Request date [{0}]".format(date)) json_weigth = request.accept_mimetypes["application/json"] logging.debug("application/json accept weight [{0}]" .format(json_weigth)) if json_weigth <= 0: # The incoming HTTP Accept header specifies a media type that is # not supported by this application REST API. Currently, only # the JSON media type is accepted. msg = "HTTP Request Header Accept [{0}] not supported".format(accept) logging.warn(msg) raise NotAcceptable(msg) method = request.method if method != 'GET': # At this time only 'GET' methods are accepted msg = "HTTP Method [{0}] not supported".format(accept) logging.warn(msg) raise MethodNotAllowed(msg) # acquire DB connection only if DB is enabled is_sql_enabled = ini_config.getboolean("SqlLite", "SQLITE_DB_ENABLE") sql_db = ini_config.get("SqlLite", "SQLITE_DB") if is_sql_enabled : db = getattr(g, 'db', None) if db is None: g.db = sqlite3.connect(sql_db) logging.debug("Connected to DB [{0}]".format(sql_db)) return
def run(): """ daemon run function. This function should be called to start the system. """ instance_path = ini_config.get("Flask", "INSTANCE_PATH") # app: Flask application object logging.debug("initializing the Flask app") global globalFlaskApp globalFlaskApp = Flask(__name__, instance_path=instance_path, instance_relative_config=True) is_debug = ini_config.getboolean("Flask", "DEBUG") is_testing = ini_config.getboolean("Flask", "TESTING") is_json_sort_keys = ini_config.getboolean("Flask", "JSON_SORT_KEYS") max_content_length = ini_config.getint("Flask", "MAX_CONTENT_LENGTH") globalFlaskApp.config.update(DEBUG=is_debug, TESTING=is_testing, JSON_SORT_KEYS=is_json_sort_keys, MAX_CONTENT_LENGTH=max_content_length) with globalFlaskApp.app_context(): logging.info("Starting application ...") from rgapps.utils.utility import get_log_file_handles logger_fds = get_log_file_handles(logging.getLogger()) logging.debug("Logger file handles fileno [{0}]" .format(logger_fds)) system = platform.system() if system == "Linux": logging.info("Server running on Linux.") pid_file = ini_config.get("Sensor", "SENSOR_PID_FILE") working_dir = ini_config.get("Logging", "WORKING_DIR") logging.debug("Instantiating daemon with pid_file [{0}] " "and working_dir [{1}]" .format(pid_file, working_dir)) import daemon.pidfile daemon_context = daemon.DaemonContext( working_directory=working_dir, umask=0o002, pidfile=daemon.pidfile.PIDLockFile(pid_file)) logging.debug("Setting up daemon signal map") daemon_context.signal_map = { signal.SIGTERM: program_cleanup } logging.debug("daemon signal map has been setup") if (logger_fds): logging.debug("setting files_preserve for the log file " "descriptor [{0}]" .format(logger_fds)) daemon_context.files_preserve = logger_fds logging.debug("Starting daemon by opening its context.") daemon_context.open() logging.info("Calling read_store_readings....") read_store_readings() logging.debug("Closing the daemon context.") daemon_context.close() else: logging.info("Server running on Windows system ...") read_store_readings() return
__author__ = "Rubens S. Gomes <*****@*****.**>" __copyright__ = "Copyright (c) 2015 Rubens S. Gomes" __license__ = "All Rights Reserved" __maintainer__ = "Rubens Gomes" __email__ = "*****@*****.**" __status__ = "Experimental" instance_path = ini_config.get("Flask", "INSTANCE_PATH") logging.info("creating Flask app ...") app = Flask(__name__, instance_path=instance_path, instance_relative_config=True) is_debug = ini_config.getboolean("Flask", "DEBUG") is_testing = ini_config.getboolean("Flask", "TESTING") is_json_sort_keys = ini_config.getboolean("Flask", "JSON_SORT_KEYS") max_content_length = ini_config.getint("Flask", "MAX_CONTENT_LENGTH") app.config.update(DEBUG=is_debug, TESTING=is_testing, JSON_SORT_KEYS=is_json_sort_keys, MAX_CONTENT_LENGTH=max_content_length) with app.app_context(): logging.info("Configuring the Flask HTTP routing.") setup_routes() logging.info("Setting up the Flask functions.") import rgapps.http.flaskfunctions