Flask 静态文件
Web应用程序通常需要静态文件,例如javascript文件或支持网页显示的CSS文件。
通常,配置Web服务器并为您提供这些服务,但在开发过程中,这些文件是从您的包或模块旁边的static文件夹中提供,它将在应用程序的**/static**中提供。
特殊端点’static’用于生成静态文件的URL。
在下面的示例中,在index.html中的HTML按钮的OnClick事件上调用hello.js中定义的javascript函数,该函数在Flask应用程序的**“/”**URL上呈现。
示例
视图函数
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("staticIndex.html")
if __name__ == '__main__':
app.run(debug = True)
模板staticIndex.html
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("staticIndex.html")
if __name__ == '__main__':
app.run(debug = True)
static/htllo.js
function sayHello() {
alert("Welcome to Flask!")
}
效果
Flask Request对象
来自客户端网页的数据作为全局请求对象发送到服务器。为了处理请求数据,应该从Flask模块导入。
Request对象的重要属性如下所列:
属性 | 解释 |
---|---|
Form | 它是一个字典对象,包含表单参数及其值的键和值对。 |
args | 解析查询字符串的内容,它是问号(?)之后的URL的一部分,传输给视图函数的参数。 |
Cookies | 保存Cookie名称和值的字典对象。 |
files | 与上传文件有关的数据。 |
method | 当前请求方法,例如GET、POST。 |
Flask Request属性Form
我们已经看到,可以在 URL 规则中指定 http 方法。触发函数接收的 Form 数据可以以字典对象的形式收集它并将其转发到模板以在相应的网页上呈现它。
在以下示例中,‘/’ URL 会呈现具有表单的网页(student.html)。
填入的数据会发布到触发 result() 函数的 ‘/result’ URL。
result() 函数收集字典对象中的 request.form 中存在的表单数据,并将其发送给 result.html。
该模板动态呈现表单数据的 HTML 表格。
下面给出的是视图函数的 Python 代码:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('studentSubject.html')
@app.route('/result',methods = ['POST', 'GET'])
def result():
# 判断HTTP请求类型
if request.method == 'POST':
# 获取请求表单信息
result = request.form
# 将表单信息传递给表格HTML页
return render_template("studentSubjectTable.html",result = result)
if __name__ == '__main__':
app.run(debug = True)
创建模板studentSubject.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:5000/result" method="POST">
<p>姓名: <input type = "text" name = "Name" /></p>
<p>物理学: <input type = "text" name = "Physics" /></p>
<p>化学: <input type = "text" name = "chemistry" /></p>
<p>数学: <input type ="text" name = "Mathematics" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
创建模板studentSubjectTable.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>学习课程信息表</h1>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
测试结果
填写表单
返回表格
如果你希望访问源码:Flask-code gitee