用于过滤Python中对象的用户界面

时间:2018-09-30 03:42:55

标签: python api design-patterns

在我的应用程序中,我有一个Job类,如下所示/概述。此作业类的实例代表特定的作业运行。作业可以有多个检查点,每个检查点可以有多个命令。

Job
 - JobName
 - [JobCheckpoint]
 - StartTime
 - EndTime
 - Status
 - ...

JobCheckpoint
 - JobCheckpointName
 - [JobCommand]
 - StartTime
 - EndTime
 - Status
 - ...

JobCommand
 - JobCommandName
 - [Command]
 - StartTime
 - EndTime
 - Status 
 - ...

在任何一天,大约有10万个不同的作业在运行。作业信息保留在文件系统中。我想在Python中设计一个用于查询这些作业对象的用户界面。例如,用户应该能够查询

  1. 在x和y间隔之间运行的所有作业。
  2. 所有运行命令x的作业。
  3. 所有作业均处于失败状态。
  4. 所有作业处于失败和终止状态。
  5. 特定作业的所有检查点/命令。
  6. 还有更多...

为解决这个问题,我正在考虑在用户界面中提供以下方法。

 get_jobs(Filter)

我不确定如何在Python中设计此Filter类

  1. 支持对Job对象的所有此类查询。
  2. 并保持用户对API的使用简单/直观。

这里的铅非常感谢。

1 个答案:

答案 0 :(得分:3)

这些是部分主观的问题。但是,我将尽我所能,并根据所提出的问题中的可用信息回答其中的一些问题。

Filter类的外观如何?

例如,这可能取决于存储机制。它是作为一堆Python对象存储在内存中,还是首先从SQL数据库或NoSQL数据库中取出。

如果它是从SQL数据库中获取的,则可以利用SQL的过滤机制。毕竟是一种(结构化的)查询语言。

在这种情况下,您的Filter类就像是将字段值转换为一堆SQL运算符/条件的转换器。

如果它是一堆没有某种数据库机制可用于查询数据的Python对象,那么您可能需要考虑自己的查询/过滤器方法。

Filter类可能正在使用Condition类和Operator类。也许您有一个Operator类作为抽象类,并且有“胶合”操作符将条件粘合在一起(AND / OR)。还有另一种用于将域对象的属性与值进行比较的运算符。

对于后者,即使您没有为其设计“过滤器语言”,也可以从此处为Flask-Restless指定的API查询格式中获得启发:https://flask-restless.readthedocs.io/en/stable/searchformat.html#query-format

当然,如果您要设计一个查询界面,例如Flask-Restless的REST API作为一种REST API,可以为您提供有关如何解决查询的灵感。

返回的域对象列表正确还是应该返回字典列表?

返回域对象列表的优点是能够使用继承。那至少是一种可能的优势。

某些课程的简要草图:

from abc import ABCMeta, abstractmethod
from typing import List

class DomainObjectOperatorGlue(metaclass=ABCMeta):    
    @abstractmethod
    def operate(self, haystack: List['DomainObject'], criteria: 
        List['DomainObject']) -> List['DomainObject']:
        pass

class DomainObjectFieldGlueOperator(metaclass=ABCMeta):
    @abstractmethod
    def operate(self, conditions: List[bool]) -> bool:
        pass

class DomainObjectFieldGlueOperatorAnd(DomainObjectFieldGlueOperator):
    def operate(self, conditions: List[bool]) -> bool:
        # If all conditions are True then return True here,
        # otherwise return False.
        # (...)
        pass

class DomainObjectFieldGlueOperatorOr(DomainObjectFieldGlueOperator):
    def operate(self, conditions: List[bool]) -> bool:
        # If only one (or more) of the conditions are True then return True
        # otherwise, if none are True, return False.
        # (...)
        pass


class DomainObjectOperatorAnd(DomainObjectOperatorGlue):
    def __init__(self):
        pass

    def operate(self, haystack: 'JobsCollection', criteria: 
List['DomainObject']) -> List['DomainObject']:
        """
        Returns list of haystackelements or empty list.
        Includes haystackelement if all (search) 'criteria' elements 
(DomainObjects) are met for haystackelement (DomainObject).
        """
        result = []
        for haystackelement in haystack.jobs:
            # AND operator wants all criteria to be True for haystackelement (Job)
        # to be included in returned search results.
        criteria_all_true_for_haystackelement = True
        for criterium in criteria:
            if haystackelement.excludes(criterium):
                criteria_all_true_for_haystackelement = False
                break
        if criteria_all_true_for_haystackelement:
            result.append(haystackelement)
    return result

class DomainObjectOperatorOr(DomainObjectOperatorGlue):
    def __init__(self):
        pass

def operate(self, haystack: List['DomainObject'], criteria: List['DomainObject']) -> List['DomainObject']:
    """
    Returns list of haystackelements or empty list.
    Includes haystackelement if all (search) 'criteria' elements (DomainObjects) are met for haystackelement (DomainObject).
    """
    result = []
    for haystackelement in haystack:
        # OR operator wants at least ONE criterium to be True for haystackelement
        # to be included in returned search results.
        at_least_one_criterium_true_for_haystackelement = False
        for criterium in criteria:
            if haystackelement.matches(criterium):
                at_least_one_criterium_true_for_haystackelement = True
                break
        if at_least_one_criterium_true_for_haystackelement:
            result.append(haystackelement)
    return result

class DomainObjectFilter(metaclass=ABCMeta):
    def __init__(self, criteria: List['DomainObject'], criteria_glue: 
DomainObjectOperatorGlue):
        self.criteria = criteria
        self.criteria_glue = criteria_glue

    @abstractmethod
    def apply(self, haystack: 'JobsCollection') -> List['DomainObject']:
        """
       Applies filter to given 'haystack' (list of jobs with sub-objects in there);
    returns filtered list of DomainObjects or empty list if none found
    according to criteria (and criteria glue).
        """
        return self.criteria_glue.operate(haystack, self.criteria)

class DomainObject(metaclass=ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def matches(self, domain_object: 'DomainObject') -> bool:
        """ Returns True if this DomainObject matches specified DomainObject,
    False otherwise.
     """
    pass

def excludes(self, domain_object: 'DomainObject') -> bool:
    """
    Convenience method; the inverse of includes-method.
    """
    return not self.matches(domain_object)


class Job(DomainObject):
    def __init__(self, name, start, end, status, job_checkpoints: 
List['JobCheckpoint']):
        self.name = name
        self.start = start
        self.end = end
        self.status = status
        self.job_checkpoints = job_checkpoints

    def matches(self, domain_object: 'DomainObject', field_glue: 
DomainObjectFieldGlueOperator) -> bool:
        """
        Returns True if this DomainObject includes specified DomainObject,
     False otherwise.
         """
        if domain_object is Job:
            # See if specified fields in search criteria (domain_object/Job) matches this job.
            # Determine here which fields user did not leave empty,
            # and guess for sensible search criteria.
            # Return True if it's  a match, False otherwise.
            condition_results = []
            if domain_object.name != None:
                condition_results.append(domain_object.name in self.name)
            if domain_object.start != None or domain_object.end != None:
                if domain_object.start == None:
                    # ...Use broadest start time for criteria here...
                    # time_range_condition = ...
                    condition_results.append(time_range_condition)                 
                elif domain_object.end == None:
                    # ...Use broadest end time for criteria here...
                    # time_range_condition = ...
                    condition_results.append(time_range_condition)                 
                else:
                    # Both start and end time specified; use specified time range.
                # time_range_condition = ...
                condition_results.append(time_range_condition)
            # Then evaluate condition_results;
            # e.g. return True if all condition_results are True here,
            # false otherwise depending on implementation of field_glue class:
            return field_glue.operate(condition_results)
    elif domain_object is JobCheckpoint:
        # Determine here which fields user did not leave empty,
        # and guess for sensible search criteria.
        # Return True if it's  a match, False otherwise.
        # First establish if parent of JobCheckpoint is 'self' (this job)
        # if so, then check if search criteria for JobCheckpoint match,
        # glue fields with something like:
        return field_glue.operate(condition_results)
    elif domain_object is JobCommand:
        # (...)
        if domain_object.parent_job == self:
            # see if conditions pan out
            return field_glue.operate(condition_results)

class JobCheckpoint(DomainObject):
    def __init__(self, name, start, end, status, job_commands: List['JobCommand'], parent_job: Job):
       self.name = name
        self.start = start
        self.end = end
        self.status = status
       self.job_commands = job_commands
        # For easier reference;
        # e.g. when search criteria matches this JobCheckpoint
        # then Job associated to it can be found
        # more easily.
        self.parent_job = parent_job

class JobCommand(DomainObject):
    def __init__(self, name, start, end, status, parent_checkpoint: JobCheckpoint, parent_job: Job):
        self.name = name
        self.start = start
        self.end = end
        self.status = status
        # For easier reference;
        # e.g. when search criteria matches this JobCommand
        # then Job or JobCheckpoint associated to it can be found
        # more easily.
        self.parent_checkpoint = parent_checkpoint
        self.parent_job = parent_job

class JobsCollection(DomainObject):
    def __init__(self, jobs: List['Job']):
         self.jobs = jobs

    def get_jobs(self, filter: DomainObjectFilter) -> List[Job]:
        return filter.apply(self)

    def get_commands(self, job: Job) -> List[JobCommand]:
        """
        Returns all commands for specified job (search criteria).
        """
        result = []
        for some_job in self.jobs:
            if job.matches(some_job):
                for job_checkpoint in job.job_checkpoints:
                    result.extend(job_checkpoint.job_commands)
         return result

    def get_checkpoints(self, job: Job) -> List[JobCheckpoint]:
        """
        Returns all checkpoints for specified job (search criteria).
        """
        result = []
        for some_job in self.jobs:
            if job.matches(some_job):
                result.extend(job.job_checkpoints)
        return result