我收到一个回溯错误,指出我有一个TYPEERROR
...当我创建一个video
的实例时,我的数据库测试工作正常,所以我知道这不是问题。我已经在here,here和在线调查了可能的问题,但我没有找到任何合适的内容。
自创建Web框架以来,在尝试通过HTML表单创建视频时,我现在得到以下回溯:
File "/usr/local/lib/python2.7/site-packages/notssdb/model/base.py", line 122, in __repr__
return "<Video(videoname='%s', length='%d', url='%s')>" % (self.videoname, self.length, self.url)
TypeError: %d format: a number is required, not unicode
这是我认为导致此问题的网络代码: 视图设置:
def get_video(self):
video_id = int(self.request.matchdict['id'])
video = self.API.retrieve_video(video_id)
return {'videoname': video.videoname, 'length': video.length, 'url': video.url}
@view_config(request_method='POST')
def post_video(self):
videoname = self.request.params['videoname']
length = self.request.params['length']
url = self.request.params['url']
video = self.API.create_video(videoname, length, url)
return HTTPAccepted(location=request.route_url('/videos/{id}'))
html(通过Pyramid框架的JINJA模板):
<form method="POST" action="/videos">
<dl>
<dt><label for = 'videoname'> Video Name </label></dt>
<dd>{{ forms.input('videoname') }}</dd>
<dt><label for = 'length'> Duration </label></dt>
<dd>{{ forms.input('int(length)') }}</dd> # < --- works
<dt><label for = 'url'> Video URL </label></dt>
<dd>{{ forms.input('url') }}</dd>
<dd><input type="submit" name="submit" value="Submit" /></dd>
</dl>
</form>
在上面添加了int()属性(参见<dd>{{ forms.input('int(length)') }}</dd> # < --- works
),但现在得到了这个TRACEBACK:
line 93, in post_video
length = self.request.params['length']
File "build/bdist.macosx-10.10-x86_64/egg/webob/multidict.py", line 342, in __getitem__
raise KeyError(key)
KeyError: 'length'
视频模型--SQLALCHEMY:
class Video(Base):
__tablename__ = 'videos'
#code
length = Column(Integer)
url = Column(String(300))
def __init__(self, videoname, length, url):
self.videoname = videoname
self.length = length
self.url = url
def __repr__(self):
return "<Video(videoname='%s', length='%s', url='%s')>" % (self.videoname, self.length, self.url)
答案 0 :(得分:0)
标题问题解决方案:
你用“%d”指定你希望self.length是一个数字,但此时它是unicode。
将self.length转换为类似此float(self.length)的数字,使用“%s”代替“%d”,这非常健壮或使用格式而不是%< / em>(see why)。
>>> length = "23.12"
>>> "{}".format(length)
"23.12"