在本章中,我們將看到Pyramid如何從HTML表單中讀取數據。讓我們把下面的HTML腳本保存為 myform.html。 我們將用它來獲取模板對象并渲染它。
<html>
<body>
<form method="POST" action="http://localhost:6543/students">
<p>Student Id: <input type="text" name="id"/> </p>
<p>student Name: <input type="text" name="name"/> </p>
<p>Percentage: <input type="text" name="percent"/> </p>
<p><input type="submit" value="Submit"> </p>
</body>
</html>
在Pyramid對象的配置中添加的“index”路由會映射到下面的index()函數,它會渲染上面的HTML表單 ?
@view_config(route_name='index', renderer='templates/myform.html')
def index(request):
return {}
我們可以看到,用戶輸入的數據是通過POST請求傳遞給/students URL的。因此,我們將添加一個’students’路由來匹配/students模式,并將其與add()視圖函數關聯(lián),如下所示
@view_config(route_name='students', renderer='templates/marklist.html')
def add(request):
student={'id':request.params['id'],
'name':request.params['name'],
'percent':int(request.params['percent'])} 9. Pyramid – HTML Form Template
students.append(student)
return {'students':students}
由POST請求發(fā)送的數據在HTTP請求對象中以 request.params 對象的形式提供。它是一個由用戶輸入的HTML表單屬性及其值組成的字典。這些數據被解析并追加到字典對象的學生列表中。更新后的學生對象作為上下文數據被傳遞給marklist.html模板。
marklist.html 網頁模板與前面的例子中使用的相同。它顯示了一個學生數據的表格,以及計算結果列。
<html>
<body>
<table border=1>
<thead>
<tr>
<th>Student ID</th> <th>Student Name</th>
<th>percentage</th>
<th>Result</th>
</tr>
</thead>
<tbody>
{% for Student in students %}
<tr>
<td>{{ Student.id }}</td>
<td>{{ Student.name }}</td>
<td>{{ Student.percent }}</td>
<td>
{% if Student.percent>=50 %}
Pass
{% else %}
Fail
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
例子
下面給出了完整的代碼,其中包含渲染HTML表單、解析表單數據和生成顯示學生標記表的頁面的視圖。
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config
students = [
{"id": 1, "name": "Ravi", "percent": 75},
{"id": 2, "name": "Mona", "percent": 80},
{"id": 3, "name": "Mathews", "percent": 45},
]
@view_config(route_name='index', renderer='templates/myform.html')
def index(request):
return {}
@view_config(route_name='students', renderer='templates/marklist.html')
def add(request):
student={'id':request.params['id'], 'name':request.params['name'],
'percent':int(request.params['percent'])}
students.append(student)
return {'students':students}
if __name__ == '__main__':
with Configurator() as config:
config.include('pyramid_jinja2')
config.add_jinja2_renderer(".html")
config.add_route('index', '/')
config.add_route('students','/students')
config.scan()
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
輸出
要啟動服務器,從命令行運行上述Python代碼。在你的瀏覽器中,訪問 http://localhost:6543/, 得到如下所示的表格—-。
輸入如圖所示的樣本數據并按下提交按鈕。瀏覽器被引導到/students URL,這又調用了 add() 視圖。結果是一個標記表,顯示了新輸入的新學生的數據。
更多建議: