3

注意:(自从前两个建议以来我已经更新了这个......您可以在此处以 txt 形式查看旧帖子:http: //bennyland.com/old-2554127.txt)。我所做的更新是为了更好地了解出了什么问题——现在我至少知道发生了什么,但我不知道如何解决它。

无论如何,使用 Django 和 Piston,我建立了一个名为 BaseApiHandler 的新 BaseHandler 类,它完成了我在所有处理程序中所做的大部分工作。在我添加了限制应用于我的结果的过滤器的功能之前,这非常有效(例如,“只给我第一个结果”)。

示例(必须删除“:”,因为我无法提交更多网址): - http//localhost/api/hours_detail/empid/22给了我来自员工 #22 的所有 hours_detail 行 - http//localhost/api/hours_detail/ empid/22/limit/first给了我来自员工 #22 的第一个 hours_detail 行

发生的事情是,当我连续运行 /limit/first 几次时,第一个示例随后被破坏,假装它是 /limit/ url,而实际上它不是。

现在我正在存储它是否是一个限制以及一个新类中的限制是什么 - 在这个 stackoverflow 编辑之前,我只是使用一个包含两个条目的列表(limit = [] 初始化时,limit = [0, 1] 设置时)。在此 stackoverflow 编辑之前,一旦您向 /limit/first 发送垃圾邮件,当转到第一个示例时,“limit”将被预设为 [0,1],然后处理程序将因此限制查询。使用我添加的调试数据,我可以肯定地说该列表是预先设置的,并且在代码执行期间没有设置。

我正在将调试信息添加到我的响应中,这样我就可以看到发生了什么。现在,当您第一次询问示例 1 的 url 时,您会得到以下正确的 statusmsg 响应:

"statusmsg": "2 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',}",

当您询问示例 2 的 url 时,您会得到以下正确的 statusmsg 响应:

"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 1 times),}",

但是,如果您刷新很多次,限制设置值开始增加(增加这个值是我的一个朋友建议的,看看这个变量是否以某种方式被保留)

"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 10 times),}",

一旦该数字超过“1 次”,您就可以开始尝试获取示例 1 的网址。每次我现在刷新示例 1 时,我都会得到奇怪的结果。以下是来自不同刷新的 3 条不同状态消息(请注意,从每条消息中,'limit':'first' 在 kwarg 的调试输出中正确缺失,而 islimit 的实际值在 8 到 10 之间徘徊):

"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 10 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 8 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 9 times),}",

所以看起来这个对象正在被缓存。在将“限制”从列表更改为类之前,似乎“限制”的列表版本被缓存,因为在转到示例 2 的 url 之后,我有时会将 [0,1] 作为限制。

以下是更新后的代码片段(请记住,您可以在此处查看第一篇文章:bennyland.com/old-2554127.txt

URLS.PY - 在 'urlpatterns = patterns('

    #hours_detail/id/{id}/empid/{empid}/projid/{projid}/datestamp/{datestamp}/daterange/{fromdate}to{todate}
    #empid is required
    url(r'^api/hours_detail/(?:' + \
        r'(?:[/]?id/(?P<id>\d+))?' + \
        r'(?:[/]?empid/(?P<empid>\d+))?' + \
        r'(?:[/]?projid/(?P<projid>\d+))?' + \
        r'(?:[/]?datestamp/(?P<datestamp>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,}))?' + \
        r'(?:[/]?daterange/(?P<daterange>(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})))?' + \
        r')+' + \
        r'(?:/limit/(?P<limit>(?:first|last)))?' + \
        r'(?:/(?P<exact>exact))?$', hours_detail_resource),

处理程序

class ResponseLimit(object):
    def __init__(self):
        self._min = 0
        self._max = 0
        self._islimit = 0

    @property
    def min(self):
        if self.islimit == 0:
            raise LookupError("trying to access min when no limit has been set")
        return self._min

    @property
    def max(self):
        if self.islimit == 0:
            raise LookupError("trying to access max when no limit has been set")
        return self._max

    @property
    def islimit(self):
        return self._islimit

    def setlimit(self, min, max):
        self._min = min
        self._max = max
        # incrementing _islimit instead of using a bool so I can try and see why it's broken
        self._islimit += 1

class BaseApiHandler(BaseHandler):
    limit = ResponseLimit()
    def __init__(self):
        self._post_name = 'base'

    @property
    def post_name(self):
        return self._post_name

    @post_name.setter
    def post_name(self, value):
        self._post_name = value

    def process_kwarg_read(self, key, value, d_post, b_exact):
        """
        this should be overridden in the derived classes to process kwargs
        """
        pass

    # override 'read' so we can better handle our api's searching capabilities
    def read(self, request, *args, **kwargs):
        d_post = {'status':0,'statusmsg':'Nothing Happened'}
        try:
            # setup the named response object
            # select all employees then filter - querysets are lazy in django
            # the actual query is only done once data is needed, so this may
            # seem like some memory hog slow beast, but it's actually not.
            d_post[self.post_name] = self.queryset(request)
            s_query = ''

            b_exact = False
            if 'exact' in kwargs and kwargs['exact'] <> None:
                b_exact = True
                s_query = '\'exact\':True,'

            for key,value in kwargs.iteritems():
                # the regex url possibilities will push None into the kwargs dictionary
                # if not specified, so just continue looping through if that's the case
                if value is None or key == 'exact':
                    continue

                # write to the s_query string so we have a nice error message
                s_query = '%s\'%s\':\'%s\',' % (s_query, key, value)

                # now process this key/value kwarg
                self.process_kwarg_read(key=key, value=value, d_post=d_post, b_exact=b_exact)

            # end of the kwargs for loop
            else:
                if self.limit.islimit > 0:
                    s_query = '%swith limit[%s,%s](limit,%s... limit set %s times),' % (s_query, self.limit.min, self.limit.max, kwargs['limit'],self.limit.islimit)
                    d_post[self.post_name] = d_post[self.post_name][self.limit.min:self.limit.max]
                if d_post[self.post_name].count() == 0:
                    d_post['status'] = 0
                    d_post['statusmsg'] = '%s not found with query: {%s}' % (self.post_name, s_query)
                else:
                    d_post['status'] = 1
                    d_post['statusmsg'] = '%s %s found with query: {%s}' % (d_post[self.post_name].count(), self.post_name, s_query)
        except:
            e = sys.exc_info()[1]
            d_post['status'] = 0
            d_post['statusmsg'] = 'error: %s %s' % (e, traceback.format_exc())
            d_post[self.post_name] = []

        return d_post


class HoursDetailHandler(BaseApiHandler):
    #allowed_methods = ('GET', 'PUT', 'POST', 'DELETE',)
    model = HoursDetail
    exclude = ()

    def __init__(self):
        BaseApiHandler.__init__(self)
        self._post_name = 'hours_detail'

    def process_kwarg_read(self, key, value, d_post, b_exact):
        # each query is handled slightly differently... when keys are added
        # handle them in here.  python doesn't have switch statements, this
        # could theoretically be performed using a dictionary with lambda
        # expressions, however I was affraid it would mess with the way the
        # filters on the queryset work so I went for the less exciting
        # if/elif block instead

        # querying on a specific row
        if key == 'id':
            d_post[self.post_name] = d_post[self.post_name].filter(pk=value)

        # filter based on employee id - this is guaranteed to happen once
        # per query (see read(...))
        elif key == 'empid':
            d_post[self.post_name] = d_post[self.post_name].filter(emp__id__exact=value)

        # look for a specific project by id
        elif key == 'projid':
            d_post[self.post_name] = d_post[self.post_name].filter(proj__id__exact=value)

        elif key == 'datestamp' or key == 'daterange':
            d_from = None
            d_to = None
            # first, regex out the times in the case of range vs stamp
            if key == 'daterange':
                m = re.match('(?P<daterangefrom>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?P<daterangeto>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})', \
                             value)
                d_from = datetime.strptime(m.group('daterangefrom'), '%Y-%m-%d')
                d_to = datetime.strptime(m.group('daterangeto'), '%Y-%m-%d')
            else:
                d_from = datetime.strptime(value, '%Y-%m-%d')
                d_to = datetime.strptime(value, '%Y-%m-%d')

            # now min/max to get midnight on day1 through just before midnight on day2
            # note: this is a hack because as of the writing of this app,
            # __date doesn't yet exist as a queryable field thus any
            # timestamps not at midnight were incorrectly left out
            d_from = datetime.combine(d_from, time.min)
            d_to = datetime.combine(d_to, time.max)

            d_post[self.post_name] = d_post[self.post_name].filter(clock_time__gte=d_from)
            d_post[self.post_name] = d_post[self.post_name].filter(clock_time__lte=d_to)

        elif key == 'limit':
            order_by = 'clock_time'
            if value == 'last':
                order_by = '-clock_time'
            d_post[self.post_name] = d_post[self.post_name].order_by(order_by)
            self.limit.setlimit(0, 1)

        else:
            raise NameError

    def read(self, request, *args, **kwargs):
        # empid is required, so make sure it exists before running BaseApiHandler's read method
        if not('empid' in kwargs and kwargs['empid'] <> None and kwargs['empid'] >= 0):
            return {'status':0,'statusmsg':'empid cannot be empty'}
        else:
            return BaseApiHandler.read(self, request, *args, **kwargs)
4

2 回答 2

0

我会说您的代码中有一个基本缺陷,如果has_limit()在 limit 是长度为 2 的列表时可以返回 True ,但是如果 limit 短于 3 个元素长度,则此行将失败:

s_query = '%swith limit[%s,%s](limit,%s > traceback:%s),' % 
          (s_query, self.limit[0], self.limit[1], kwargs['limit'], 
           self.limit[2])

为什么要将 self.limit 初始化为无效的长度列表?您还可以使这段代码更具防御性:

if self.has_limit():
    s_query += 'with limit[%s,%s]' % self.limit[0:1]
    if 'limit' in kwargs and len(self.limit) > 2:
        s_query += '(limit,%s > traceback:%s),' % 
              (kwargs['limit'], self.limit[2])
于 2010-03-31T17:05:36.750 回答
0

我认为您可能正在通过get_limit属性访问器为您的内部限制列表创建别名。尝试在此访问器中删除(或至少添加一个打印语句)。如果您有将本地列表绑定到 get_limit 的外部代码,那么它可以使用 append、del 或对切片的赋值来更新内容,例如 [:]。或者试试这个:

def get_limit(self): 
    return self._limit[:]

它不会将您的内部列表绑定到外部名称,而是复制您的内部列表。

于 2010-03-31T20:42:12.520 回答