python列表神秘地设置在我的django /活塞处理程序中的东西

时间:2010-03-31 15:14:56

标签: python django django-piston

注意:(自从前两个建议后我已经更新了......你可以在这里以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 / url。

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

我正在将调试信息添加到我的回复中,以便我可以看到正在发生的事情。现在,当您第一次询问示例1的url时,您将获得此CORRECT statusmsg响应:

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

当您询问示例2的url时,您会收到此CORRECT 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),

HANDLERS.PY

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)

2 个答案:

答案 0 :(得分:0)

我会说代码中存在一个基本缺陷,如果has_limit()可以返回True,当limit是长度为2的列表时,如果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])

答案 1 :(得分:0)

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

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

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