hello world
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<h1>哈哈</h1>"
# 括号中的参数使得同一网络下的所有设备都可以访问该服务器(不过我试了下似乎没有效果)
app.run(host="0.0.0.0")
实现传参:
# 参数默认为string类型
@app.route("/<name>")
def hello_world(name):
return f"<h1>你好{name}</h1> "
# 转换器可以实现int类型传参(在尖括号中标记)
@app.route("/<int:name>")
def hello_world(name):
return f"<h1>你好{name}</h1> "
转换器类型:
| 类型 | 描述 |
|---|---|
| string | (省缺)接收任何不包含斜杠的文本 |
| int | 接受正整数 |
| float | 接受浮点数 |
| path | 类似string,但可以包含斜杠 |
| uuid | 接受UUID字符串 |
重定向
@app.route("/bilibili")
def bilibili():
return redirect("https://www.bilibili.com/")
接受POST请求
@app.route("/test", methods=["POST"])
def first_post():
my_json = request.get_json() # 浏览器请求携带的json数据
print(my_json)
return "good" # 给浏览器返回的响应
检测POST请求参数是否正确
@app.route("/test", methods=["POST"])
def first_post():
try
my_json = request.get_json() # 浏览器请求携带的json数据
print(my_json)
get_name = my_json.get("name")
get_age = my_json.get("age")
if not all([get_name, get_age]):
return jsonify(msg="缺少参数")
return "good" # 给浏览器返回的响应
except Exception as e:
print(e)
return jsonify(msg="出错了,请查看是否正确访问")