Ejemplo n.º 1
0
def require_auth():
    if request.method == 'OPTIONS':
        return

    auth = request.headers.get('Authorization')

    g.auth_user = None

    if auth and auth.startswith('Bearer '):
        token = auth.split(' ', 1)[1]
        g.auth_user = User.verify_session_token(token)
        # Not a session token? Maybe APIKey token
        if g.auth_user is None:
            g.auth_user = APIKey.verify_token(token)
        # Still nothing? Maybe legacy API key
        if g.auth_user is None:
            g.auth_user = User.verify_legacy_token(token)
            if g.auth_user is not None:
                log.getLogger().warning(
                    "'%s' used legacy auth token for authentication",
                    g.auth_user.login)

    if g.auth_user:
        if app_config.malwarecage.enable_maintenance and g.auth_user.login != app_config.malwarecage.admin_login:
            raise Forbidden('Maintenance underway. Please come back later.')

        if g.auth_user.disabled:
            raise Forbidden("User has been disabled.")

        if app_config.malwarecage.enable_rate_limit and not g.auth_user.has_rights(
                Capabilities.unlimited_requests):
            """
            Single sample view in malwarefront generates 7 requests (6 GET, 1 POST)
            """
            conn = redis.from_url(app_config.malwarecage.redis_uri)
            if request.method == 'GET':
                """
                DownloadResource is token-based and shouldn't be limited
                """
                if request.endpoint != 'downloadresource':
                    # 1000 per 10 seconds
                    rate_limit(conn, "get-request", 10, 1000)
                    # 2000 per 1 minute
                    rate_limit(conn, "get-request", 60, 2000)
                    # 6000 per 5 minutes
                    rate_limit(conn, "get-request", 5 * 60, 6000)
                    # 10000 per 15 minutes
                    rate_limit(conn, "get-request", 15 * 60, 10000)
            else:
                # 10 per 10 seconds
                rate_limit(conn, "set-request", 10, 10)
                # 30 per 1 minute
                rate_limit(conn, "set-request", 60, 30)
                # 100 per 5 minutes
                rate_limit(conn, "set-request", 5 * 60, 100)
                # 200 per 15 minutes
                rate_limit(conn, "set-request", 15 * 60, 200)
Ejemplo n.º 2
0
def log_request(response):
    response_time = datetime.utcnow() - g.request_start_time
    response_size = response.calculate_content_length()

    log.getLogger().info('request',
                         extra={
                             'path': request.path,
                             'arguments': request.args,
                             'method': request.method,
                             'status': response.status_code,
                             'response_time': response_time,
                             'response_size': response_size
                         })

    return response
Ejemplo n.º 3
0
 def __init__(self):
     self.log = getLogger("core.osgi.events.OsgiEventHandler")
     self.registration = BUNDLE_CONTEXT.registerService(
         EventHandler, self,
         hashtable((EventConstants.EVENT_TOPIC, ["*"])))
     self.log.info("Registered openHAB OSGi event listener service")
     self.log.debug("Registration: [{}]".format(self.registration))
Ejemplo n.º 4
0
def to_joda_datetime(value):
    # type: (t.Any) -> JodaDateTime
    """
    Converts any of the supported date types to ``org.joda.time.DateTime``. If
    ``value`` does not have timezone information, the system default will be
    used.

    Examples:
        .. code-block::

            joda_time = to_joda_datetime(items["date_item"])

    Args:
        value: the value to convert

    Returns:
        org.joda.time.DateTime: the converted value
        None: if ``org.joda.time`` is not available

    Raises:
        TypeError: if the type of ``value`` is not suported by this package
    """
    if JodaDateTime is None:
        frame = inspect.stack()[1]
        getLogger("date").warn(
            "'{func}' ({file}:{line}) called 'to_joda_datetime' but Joda is not available"
            .format(file=frame.filename,
                    line=frame.lineno,
                    func=frame.function))
        del frame
        return None

    if isinstance(value, JodaDateTime):
        return value

    value_zoneddatetime = to_java_zoneddatetime(value)
    return JodaDateTime(
        value_zoneddatetime.toInstant().toEpochMilli(),
        JodaDateTimeZone.forTimeZone(
            TimeZone.getTimeZone(value_zoneddatetime.getZone())))
Ejemplo n.º 5
0
def create_admin(name, email, password, require_empty):
    logger = log.getLogger()
    g.request_id = "cli"
    g.request_start_time = datetime.utcnow()

    if require_empty:
        if Group.query.count() > 0 and User.query.count() > 0:
            logger.info(
                'Some users and groups already exist in the database. No changes were made.'
            )
            return

    try:
        group = Group(name='public', capabilities=[])
        db.session.add(group)
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        db.session.rollback()
        logger.exception('Group public already exists, no changes were made.')
    else:
        logger.info('Succesfully added group public"')

    try:
        group = Group(name=name, capabilities=Capabilities.all(), private=True)
        db.session.add(group)
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        db.session.rollback()
        logger.exception('Group already exists, no changes were made.')
    else:
        logger.info('Succesfully added group %s', name)

    group = db.session.query(Group).filter(Group.name == name).first()

    try:
        user = User(login=name, email=email)
        user.set_password(password)
        user.version_uid = '0' * 16
        user.identity_ver = '0' * 16
        user.password_ver = '0' * 16
        user.groups.append(group)
        user.groups.append(Group.public_group())
        db.session.add(user)
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        db.session.rollback()
        logger.exception('User already exists, no changes were made.')
    else:
        logger.info('Succesfully added admin user %s', name)
Ejemplo n.º 6
0
 def __init__(self, callback, triggers, name=None, description=None, tags=None):
     self.triggers = triggers
     if name is None:
         if hasattr(callback, '__name__'):
             name = callback.__name__
         else:
             name = "JSR223-Jython"
     self.name = name
     callback.log = getLogger(name)
     callback.name = name
     self.callback = callback
     if description is not None:
         self.description = description
     if tags is not None:
         self.tags = set(tags)
Ejemplo n.º 7
0
class OsgiEventAdmin(object):

    _event_handler = None
    event_listeners = []
    log = getLogger(u"core.osgi.events.OsgiEventAdmin")

    # Singleton
    class OsgiEventHandler(EventHandler):
        def __init__(self):
            self.log = getLogger("core.osgi.events.OsgiEventHandler")
            self.registration = BUNDLE_CONTEXT.registerService(
                EventHandler, self,
                hashtable((EventConstants.EVENT_TOPIC, ["*"])))
            self.log.info("Registered openHAB OSGi event listener service")
            self.log.debug("Registration: [{}]".format(self.registration))

        def handleEvent(self, event):
            self.log.critical("Handling event: [{}]".format(event))
            for listener in OsgiEventAdmin.event_listeners:
                try:
                    listener(event)
                except:
                    self.log.error("Listener failed: '{}'".format(
                        traceback.format_exc()))

        def dispose(self):
            self.registration.unregister()

    @classmethod
    def add_listener(class_, listener):
        class_.log.debug("Adding listener admin: '{} {}'".format(
            id(class_), listener))
        class_.event_listeners.append(listener)
        if len(class_.event_listeners) == 1:
            if class_._event_handler is None:
                class_._event_handler = class_.OsgiEventHandler()

    @classmethod
    def remove_listener(class_, listener):
        class_.log.debug("Removing listener: '{}'".format(listener))
        if listener in class_.event_listeners:
            class_.event_listeners.remove(listener)
        if not class_.event_listeners:
            if class_._event_handler is not None:
                class_.log.info(
                    "Unregistering openHAB OSGi event listener service")
                class_._event_handler.dispose()
                class_._event_handler = None
Ejemplo n.º 8
0
 def init(self, *args, **kwargs):
     SimpleRule.__init__(self)
     if name is None:
         if hasattr(class_, '__name__'):
             self.name = class_.__name__
         else:
             self.name = "JSR223-Jython"
     else:
         self.name = name
     # set_uid_prefix(self)
     self.log = getLogger(self.name)
     class_.__init__(self, *args, **kwargs)
     if description is not None:
         self.description = description
     elif self.description is None and class_.__doc__:
         self.description = class_.__doc__
     if hasattr(self, "getEventTriggers"):
         self.triggers = log_traceback(self.getEventTriggers)()
     if tags is not None:
         self.tags = set(tags)
Ejemplo n.º 9
0
    'addRule'#,
    # 'set_uid_prefix'
]

from inspect import isclass
# from java.util import UUID

# try:
#     from org.openhab.core.automation import Rule as SmarthomeRule
# except:
#     from org.eclipse.smarthome.automation import Rule as SmarthomeRule

from core.log import getLogger, log_traceback
from core.jsr223.scope import SimpleRule, scriptExtension

LOG = getLogger("core.rules")

scriptExtension.importPreset("RuleSimple")

def rule(name=None, description=None, tags=None):
    """
    This decorator can be used with both functions and classes to create rules.

    See :ref:`Guides/Rules:Decorators` for a full description of how to use
    this decorator.

    Examples:
        .. code-block::

          @rule('name', 'description', ['tag1', 'tag2'])
          @rule('name', tags=['tag1', 'tag2'])
Ejemplo n.º 10
0
def when(target):
    """
    This function decorator creates a ``triggers`` attribute in the decorated
    function, which is used by the ``rule`` decorator when creating the rule.
    The ``when`` decorator simplifies the use of many of the triggers in this
    module and allows for them to be used with natural language similar to what
    is used in the rules DSL.

    See :ref:`Guides/Rules:Decorators` for examples of how to use this
    decorator.

    Examples:
        .. code-block::

            @when("Time cron 55 55 5 * * ?")
            @when("Item Test_String_1 changed from 'old test string' to 'new test string'")
            @when("Item gMotion_Sensors changed")
            @when("Member of gMotion_Sensors changed from ON to OFF")
            @when("Descendent of gContact_Sensors changed from OPEN to CLOSED")
            @when("Item Test_Switch_2 received update ON")
            @when("Item Test_Switch_1 received command OFF")
            @when("Item added")
            @when("Item removed")
            @when("Item updated")
            @when("Thing added")
            @when("Thing removed")
            @when("Thing updated")
            @when("Thing kodi:kodi:familyroom changed")
            @when("Thing kodi:kodi:familyroom changed from ONLINE to OFFLINE")# requires S1636, 2.5M2 or newer
            @when("Thing kodi:kodi:familyroom received update ONLINE")# requires S1636, 2.5M2 or newer
            @when("Channel astro:sun:local:eclipse#event triggered START")# must use a Channel of kind Trigger
            @when("System started")# requires S1566, 2.5M2 or newer ('System shuts down' has not been implemented)
            @when("Directory /opt/test [created, deleted, modified]")# requires S1566, 2.5M2 or newer
            @when("Subdirectory 'C:\My Stuff' [created]")# requires S1566, 2.5M2 or newer

    Args:
        target (string): the `rules DSL-like formatted trigger expression <https://www.openhab.org/docs/configuration/rules-dsl.html#rule-triggers>`_
            to parse
    """
    from os import path

    itemRegistry = scriptExtension.get("itemRegistry")  # type: t_itemRegistry
    things = scriptExtension.get("things")  # type: t_things
    from core.log import getLogger

    try:
        from org.openhab.core.thing import ChannelUID, ThingUID, ThingStatus
        from org.openhab.core.thing.type import ChannelKind
    except:
        from org.eclipse.smarthome.core.thing import ChannelUID, ThingUID, ThingStatus
        from org.eclipse.smarthome.core.thing.type import ChannelKind

    try:
        from org.eclipse.smarthome.core.types import TypeParser
    except:
        from org.openhab.core.types import TypeParser

    try:
        from org.quartz.CronExpression import isValidExpression
    except:
        # Quartz is removed in OH3, this needs to either impliment or match
        # functionality in `org.openhab.core.internal.scheduler.CronAdjuster`
        def isValidExpression(expr):
            import re

            expr = expr.strip()
            if expr.startswith("@"):
                return re.match(
                    r"@(annually|yearly|monthly|weekly|daily|hourly|reboot)",
                    expr) is not None

            parts = expr.split()
            if 6 <= len(parts) <= 7:
                for i in range(len(parts)):
                    if not re.match(
                            r"\?|(\*|\d+)(\/\d+)?|(\d+|\w{3})(\/|-)(\d+|\w{3})|((\d+|\w{3}),)*(\d+|\w{3})",
                            parts[i]):
                        return False
                return True
            return False

    LOG = getLogger(u"core.triggers")

    try:

        def item_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []

            if trigger_target in ["added", "removed", "updated"]:
                event_names = {
                    "added": "ItemAddedEvent",
                    "removed": "ItemRemovedEvent",
                    "updated": "ItemUpdatedEvent"
                }
                trigger_name = "Item-{}".format(
                    event_names.get(trigger_target))
                function.triggers.append(
                    ItemEventTrigger(event_names.get(trigger_target),
                                     trigger_name=trigger_name).trigger)
            else:
                item = itemRegistry.getItem(trigger_target)
                group_members = []
                if target_type == "Member of":
                    group_members = item.getMembers()
                elif target_type == "Descendent of":
                    group_members = item.getAllMembers()
                else:
                    group_members = [item]
                for member in group_members:
                    trigger_name = "Item-{}-{}{}{}{}{}".format(
                        member.name, trigger_type.replace(" ", "-"),
                        "-from-{}".format(old_state) if old_state is not None
                        else "", "-to-" if new_state is not None
                        and trigger_type == "changed" else "",
                        "-" if trigger_type == "received update"
                        and new_state is not None else "",
                        new_state if new_state is not None else "")
                    trigger_name = validate_uid(trigger_name)
                    if trigger_type == "received update":
                        function.triggers.append(
                            ItemStateUpdateTrigger(
                                member.name,
                                state=new_state,
                                trigger_name=trigger_name).trigger)
                    elif trigger_type == "received command":
                        function.triggers.append(
                            ItemCommandTrigger(
                                member.name,
                                command=new_state,
                                trigger_name=trigger_name).trigger)
                    else:
                        function.triggers.append(
                            ItemStateChangeTrigger(
                                member.name,
                                previous_state=old_state,
                                state=new_state,
                                trigger_name=trigger_name).trigger)
                    LOG.trace(u"when: Created item_trigger: '{}'".format(
                        trigger_name))
            return function

        def cron_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            function.triggers.append(
                CronTrigger(trigger_type, trigger_name=trigger_name).trigger)
            LOG.trace(u"when: Created cron_trigger: '{}'".format(trigger_name))
            return function

        def system_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            #if trigger_target == "started":
            function.triggers.append(
                StartupTrigger(trigger_name=trigger_name).trigger)
            #else:
            #    function.triggers.append(ShutdownTrigger(trigger_name=trigger_name).trigger)
            LOG.trace(
                u"when: Created system_trigger: '{}'".format(trigger_name))
            return function

        def thing_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            if trigger_target in ["added", "removed", "updated"]:
                event_names = {
                    "added": "ThingAddedEvent",
                    "removed": "ThingRemovedEvent",
                    "updated": "ThingUpdatedEvent"
                }
                function.triggers.append(
                    ThingEventTrigger(event_names.get(trigger_target),
                                      trigger_name=trigger_name).trigger)
            elif new_state is not None or old_state is not None:
                if trigger_type == "changed":
                    function.triggers.append(
                        ThingStatusChangeTrigger(
                            trigger_target,
                            previous_status=old_state,
                            status=new_state,
                            trigger_name=trigger_name).trigger)
                else:
                    function.triggers.append(
                        ThingStatusUpdateTrigger(
                            trigger_target,
                            status=new_state,
                            trigger_name=trigger_name).trigger)
            else:
                event_types = "ThingStatusInfoChangedEvent" if trigger_type == "changed" else "ThingStatusInfoEvent"
                function.triggers.append(
                    ThingEventTrigger(event_types,
                                      trigger_target,
                                      trigger_name=trigger_name).trigger)
            LOG.trace(
                u"when: Created thing_trigger: '{}'".format(trigger_name))
            return function

        def channel_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            function.triggers.append(
                ChannelEventTrigger(trigger_target,
                                    event=new_state,
                                    trigger_name=trigger_name).trigger)
            LOG.trace(
                u"when: Created channel_trigger: '{}'".format(trigger_name))
            return function

        def directory_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            event_kinds = []
            if "created" in trigger_type:
                event_kinds.append(ENTRY_CREATE)
            if "deleted" in trigger_type:
                event_kinds.append(ENTRY_DELETE)
            if "modified" in trigger_type:
                event_kinds.append(ENTRY_MODIFY)
            if event_kinds == []:
                event_kinds = [ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY]
            function.triggers.append(
                DirectoryEventTrigger(
                    trigger_target,
                    event_kinds=event_kinds,
                    watch_subdirectories=target_type == "Subdirectory",
                    trigger_name=trigger_name).trigger)
            LOG.trace(
                u"when: Created channel_trigger: '{}'".format(trigger_name))
            return function

        target_type = None
        trigger_target = None
        trigger_type = None
        old_state = None
        new_state = None
        trigger_name = None

        if isValidExpression(target):
            # a simple cron target was used, so add a default target_type and trigger_target (Time cron XXXXX)
            target_type = "Time"
            trigger_target = "cron"
            trigger_type = target
            trigger_name = "Time-cron-{}".format(target)
        else:
            from shlex import split

            input_list = split(target)
            if len(input_list) > 1:
                # target_type trigger_target [trigger_type] [from] [old_state] [to] [new_state]
                while input_list:
                    if target_type is None:
                        if " ".join(input_list[0:2]) in [
                                "Member of", "Descendent of"
                        ]:
                            target_type = " ".join(input_list[0:2])
                            input_list = input_list[2:]
                        else:
                            target_type = input_list.pop(0)
                    elif trigger_target is None:
                        if target_type == "System" and len(input_list) > 1:
                            raise ValueError(
                                u"when: \"{}\" could not be parsed. trigger_type '{}' is invalid for target_type 'System'. The only valid trigger_type is 'started'."
                                .format(target, target_type))
                            # if " ".join(input_list[0:2]) == "shuts down":
                            #     trigger_target = "shuts down"
                        else:
                            trigger_target = input_list.pop(0)
                    elif trigger_type is None:
                        if "received" in " ".join(input_list[0:2]):
                            if " ".join(input_list[0:2]) == "received update":
                                if target_type in [
                                        "Item", "Thing", "Member of",
                                        "Descendent of"
                                ]:
                                    input_list = input_list[2:]
                                    trigger_type = "received update"
                                else:
                                    raise ValueError(
                                        u"when: \"{}\" could not be parsed. 'received update' is invalid for target_type '{}'. The valid options are 'Item', 'Thing', 'Member of', or 'Descendent of'."
                                        .format(target, target_type))
                            elif " ".join(
                                    input_list[0:2]) == "received command":
                                if target_type in [
                                        "Item", "Member of", "Descendent of"
                                ]:
                                    input_list = input_list[2:]
                                    trigger_type = "received command"
                                else:
                                    raise ValueError(
                                        u"when: \"{}\" could not be parsed. 'received command' is invalid for target_type '{}'. The valid options are 'Item', 'Member of', or 'Descendent of'."
                                        .format(target, target_type))
                            else:
                                raise ValueError(
                                    u"when: \"{}\" could not be parsed. '{}' is invalid for target_type '{}'. The valid options are 'received update' or 'received command'."
                                    .format(target, " ".join(input_list[0:2]),
                                            target_type))
                        elif input_list[0][0] == "[":
                            if input_list[0][
                                    -1] == "]":  # if there are no spaces separating the event_kinds, it's ready to go
                                trigger_type = input_list.pop(0).replace(
                                    " ", "").strip("[]'\"").split(",")
                            else:
                                event_kinds = input_list.pop(0).replace(
                                    " ", "").strip("[]'\"")
                                found_closing_bracket = False
                                while input_list and not found_closing_bracket:
                                    if input_list[0][-1] == "]":
                                        found_closing_bracket = True
                                    event_kinds = "{}{}".format(
                                        event_kinds,
                                        input_list.pop(0).replace(
                                            " ", "").strip("[]'\""))
                                trigger_type = event_kinds.split(",")
                            if target_type in ["Directory", "Subdirectory"]:
                                for event_kind in trigger_type:
                                    if event_kind not in [
                                            "created", "deleted", "modified"
                                    ]:  # ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY
                                        raise ValueError(
                                            u"when: \"{}\" could not be parsed. trigger_type '{}' is invalid for target_type '{}'. The valid options are 'created', 'deleted', or 'modified'."
                                            .format(target, trigger_type,
                                                    target_type))
                            else:
                                raise ValueError(
                                    u"when: \"{}\" could not be parsed. target_type '{}' is invalid for trigger_target '{}'. The valid options are 'Directory' or 'Subdirectory'."
                                    .format(target, target_type,
                                            trigger_target))
                        elif input_list[0] == "changed":
                            if target_type in [
                                    "Item", "Thing", "Member of",
                                    "Descendent of"
                            ]:
                                input_list.pop(0)
                                trigger_type = "changed"
                            else:
                                raise ValueError(
                                    u"when: \"{}\" could not be parsed. 'changed' is invalid for target_type '{}'"
                                    .format(target, target_type))
                        elif input_list[0] == "triggered":
                            if target_type == "Channel":
                                trigger_type = input_list.pop(0)
                            else:
                                raise ValueError(
                                    u"when: \"{}\" could not be parsed. 'triggered' is invalid for target_type '{}'. The only valid option is 'Channel'."
                                    .format(target, target_type))
                        elif trigger_target == "cron":
                            if target_type == "Time":
                                if isValidExpression(" ".join(input_list)):
                                    trigger_type = " ".join(input_list)
                                    del input_list[:]
                                else:
                                    raise ValueError(
                                        u"when: \"{}\" could not be parsed. '{}' is not a valid cron expression. See http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-06."
                                        .format(target, " ".join(input_list)))
                            else:
                                raise ValueError(
                                    u"when: \"{}\" could not be parsed. 'cron' is invalid for target_type '{}'"
                                    .format(target, target_type))
                        else:
                            raise ValueError(
                                u"when: \"{}\" could not be parsed because the trigger_type {}"
                                .format(
                                    target,
                                    "is missing" if input_list[0] is None else
                                    "'{}' is invalid".format(input_list[0])))
                    else:
                        if old_state is None and trigger_type == "changed" and input_list[
                                0] == "from":
                            input_list.pop(0)
                            old_state = input_list.pop(0)
                        elif new_state is None and trigger_type == "changed" and input_list[
                                0] == "to":
                            input_list.pop(0)
                            new_state = input_list.pop(0)
                        elif new_state is None and (
                                trigger_type == "received update"
                                or trigger_type == "received command"):
                            new_state = input_list.pop(0)
                        elif new_state is None and target_type == "Channel":
                            new_state = input_list.pop(0)
                        elif input_list:  # there are no more possible combinations, but there is more data
                            raise ValueError(
                                u"when: \"{}\" could not be parsed. '{}' is invalid for '{} {} {}'"
                                .format(target, input_list, target_type,
                                        trigger_target, trigger_type))

            else:
                # a simple Item target was used (just an Item name), so add a default target_type and trigger_type (Item XXXXX changed)
                if target_type is None:
                    target_type = "Item"
                if trigger_target is None:
                    trigger_target = target
                if trigger_type is None:
                    trigger_type = "changed"

        # validate the inputs, and if anything isn't populated correctly throw an exception
        if target_type is None or target_type not in [
                "Item", "Member of", "Descendent of", "Thing", "Channel",
                "System", "Time", "Directory", "Subdirectory"
        ]:
            raise ValueError(
                u"when: \"{}\" could not be parsed. target_type is missing or invalid. Valid target_type values are: Item, Member of, Descendent of, Thing, Channel, System, Time, Directory, and Subdirectory."
                .format(target))
        elif target_type != "System" and trigger_target not in [
                "added", "removed", "updated"
        ] and trigger_type is None:
            raise ValueError(
                u"when: \"{}\" could not be parsed because trigger_type cannot be None"
                .format(target))
        elif target_type in ["Item", "Member of", "Descendent of"
                             ] and trigger_target not in [
                                 "added", "removed", "updated"
                             ] and itemRegistry.getItems(trigger_target) == []:
            raise ValueError(
                u"when: \"{}\" could not be parsed because Item '{}' is not in the ItemRegistry"
                .format(target, trigger_target))
        elif target_type in [
                "Member of", "Descendent of"
        ] and itemRegistry.getItem(trigger_target).type != "Group":
            raise ValueError(
                u"when: \"{}\" could not be parsed because '{}' was specified, but '{}' is not a group"
                .format(target, target_type, trigger_target))
        elif target_type == "Item" and trigger_target not in [
                "added", "removed", "updated"
        ] and old_state is not None and trigger_type == "changed" and TypeParser.parseState(
                itemRegistry.getItem(trigger_target).acceptedDataTypes,
                old_state) is None:
            raise ValueError(
                u"when: \"{}\" could not be parsed because '{}' is not a valid state for '{}'"
                .format(target, old_state, trigger_target))
        elif target_type == "Item" and trigger_target not in [
                "added", "removed", "updated"
        ] and new_state is not None and (
                trigger_type == "changed" or trigger_type
                == "received update") and TypeParser.parseState(
                    itemRegistry.getItem(trigger_target).acceptedDataTypes,
                    new_state) is None:
            raise ValueError(
                u"when: \"{}\" could not be parsed because '{}' is not a valid state for '{}'"
                .format(target, new_state, trigger_target))
        elif target_type == "Item" and trigger_target not in [
                "added", "removed", "updated"
        ] and new_state is not None and trigger_type == "received command" and TypeParser.parseCommand(
                itemRegistry.getItem(trigger_target).acceptedCommandTypes,
                new_state) is None:
            raise ValueError(
                u"when: \"{}\" could not be parsed because '{}' is not a valid command for '{}'"
                .format(target, new_state, trigger_target))
        elif target_type == "Thing" and trigger_target not in [
                "added", "removed", "updated"
        ] and things.get(ThingUID(trigger_target)
                         ) is None:  # returns null if Thing does not exist
            raise ValueError(
                u"when: \"{}\" could not be parsed because Thing '{}' is not in the ThingRegistry"
                .format(target, trigger_target))
        elif target_type == "Thing" and old_state is not None and not hasattr(
                ThingStatus, old_state):
            raise ValueError(
                u"when: '{}' is not a valid Thing status".format(old_state))
        elif target_type == "Thing" and new_state is not None and not hasattr(
                ThingStatus, new_state):
            raise ValueError(
                u"when: '{}' is not a valid Thing status".format(new_state))
        elif target_type == "Thing" and trigger_target not in [
                "added", "removed", "updated"
        ] and trigger_type is None:
            raise ValueError(
                u"when: \"{}\" could not be parsed. trigger_target '{}' is invalid for target_type 'Thing'. The only valid trigger_type values are 'added', 'removed', and 'updated'."
                .format(target, trigger_target))
        elif target_type == "Channel" and things.getChannel(
                ChannelUID(trigger_target)
        ) is None:  # returns null if Channel does not exist
            raise ValueError(
                u"when: \"{}\" could not be parsed because Channel '{}' does not exist"
                .format(target, trigger_target))
        elif target_type == "Channel" and things.getChannel(
                ChannelUID(trigger_target)).kind != ChannelKind.TRIGGER:
            raise ValueError(
                u"when: \"{}\" could not be parsed because '{}' is not a trigger Channel"
                .format(target, trigger_target))
        elif target_type == "System" and trigger_target != "started":  # and trigger_target != "shuts down":
            raise ValueError(
                u"when: \"{}\" could not be parsed. trigger_target '{}' is invalid for target_type 'System'. The only valid trigger_type value is 'started'."
                .format(target, target_type
                        ))  # and 'shuts down'".format(target, target_type))
        elif target_type in ["Directory", "Subdirectory"
                             ] and not path.isdir(trigger_target):
            raise ValueError(
                u"when: \"{}\" could not be parsed. trigger_target '{}' does not exist or is not a directory."
                .format(target, target_type))
        elif target_type in ["Directory", "Subdirectory"] and any(
                event_kind for event_kind in trigger_type
                if event_kind not in ["created", "deleted", "modified"]):
            raise ValueError(
                u"when: \"{}\" could not be parsed. trigger_target '{}' is invalid for target_type '{}'."
                .format(target, trigger_target, target_type))

        LOG.trace(
            u"when: target: '{}', target_type: '{}', trigger_target: '{}', trigger_type: '{}', old_state: '{}', new_state: '{}'"
            .format(target, target_type, trigger_target, trigger_type,
                    old_state, new_state))

        trigger_name = validate_uid(trigger_name or target)
        if target_type in ["Item", "Member of", "Descendent of"]:
            return item_trigger
        elif target_type == "Thing":
            return thing_trigger
        elif target_type == "Channel":
            return channel_trigger
        elif target_type == "System":
            return system_trigger
        elif target_type == "Time":
            return cron_trigger
        elif target_type in ["Directory", "Subdirectory"]:
            return directory_trigger

    except ValueError as ex:
        LOG.warn(ex)

        def bad_trigger(function):
            if not hasattr(function, 'triggers'):
                function.triggers = []
            function.triggers.append(None)
            return function

        # If there was a problem with a trigger configuration, then add None
        # to the triggers attribute of the callback function, so that
        # core.rules.rule can identify that there was a problem and not start
        # the rule
        return bad_trigger

    except:
        import traceback
        LOG.warn(traceback.format_exc())
Ejemplo n.º 11
0
from flask import Flask, g, request, request_started, request_finished
#from flask.ext.pymongo import PyMongo

from core.config import FullConfParser
from core import log
logger = log.getLogger("flaskserver")
from db.db_manager import db_sync_manager
from server.flask.views import ro_flask_views

from werkzeug import serving
from OpenSSL import crypto, SSL

import ast
import os
import sys


class ClientCertHTTPRequestHandler(serving.WSGIRequestHandler):
    """Overwrite the werkzeug handler, so we can extract the client cert and put it into the request's environment."""
    def make_environ(self):
        env = super(ClientCertHTTPRequestHandler, self).make_environ()
        if self._client_cert:
            env['CLIENT_RAW_CERT'] = self._client_cert
        return env

    def setup(self):
        super(ClientCertHTTPRequestHandler, self).setup()
        self.connection.do_handshake()
        peer_cert = self.connection.get_peer_certificate()
        if peer_cert:
            pem = crypto.dump_certificate(crypto.FILETYPE_PEM, peer_cert)
Ejemplo n.º 12
0
# -*- coding: utf-8 -*-
"""
    :author: ATao
    :tag: 思考是个好东西!
    :description: yaml测试文件的核心处理层
"""

from utils.operateYaml import readYaml
from core.log import getLogger

logger = getLogger()

class YamlCasesDriver:
    def __init__(self,configs):
        self.yaml_data = readYaml(configs.YAML_CASES_PATH)

    def get_cases_info(self):
        case_infos = []
        for i in self.yaml_data:
            case_infos.append(tuple(i.values()))
        logger.info("已从Yaml Case文件中获得了测试用例信息!")
        return case_infos








Ejemplo n.º 13
0
    from org.openhab.core.thing.link import ItemChannelLink
except:
    from org.eclipse.smarthome.core.thing.link import ItemChannelLink

ITEM_CHANNEL_LINK_REGISTRY = osgi.get_service(
    "org.openhab.core.thing.link.ItemChannelLinkRegistry") or osgi.get_service(
        "org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry"
    )  # type: ItemChannelLinkRegistry

MANAGED_ITEM_CHANNEL_LINK_PROVIDER = osgi.get_service(
    "org.openhab.core.thing.link.ManagedItemChannelLinkProvider"
) or osgi.get_service(
    "org.eclipse.smarthome.core.thing.link.ManagedItemChannelLinkProvider"
)  # type: ManagedItemChannelLinkProvider

LOG = getLogger(u"core.links")


def add_link(item_or_item_name, channel_uid_or_string):
    """
    This function adds a Link to an Item using a
    ManagedItemChannelLinkProvider.

    Args:
        item_or_item_name (Item or str): the Item object or name to create
            the Link for
        channel_uid_or_string (ChannelUID or str): the ChannelUID or string
            representation of a ChannelUID to link the Item to

    Returns:
        Item or None: the Item that the Link was added to or None
Ejemplo n.º 14
0
Provides utility functions for retrieving, registering and removing OSGi
services.
"""
__all__ = [
    'REGISTERED_SERVICES', 'get_service', 'find_services', 'register_service',
    'unregister_service'
]

from core.jsr223.scope import scriptExtension
from org.osgi.framework import FrameworkUtil
from core.log import getLogger

_BUNDLE = FrameworkUtil.getBundle(type(scriptExtension))
BUNDLE_CONTEXT = _BUNDLE.getBundleContext() if _BUNDLE else None
REGISTERED_SERVICES = {}
LOG = getLogger("core.osgi")


def get_service(class_or_name):
    """
    This function gets the specified OSGi service.

    Args:
        class_or_name (class or str): the class or class name of the service to
            get

    Returns:
        OSGi service or None: the requested OSGi service or None
    """
    if BUNDLE_CONTEXT:
        classname = class_or_name.getName() if isinstance(
Ejemplo n.º 15
0
def main():
    setup_path()

    # Parse command line arguments
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument(
        "--debug",
        help="Increase output verbosity",
        action="store_true")
    args_parser.add_argument("--tweak",
                             help="Set time and date to tweaked value")
    args_parser.add_argument("--chords",
                             help="Directory to look for scripts in")
    args_parser.add_argument( "--history",
                            help="List previous chord executions" )
    args = args_parser.parse_args()

    # Set up logging
    import core.log as log
    logging = log.getLogger(args.debug)
    logging.debug('Using Python %s', platform.python_version())

    # Load configuration
    from core.config import config as conf

    # Set up database
    db = setup_db()

    # Where are the chords kept?
    if args.chords:
        if os.path.isdir(args.chords):
            chordsDirectory = args.chords
    else:
        try:
            chordsDirectoryFromConf = conf.get('ocarina', 'chords')
            if os.path.isdir(chordsDirectoryFromConf):
                chordsDirectory = chordsDirectoryFromConf
        except:
            chordsDirectory = os.path.abspath(
                os.path.join(currentDirectory, '../chords'))
    sys.path.insert(0, chordsDirectory)

    # Where are the virtual environments kept?
    try:
        virtualEnvDirectoryFromConf = conf.get('ocarina', 'virtualenv')
        if os.path.isdir(virtualEnvDirectoryFromConf):
            virtualEnvDirectory = virtualEnvDirectoryFromConf
    except:
        virtualEnvDirectory = os.path.abspath(
            os.path.join(currentDirectory, '../.virtualenv'))

    shouldRunChords = not args.history

    if shouldRunChords:
        import core.chords as chords
        from core.now import Now
        now = Now(args.tweak)
        chords.run(chordsDirectory, virtualEnvDirectory, now, logging)

    if args.history:
        from core.history import History

        history = History( db )
        history.listPrevious( args.history )
Ejemplo n.º 16
0
import functools
import importlib
import pkgutil

from core.config import app_config
from core import log
from model import Object, File, Config, TextBlob

logger = log.getLogger()

_plugin_handlers = []


class PluginAppContext(object):
    def __init__(self, app, api, spec):
        self.app = app
        self.api = api
        self.spec = spec

    def register_hook_handler(self, hook_handler_cls):
        global _plugin_handlers
        _plugin_handlers.append(hook_handler_cls())

    def register_resource(self, resource, *urls, undocumented=False, **kwargs):
        self.api.add_resource(resource, *urls, **kwargs)
        if not undocumented:
            self.spec.path(resource=resource, api=self.api)

    def register_converter(self, converter_name, converter):
        self.app.url_map.converters[converter_name] = converter
Ejemplo n.º 17
0
    from org.openhab.core.thing import ChannelUID
except:
    from org.eclipse.smarthome.core.thing import ChannelUID

try:
    from org.joda.time import DateTime as JodaDateTime
except:
    JodaDateTime = None

from java.time import ZonedDateTime

from core.date import to_java_zoneddatetime, to_joda_datetime
from core.log import getLogger
from core.jsr223.scope import itemRegistry, StringType, NULL, UNDEF, ON, OFF, OPEN, CLOSED, events, things

LOG = getLogger(u"core.utils")


def validate_item(item_or_item_name):
    """
    This function validates whether an Item exists or if an Item name is valid.

    Args:
        item_or_item_name (Item or str): name of the Item

    Returns:
        Item or None: None, if the Item does not exist or the Item name is not
        in a valid format, else validated Item
    """
    item = item_or_item_name
    if isinstance(item, (basestring, unicode, StringType)):
Ejemplo n.º 18
0
from core.config import ConfParser
from handler.geni.v3.extensions.geni.util import cred_util
from handler.geni.v3 import exceptions
from handler.geni.v3 import extensions
from lxml import etree
from lxml.builder import ElementMaker

from core import log
logger = log.getLogger('geniv3delegatebase')

import ast
import os
import urllib2


class GENIv3DelegateBase(object):
    """
    Please find more information about the concept of Handlers and Delegates via the wiki (e.g. https://github.com/motine/AMsoil/wiki/GENI).
    
    The GENIv3 handler (see above) assumes that this class uses RSpec version 3 when interacting with the client.
    For creating new a new RSpec type/extension, please see the wiki via https://github.com/motine/AMsoil/wiki/RSpec.
    
    General parameters for all following methods:
    {client_cert} The client's certificate. See [flaskrpcs]XMLRPCDispatcher.requestCertificate(). Also see http://groups.geni.net/geni/wiki/GeniApiCertificates
    {credentials} The a list of credentials in the format specified at http://groups.geni.net/geni/wiki/GAPI_AM_API_V3/CommonConcepts#credentials

    Dates are converted to UTC and then made timezone-unaware (see http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone).
    """

    ALLOCATION_STATE_UNALLOCATED = 'geni_unallocated'
    """The sliver does not exist. (see http://groups.geni.net/geni/wiki/GAPI_AM_API_V3/CommonConcepts#SliverAllocationStates)"""
Ejemplo n.º 19
0
from flask import Flask, g, request, request_started, request_finished
from flask.ext.pymongo import PyMongo

from core.config import ConfParser
from core import log
logger=log.getLogger("flaskserver")
from server.flask.views import ro_flask_views

from werkzeug import serving
from OpenSSL import SSL, crypto

import ast
import os
import sys

class ClientCertHTTPRequestHandler(serving.WSGIRequestHandler):
    """Overwrite the werkzeug handler, so we can extract the client cert and put it into the request's environment."""
    def make_environ(self):
        env = super(ClientCertHTTPRequestHandler, self).make_environ()
        if self._client_cert:
            env['CLIENT_RAW_CERT'] = self._client_cert
        return env

    def setup(self):
        super(ClientCertHTTPRequestHandler, self).setup()
        self.connection.do_handshake()
        peer_cert = self.connection.get_peer_certificate()
        if peer_cert:
            pem = crypto.dump_certificate(crypto.FILETYPE_PEM, peer_cert)
            self._client_cert = pem
        else:
Ejemplo n.º 20
0
from core.config import FullConfParser
from handler.geni.v3 import exceptions
from lxml import etree
from lxml.builder import ElementMaker

from core import log
logger=log.getLogger('geniv3delegatebase')

import ast
import extensions
import os
import urllib2


class GENIv3DelegateBase(object):
    """
    Please find more information about the concept of Handlers and Delegates via the wiki (e.g. https://github.com/motine/AMsoil/wiki/GENI).

    The GENIv3 handler (see above) assumes that this class uses RSpec version 3 when interacting with the client.
    For creating new a new RSpec type/extension, please see the wiki via https://github.com/motine/AMsoil/wiki/RSpec.

    General parameters for all following methods:
    {client_cert} The client's certificate. See [flaskrpcs]XMLRPCDispatcher.requestCertificate(). Also see http://groups.geni.net/geni/wiki/GeniApiCertificates
    {credentials} The a list of credentials in the format specified at http://groups.geni.net/geni/wiki/GAPI_AM_API_V3/CommonConcepts#credentials

    Dates are converted to UTC and then made timezone-unaware (see http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone).
    """

    ALLOCATION_STATE_UNALLOCATED = 'geni_unallocated'
    """The sliver does not exist. (see http://groups.geni.net/geni/wiki/GAPI_AM_API_V3/CommonConcepts#SliverAllocationStates)"""
    ALLOCATION_STATE_ALLOCATED = 'geni_allocated'
Ejemplo n.º 21
0
    pass

from core import osgi
from core.log import getLogger

try:
    from org.openhab.core.items import Metadata, MetadataKey
except:
    from org.eclipse.smarthome.core.items import Metadata, MetadataKey

METADATA_REGISTRY = osgi.get_service(
    "org.openhab.core.items.MetadataRegistry") or osgi.get_service(
        "org.eclipse.smarthome.core.items.MetadataRegistry"
    )  # type: MetadataRegistry

LOG = getLogger(u"core.metadata")


def get_all_namespaces(item_name):
    # type: (str) -> t.List[String]
    """
    This function will return a list of an Item's namespaces.

    Examples:
        .. code-block::

            # Get a list of an Item's namespaces
            get_all_namespaces("Item_Name")

    Args:
        item_name (str): the name of the Item for which to retrieve the
Ejemplo n.º 22
0
from abc import ABCMeta, abstractmethod
from core import log
import threading
import time

logger = log.getLogger("service")


class Service(threading.Thread):
    __metaclass__ = ABCMeta

    @abstractmethod
    def do_action(self):
        """
        Implement this method that is called every step.
        """
        pass

    def __init__(self, name, interval):
        super(Service, self).__init__(name=name)
        self.__mutex = threading.Lock()
        self.__stop = threading.Event()
        # Interval/Frequency (in seconds)
        self.__interval = interval
        self.name = name
        self.daemon = True

    def __is_stopped(self):
        with self.__mutex:
            return self.__stop.isSet()
Ejemplo n.º 23
0
from core import log
from datetime import datetime
from dateutil import tz
import re

logger = log.getLogger("coreutils.dates")

# ---- Date utils ----

RFC3339_FORMAT_STRING = "%Y-%m-%d %H:%M:%S.%fZ"


def rfc3339_to_datetime(date):
    """
    Returns a datetime object from an input string formatted
    according to RFC3339.

    Ref: https://github.com/fp7-ofelia/ocf/blob/ofelia.development/core/
         lib/am/ambase/src/geni/v3/handler/handler.py#L321-L332
    """
    try:
        date_form = re.sub(r'[\+|\.].+', "", date)
        formatted_date = datetime.strptime(
            date_form.replace("T", " ").replace("Z", ""), "%Y-%m-%d %H:%M:%S")
    except:
        formatted_date = date
    return formatted_date


def datetime_to_rfc3339(date):
    """
Ejemplo n.º 24
0
import ast
import base64
import inspect
import traceback
import zlib

from handler.geni.v3 import exceptions as geni_ex

from core.config import ConfParser
from core import dates
from core import log
logger = log.getLogger("handlergeniv3")

from credentials.gcfmanager import GCFCredentialManager
from server.flask.flaskserver import FlaskServer
# Create and register the RPC server
flaskserver = FlaskServer()
from server.flask.flaskxmlrpc import FlaskXMLRPC
xmlrpc = FlaskXMLRPC(flaskserver)


class GENIv3Handler(xmlrpc.Dispatcher):

    def __init__(self):
        super(GENIv3Handler, self).__init__(logger)
        self._delegate = None
        self._verify_users =\
            ast.literal_eval(ConfParser("auth.conf").get("certificates").
                             get("verify_users"))
        self.__credential_manager = GCFCredentialManager()
Ejemplo n.º 25
0
from datetime import datetime
from dateutil import parser as dateparser
import base64
import zlib

# from lxml import etree
# from lxml.builder import ElementMaker

from handler.geni.v3 import exceptions as geni_ex
# import handler.geni.v3.extensions.geni
# import handler.geni.v3.extensions.sfa.trust.gid as gid
from delegate.geni.v3.db_manager_se import db_sync_manager

from core import dates
from core import log
logger = log.getLogger("handlergeniv3")
from core.utils import credentials as geni_creds

# import ast

from server.flask.flaskserver import FlaskServer
# Create and register the RPC server
flaskserver = FlaskServer()
from server.flask.flaskxmlrpc import FlaskXMLRPC
xmlrpc = FlaskXMLRPC(flaskserver)
#from SimpleXMLRPCServer import SimpleXMLRPCDispatcher as Dispatcher


class GENIv3Handler(xmlrpc.Dispatcher):
    RFC3339_FORMAT_STRING = "%Y-%m-%d %H:%M:%S.%fZ"
Ejemplo n.º 26
0
from core import log
from datetime import datetime
from dateutil import tz
import re

logger = log.getLogger("coreutils.dates")

# ---- Date utils ----

RFC3339_FORMAT_STRING = "%Y-%m-%d %H:%M:%S.%fZ"


def rfc3339_to_datetime(date):
    """
    Returns a datetime object from an input string formatted
    according to RFC3339.

    Ref: https://github.com/fp7-ofelia/ocf/blob/ofelia.development/core/
         lib/am/ambase/src/geni/v3/handler/handler.py#L321-L332
    """
    try:
        date_form = re.sub(r'[\+|\.].+', "", date)
        formatted_date = datetime.strptime(
            date_form.replace("T", " ").
            replace("Z", ""), "%Y-%m-%d %H:%M:%S")
    except:
        formatted_date = date
    return formatted_date


def datetime_to_rfc3339(date):
Ejemplo n.º 27
0
            # do something with event
"""
import uuid
import traceback

import java.util

from org.osgi.service.event import EventHandler, EventConstants#, EventAdmin

from core.jsr223.scope import scriptExtension
scriptExtension.importPreset("RuleSupport")
from core.jsr223.scope import Trigger, TriggerBuilder, Configuration
from core.osgi import BUNDLE_CONTEXT
from core.log import getLogger

LOG = getLogger(u"core.osgi.events")


def hashtable(*key_values):
    """
    Creates a Hashtable from 2-tuples of key/value pairs.

    Args:
        key_values (2-tuples): the key/value pairs to add to the Hashtable

    Returns:
        java.util.Hashtable: initialized Hashtable
    """
    _hashtable = java.util.Hashtable()
    for key, value in key_values:
        _hashtable.put(key, value)
Ejemplo n.º 28
0
from core.config import FullConfParser
from handler.geni.v3 import exceptions
from lxml import etree
from lxml.builder import ElementMaker

from core import log

logger = log.getLogger("geniv3delegatebase")

import ast
import extensions
import os
import urllib2


class GENIv3DelegateBase(object):
    """
    Please find more information about the concept of Handlers and Delegates
    via the wiki (e.g. https://github.com/motine/AMsoil/wiki/GENI).

    The GENIv3 handler (see above) assumes that this class uses RSpec version
    3 when interacting with the client.
    For creating new a new RSpec type/extension, please see the wiki via
    https://github.com/motine/AMsoil/wiki/RSpec.

    General parameters for all following methods:
    {client_cert} The client's certificate. See
        [flaskrpcs]XMLRPCDispatcher.requestCertificate().
        Also see http://groups.geni.net/geni/wiki/GeniApiCertificates
    {credentials} The a list of credentials in the format specified at http://
        groups.geni.net/geni/wiki/GAPI_AM_API_V3/CommonConcepts#credentials
Ejemplo n.º 29
0
import core
from core import osgi
from core.log import getLogger
from core.links import remove_all_links

ItemBuilderFactory = osgi.get_service(
    "org.openhab.core.items.ItemBuilderFactory") or osgi.get_service(
        "org.eclipse.smarthome.core.items.ItemBuilderFactory"
    )  # type: ohItemBuilderFactory

ManagedItemProvider = osgi.get_service(
    "org.openhab.core.items.ManagedItemProvider") or osgi.get_service(
        "org.eclipse.smarthome.core.items.ManagedItemProvider"
    )  # type: ohManagedItemProvider

log = getLogger("core.items")


def add_item(item_or_item_name,
             item_type=None,
             category=None,
             groups=None,
             label=None,
             tags=[],
             gi_base_type=None,
             group_function=None):
    """
    Adds an Item using a ManagedItemProvider.

    Args:
        item_or_item_name (Item or str): Item object or name for the Item to
Ejemplo n.º 30
0
"""
	author	: linkin
	date	: 2019.03.04
	email	: [email protected]

"""
import os
import w3lib.url
from PIL import Image
from config import WIDTH,HEIGHT
from settings import IMAGE_RATIO
from util.http import send_request
from decorator import force_type
from core.log import getLogger

logger = getLogger(__name__)

class BinaryImage:

	@force_type({1:str})
	def __init__(self,path_or_url):
		self.string = path_or_url

	def to_binary(self):
		if os.path.isfile(self.string):
			with open(self.string,'rb') as f:
				pic = f.read()
		elif w3lib.url.is_url(self.string):
				response = send_request(self.string)
				pic = response.content
		else:
Ejemplo n.º 31
0
import requests
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from flaskext.uploads import UploadSet, configure_uploads

from configs import config
from core.db.router import AutoRouteSQLAlchemy
from core.dapper.intercept import XB3HTTPAdapter
from core.log import getLogger
from redis import Redis

from core.hrms_redis.hrms_redis import RedisEntity

reload(sys)
sys.setdefaultencoding('utf8')
log = getLogger("hrms")


def create_app():
    flask_app = Flask(__name__,
                      template_folder=config.TEMPLATE_FOLDER,
                      static_folder=config.STATIC_FOLDER)
    flask_app.config.from_object(config)
    flask_app.template_folder = flask_app.config['TEMPLATE_FOLDER']
    flask_app.static_folder = flask_app.config['STATIC_FOLDER']
    log.info("create app done")

    return flask_app


def get_app_name():