gpt4 book ai didi

python 列表神秘地设置为我的 django/活塞处理程序中的某些内容

转载 作者:行者123 更新时间:2023-11-28 19:28:23 25 4
gpt4 key购买 nike

注意:(我已经根据前两个建议更新了这篇文章...您可以在此处查看 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 给我第一个 hours_detail 行来自员工#22

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

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

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

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

当您询问示例 2 的 url 时,您会收到此正确的状态消息响应:

"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),}",

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

"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 条不同状态消息(请注意,从每条消息中,kwarg 的调试输出中正确地缺少 'limit':'first',而 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),

处理程序.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)

最佳答案

我会说你的代码有一个基本的缺陷,如果 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])

关于python 列表神秘地设置为我的 django/活塞处理程序中的某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2554127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com