コード例 #1
0
ファイル: index.py プロジェクト: vickatte/jazz
def handler(event, context):
    # initialize logger module
    logger = Logger(event, context)
   
    # Load config handler   
    config = Config(context)

    ## ==== Sample code to fetch environment specific configurations ====
    # myconfig = config.get_config('default') === "default" is the section over here
    # logger.info ('One of the environment configuration: config_key => ' + myconfig['config_key'])

    ## ==== Log message samples ====
    # logger.error('Runtime errors or unexpected conditions.')
    # logger.warn('Runtime situations that are undesirable, but not wrong')
    # logger.info('Interesting runtime events eg. connection established)')
    # logger.verbose('Generally speaking, most log lines should be verbose.')
    # logger.debug('Detailed information on the flow through the system.')

    myconfig = config.get_config('default')

    logger.info('Sample response for function1.')
    return {
        "message": "Your function executed successfully!",
        "event": event,
        "myconfig": myconfig['config_key']
    }
コード例 #2
0
 def save_pickle(file_name, obj):
     """
     Pickle the Python object to the given file.
     """
     pickle_path = join(Config.get_config_folder(), file_name)
     with open(pickle_path, "wb") as f:
         dump(obj, f)
コード例 #3
0
ファイル: hotkey_handler.py プロジェクト: Zen-CODE/zenplayer
 def _load_hotkeymap():
     """
     Return the specified hotkey mappings. Load from the json file if
     we have not done that already.
     """
     mappings = Config.load("hotkeymap.json")
     return mappings["hotkeymap"]
コード例 #4
0
ファイル: webserver.py プロジェクト: Zen-CODE/zenplayer
 def start(ctrl):
     """ Start the ZenPlayer web API backend. """
     config = Config.load("webserver.json")
     Logger.info("Webserver: Starting web server ")
     thread = FlaskThread(ctrl, config)
     thread.daemon = True
     thread.start()
     WebServer._thread = thread
コード例 #5
0
 def __init__(self):
     config = Config().config
     redis_host = config["redis_db"]["host"]
     redis_port = config["redis_db"]["port"]
     redis_db = config["redis_db"]["db"]
     # @see https://stackoverflow.com/a/25958063
     self.__r = redis.Redis(host=redis_host,
                            port=redis_port,
                            db=redis_db,
                            decode_responses=True)
コード例 #6
0
 def load_pickle(file_name, default=None):
     """
     Unpickle the Python object from the given file. If it does
     not exist, return the default value.
     """
     pickle_path = join(Config.get_config_folder(), file_name)
     if exists(pickle_path):
         with open(pickle_path, "rb") as f:
             return load(f)
     else:
         return default
コード例 #7
0
ファイル: library.py プロジェクト: Zen-CODE/zenplayer
 def _get_data_frame(path):
     """ Return a pandas DataFrame with 'Artist', 'Album', 'Track', and
     'Cover' columns.
     """
     # This code saves the state in a pickle file for speed. Not worth it
     state_file = join(Config.get_config_folder(), "library-pd.pkl")
     if exists(state_file):
         df = pd.read_pickle(state_file)
     else:
         df = Library._build_data_frame(path)
         df.to_pickle(state_file)
     return df
コード例 #8
0
ファイル: loader.py プロジェクト: Zen-CODE/zenplayer
    def get_class_data(ctrl):
        """
        Return a list of dictionaries, where each dictionary contains the
        following keys:

            "name": The name of the class
            "instance": A reference to the instantiated instance of this class
            "methods": A list of public methods of the class exposed for the
                       API
        """
        class_list = Config.load("webserver_classes.json")
        ret = []
        for name in class_list:
            obj = Loader._get_class(name)(ctrl)
            ret.append({"name": name,
                        "instance": obj,
                        "methods": Loader._get_public_methods(obj)})
        return ret
コード例 #9
0
ファイル: index.py プロジェクト: vickatte/jazz
def handler(event, context):
    try:
        # initialize logger module
        logger = Logger(event, context)

        # Load config handler.
        config = Config(event)

        ## ==== Sample code to fetch environment specific configurations ====
        # myconfig = config.get_config('default')
        # logger.info ('One of the environment configuration: config_key => ' + myconfig['config_key'])

        ## ==== Log message samples ====
        # logger.error('Runtime errors or unexpected conditions.')
        # logger.warn('Runtime situations that are undesirable, but not wrong')
        # logger.info('Interesting runtime events eg. connection established)')
        # logger.verbose('Generally speaking, most log lines should be verbose.')
        # logger.debug('Detailed information on the flow through the system.')

        # This is the happy path
        data = {
            'key': 'value'
        }

        response = ""
        if 'method' in event:
            if event['method'] == "POST":
                # Handle Post response here
                logger.info('Sample log inside POST')
                response = CustomResponse(data, event['body']).get_json()
            else:
                # Handle Get/other response here.
                logger.info('Sample log inside GET')
                response = CustomResponse(data, event['query']).get_json()
        return response
    except Exception as e:
        # Exception Handling
        exception_type = e.__class__.__name__

        # Create a JSON string here
        api_exception_json = CustomErrors.throwInternalServerError(
            str(e))
        raise LambdaException(api_exception_json)
コード例 #10
0
def handler(event, context):
    try:

        # initialze logger module
        logger = Logger(event, context)

        # Load config handler.
        config = Config(event)

        logger.error('Runtime errors or unexpected conditions.')
        logger.warn('Runtime situations that are undesirable, but not wrong')
        logger.info('Interesting runtime events eg. connection established)')
        logger.verbose('Generally speaking, most log lines should be verbose.')
        logger.debug('Detailed information on the flow through the system.')

        # This is the happy path
        data = {
            'key': 'value'
        }

        response = ""
        if 'method' in event:
            if event['method'] == "POST":
                # Handle Post response here
                response = CustomResponse(data, event['body']).get_json()
            else:
                # Handle Get/other response here.
                response = CustomResponse(data, event['query']).get_json()
        return response
    except Exception as e:
        # Exception Handling
        exception_type = e.__class__.__name__
        exception_message = e.message

        # Create a JSON string here
        api_exception_json = CustomErrors.throwInternalServerError(
            exception_message)
        raise LambdaException(api_exception_json)
コード例 #11
0
 def _load_keymap():
     """ Load the specified key mappings from the json file. """
     mappings = Config.load("keymap.json")
     return mappings["keymap"]
コード例 #12
0
 def get():
     """
     Build and return an appropriately configured Storage class
     """
     return JsonStore(
         join(Config.get_config_folder(), "zenplayer_state.json"))
コード例 #13
0
ファイル: app.py プロジェクト: foza/sample-for-views
#!venv/bin/python3
from flask import Flask, jsonify, abort, request, make_response
from flask_httpauth import HTTPBasicAuth
from components.functions import *
from components.config import Config
from components.database import Database
from os import environ
import requests
app = Flask(__name__)
auth = HTTPBasicAuth()
config = Config()


@auth.verify_password
def verify_password(username, password):
    db = Database(config)
    user = db.getOneByParam(
        "SELECT `password` FROM `user` WHERE `username` = %s", username)
    if user is not None and user.get("password") is not None:
        if validatePassword(password, user.get("password")):
            return True
    return False


@auth.error_handler
def unauthorized():
    return make_response(get_response("Несанкционированный доступ", False),
                         403)


@app.errorhandler(404)
コード例 #14
0
ファイル: main.py プロジェクト: Zen-CODE/zenplayer
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self._config = Config.load("zenplayer.json")
     self.init_logging()