Python Pyramid 简明教程

Python Pyramid - HTML Form Template

在本章中,我们将看到 Pyramid 如何从 HTML 表单读取数据。让我们将以下 HTML 脚本保存为 myform.html 。我们将使用它来获取 Template 对象并对其进行渲染。

In this chapter, we shall see how Pyramid reads the data from HTML form. Let us save the following HTML script as myform.html. We shall use it for obtaining Template object and render it.

<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 表单 −

An "index" route added in Pyramid object’s configuration is mapped to the following index() function, which renders the above HTML form −

@view_config(route_name='index', renderer='templates/myform.html')
def index(request):
   return {}

正如我们所看到的,用户输入的数据通过 POST 请求传递到 /students URL。因此,我们将添加一个 'students' 路由来匹配 /students 模式,并将其与 add() 视图函数关联,如下所示 −

As we can see, the data entered by user is passed to /students URL by POST request. So, we shall add a 'students' route to match the /students pattern, and associate it with add() view function as follows −

@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 请求发送的数据以 request.params 对象的形式在 HTTP 请求对象中可用。它是 HTML 表单属性及其由用户输入的值的字典。解析此数据并将其追加到词典对象的 students 列表中。更新后的 students 对象作为上下文数据传递给 marklist.html 模板。

The data sent by POST request is available in the HTTP request object in the form of request.params object. It is a dictionary of HTML form attributes and their values as entered by the user. This data is parsed and appended to students list of dictionary objects. The updated students object is passed to the marklist.html template as a context data.

marklist.html web 模板与前一个示例中使用的相同。它显示一个带有计算结果列的学生数据表。

The marklist.html web template as the same as used in the previous example. It displays a table of student data along with the computed result column.

<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>

Example

下面给出了用于渲染 HTML 表单、解析表单数据和生成显示学生成绩表表格的页面的完整代码,其中包含视图 −

The complete code containing views for rendering the HTML form, parsing the form data and generating a page showing the students marklist table is given below −

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()

Output

要启动服务器,请从命令行运行上述 Python 代码。在浏览器中,访问 http://localhost:6543/ 以获取如下所示的表单 −

To start the server, run the above Python code from command line. In your browser, visit http://localhost:6543/ to get the form as shown below −

student

输入示例数据,所示,然后按提交按钮。浏览器将被定向到 /students URL,它反过来调用 add() 视图。结果是显示新输入的学生新数据的成绩单表。

Enter a sample data as shown and press submit button. The browser is directed to /students URL, which in turn invokes the add() view. The result is a table of marklist showing the newly entered data of a new student.

students url