如何将优先级队列添加到Flask API?

时间:2019-02-11 14:07:42

标签: python-2.7

我有一个flask api和优先级队列文件,如何将两者集成在一起?

我的api将服务大约4个应用程序,我决定使用优先级队列对任务进行排队以提高性能。所以我有api和优先级队列代码,但是如何集成两者呢?我是这个新手。

import heapq
import itertools

class PriorityQueue(object):

_REMOVED = "<REMOVED>"


def __init__(self):
    #initialize a list
    self.heap = []
    self.entries = {}
    self.counter = itertools.count()


def add (self, task, priority=0):
    if task in self.entries:
        self.remove(task)

    count = next(self.counter)
    # weight = -priority since heap is a min-heap
    entry = [-priority, count, task]
    self.entries[task] = entry
    heapq.heappush(self.heap, entry)
    pass




def remove(self, task):
    """ Mark the given task as REMOVED.

    Do this to avoid breaking heap-invariance of the internal heap.
    """
    entry = self.entries[task]
    entry[-1] = PriorityQueue._REMOVED
    pass

def pop(self):
    """ Get task with highest priority.

    :return: Priority, Task with highest priority
    """
    while self.heap:
        weight, count, task = heapq.heappop(self.heap)
        if task is not PriorityQueue._REMOVED:
            del self.entries[task]
            return -weight, task
    raise KeyError("The priority queue is empty")

def peek(self):
    """ Check task with highest priority, without removing.

    :return: Priority, Task with highest priority
    """
    while self.heap:
        weight, count, task = self.heap[0]
        if task is PriorityQueue._REMOVED:
            heapq.heappop(self.heap)
        else:
            return -weight, task

    return None

def __str__(self):
    temp = [str(e) for e in self.heap if e[-1] is not PriorityQueue._REMOVED]
    return "[%s]" % ", ".join(temp)

我想将优先级队列集成到我的API中。

0 个答案:

没有答案