【脚本语言系列】关于PythonWeb服务器Flask,你需要知道的事
如何使用Flask
简单网页
保存demo1.html位于脚本所处的目录下
<!--demo1.html-->
<html>
<head>
<title>Flask Demo1</title>
</head>
<body>
Hello My Friend: {{name}}
</body>
</html>
# -*- coding:utf-8 -*-
from flask import Flask
app = Flask(__name__,static_folder=".", static_url_path="")
@app.route("/")
def home():
return app.send_static_file("demo1.html")
@app.route("/echo/<name>")
def echo(name):
return "Hello MyFriend: %s" %name
app.run(port=9999, debug=True)
# http://127.0.0.1:9999/echo/AllenMoore
* Restarting with stat
* Debugger is active!
* Debugger PIN: 602-361-623
* Running on http://127.0.0.1:9999/ (Press CTRL+C to quit)
模板运用
保存demo1.html位于脚本所处的目录下的templates文件夹中
<!--demo1.html-->
<html>
<head>
<title>Flask Demo1</title>
</head>
<body>
Hello My Friend: {{name}}
</body>
</html>
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/echo/<name>")
def echo(name):
return render_template("demo1.html",name=name)
app.run(port=9999, debug=True)
# http://127.0.0.1:9999/echo/AllenMoore
* Restarting with stat
* Debugger is active!
* Debugger PIN: 602-361-623
* Running on http://127.0.0.1:9999/ (Press CTRL+C to quit)
- URL的扩展作传参
保存demo2.html位于脚本所处的目录下的templates文件夹中
<!--demo2.html-->
<html>
<head>
<title>Flask Demo2</title>
</head>
<body>
Hello My Friend: {{name}}
Welcome To This Place: {{place}}
</body>
</html>
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/echo/<name>/<place>")
def echo(name, place):
return render_template("demo2.html", name=name, place=place)
app.run(port=9999, debug=True)
# http://127.0.0.1:9999/echo/AllenMoore/TheMachine
* Restarting with stat
* Debugger is active!
* Debugger PIN: 602-361-623
* Running on http://127.0.0.1:9999/ (Press CTRL+C to quit)
GET参数作传参
URL的扩展作传参
保存demo3.html位于脚本所处的目录下的templates文件夹中
<!--demo2.html-->
<html>
<head>
<title>Flask Demo2</title>
</head>
<body>
Hello My Friend: {{name}}
Welcome To This Place: {{place}}
</body>
</html>
# -*- coding:utf-8 -*-
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/echo/")
def echo():
kwargs={}
kwargs["name"] = request.args.get("name")
kwargs["place"] = request.args.get("place")
return render_template("demo3.html", **kwargs)
app.run(port=9999, debug=True)
# http://127.0.0.1:9999/echo/?name=AllenMoore&place=TheMachine
* Restarting with stat
* Debugger is active!
* Debugger PIN: 602-361-623
* Running on http://127.0.0.1:9999/ (Press CTRL+C to quit)
什么是Flask
Flask是Web服务器框架,定位于入门级。
为何使用Flask
Flask如同Bottle一样简单,而且还能扩展许多扩展功能,比如认证服务。