Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 173.9MB ·虚拟内存 1439.3MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
我们通常会在一个 HTML 文件嵌入表单,通过 Post 方法,将表单数据提交给后端服务程序。
在下面的示例中,我们将表单发送到 Bottle 应用。
$ mkdir simple_form && cd simple_form $ mkdir public $ touch public/index.html simple_form.py
我们为应用创建目录和文件。
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home page</title>
</head>
<body>
<form method="post" action="doform">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="occupation">Occupation:</label>
<input type="text" id="occupation" name="occupation">
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
在 HTML 文件中,我们有一个表单标签。 该表格包含两个输入字段:名称和职业。
simple_form.py
#!/usr/bin/env python3
from bottle import route, run, post, request, static_file
@route('/')
def server_static(filepath="index.html"):
return static_file(filepath, root='./public/')
@post('/doform')
def process():
name = request.forms.get('name')
occupation = request.forms.get('occupation')
return "Your name is {0} and you are a(n) {1}".format(name, occupation)
run(host='localhost', reloader=True, port=8080, debug=True)
在simple_form.py文件中,我们提供一个表格并处理该表格。
@route('/')
def server_static(filepath="index.html"):
return static_file(filepath, root='./public/')
对于根路径(/),我们从public目录提供index.html。
@post('/doform')
def process():
name = request.forms.get('name')
occupation = request.forms.get('occupation')
return "Your name is {0} and you are a(n) {1}".format(name, occupation)
在这里,我们处理表格。 我们使用@post装饰器。 我们从request.forms获取数据并构建消息字符串。
使用 static_file(),我们可以在 Bottle 中提供静态文件。$ mkdir botstat && cd botstat$ mkdir public $ touch public/h ...