没有在html文件中获得所需的输出

时间:2012-06-23 11:38:20

标签: python web.py

我正在尝试制作分支预测器:

这是我在app.py中的代码:

import web
urls = (
'/hello','index'
)

app = web.application(urls,globals())

render = web.template.render('templates/', base='layout')

class index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
        form=web.input(name='nobody', rank=0)
        branch=None
        if form.rank<=4613:
            branch = 'COE, ECE,IT,ICE,MPAE,BT'
        if int(form.rank)<=7471 & int(form.rank)>4613:
            branch='ECE,IT,ICE,MPAE,BT'
        if int(form.rank)<=11325 & int(form.rank)>7471:
            branch = 'IT,ICE,MPAE,BT'
        if int(form.rank)<=16565 & int(form.rank)>11325:
            branch='ICE,MPAE,BT'
        if int(form.rank)<=17955 & int(form.rank)>16565:
            branch='MPAE,BT'
        if int(form.rank)<=20714 & int(form.rank)<17955:
            branch='BT'
        return render.index(branch=branch) 

if __name__=='__main__':
    app.run()

这是我的html文件hello_form.html

中的代码
<h1>NSIt Branch Predictor for First Round</h1>
<form action='hello' method ='POST'>
Your Name: <input type = 'text' name = 'name'>
<br>
AIEEE Rank: <input type = 'text' name ='rank'>
<input type='submit'>

这是我在index.html中的代码:

$def with (branch)
branch: $branch

我的layout.html如下:

$def with (content)
<html>
<head>
<title> first python website</title>
</head>
<body>
$:content
</body>
</html>

但在输出中我得到了:

branch:

1 个答案:

答案 0 :(得分:2)

我从未使用过您正在使用的应用程序框架,但您的POST方法存在许多问题。这应该是它应该是什么样子。然后我将谈论问题和一些替代解决方案。

def POST(self):
    form = web.input(name='nobody', rank='0')
    rank = int(form.rank)
    if rank <= 4613:
        branch = 'COE, ECE,IT,ICE,MPAE,BT'
    elif rank <= 7471:
        branch = 'ECE,IT,ICE,MPAE,BT'
    elif rank <= 11325:
        branch = 'IT,ICE,MPAE,BT'
    elif rank <= 16565:
        branch = 'ICE,MPAE,BT'
    elif rank <= 17955:
        branch = 'MPAE,BT'
    elif rank <= 20714:
        branch = 'BT'
    else:
        branch = None
    return render.index(branch=branch) 

第一个问题是你的第一个比较是在字符串和整数之间:if form.rank<=4613。应该是if int(form.rank)<=4613。比较字符串和数字很少能达到预期效果。

>>> rank = '4613'
>>> rank <= 4613
False
>>> rank > sys.maxint
True

接下来,您使用的是bitwise and operator &而不是boolean and operator。例如,int(form.rank)<=7471 & int(form.rank)>4613应为int(form.rank)<=7471 and int(form.rank)>4613

您可以使用operator chaining代替and内容来改善这一点:

if rank <= 4613:
    branch = 'COE, ECE,IT,ICE,MPAE,BT'
if 4613 < rank <= 7471:
    branch = 'ECE,IT,ICE,MPAE,BT'
if 7471 < rank <= 11325:
    branch = 'IT,ICE,MPAE,BT'

最终,您拥有的内容最好表示为ifelif语句链,除非您想使用某种基于区间的数据结构。对于这么简单的事情,if语句可以正常工作。

快乐的拼贴!