0

这行代码:

contract = Contract.get_by_id(contract_id)

从这个块:

class MainHandler(webapp2.RequestHandler):
    def get(self):     
        contract_id = self.request.get("contract_id")
        if contract_id is None:
            contract = db.GqlQuery("SELECT * FROM Contract ORDER BY date DESC").get()
            if contract == None:
                numBook = 1
                numInitialPage = 1
                numFinalPage = 1            
        else:
            contract = Contract.get_by_id(contract_id)

template_values = {"numBook":numBook,
                           "numInitialPage":numInitialPage,
                           "numFinalPage":numFinalPage}
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))

正在产生此错误:

     File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "C:\Users\Py\Desktop\contract\main.py", line 277, in get
        contract_id = self.request.get("contract_id")
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1292, in get_by_id
    ids, multiple = datastore.NormalizeAndTypeCheck(ids, (int, long))
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\datastore.py", line 139, in NormalizeAndTypeCheck
    (types, arg, typename(arg)))
BadArgumentError: Expected an instance or iterable of (<type 'int'>, <type 'long'>); received  (a str).

我的目标是:如果在其他处理程序重定向到 MainHandler 时通过变量传递了一个值contract_id,则 MainHandler 应该使用它。但是如果 MainHandler 是第一次使用,那么contract_idvalue 应该是None并且程序应该是另一件事。但这并没有发生。调用 MainHandler 时,它将“contract_id”(来自self.request.get("contract_id"))解释为字符串值。如何解决这个问题并实现我的目标?

4

1 回答 1

2

错误告诉您的是它需要一个int或一个int. 这与docs一致。因此,您需要先转换 contract_idint.

...
else:
  contract = Contract.get_by_id(int(contract_id))

此外,您需要更改检查是否contract_id通过的方式。self.request.get当值未定义时,该方法返回一个空字符串。请参阅http://webapp-improved.appspot.com/api/webapp2.html#webapp2.Request.get

所以你必须在这里选择替代品:

contract_id = self.request.get("contract_id")
if not contract_id:

或者

contract_id = self.request.get("contract_id", None)
if contract_id is None:
于 2012-08-09T16:51:01.520 回答