6 flask之必會四板斧
阿新 • • 發佈:2022-03-22
# response物件
-直接返回字串----》django的HTTPResponse
-render_template--->django的render---》返回模板
-redirect---->django的redirect---》返回重定向
-jsonfy--->django的JsonResponse---》返回json格式字串
1 ''
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'hello world' if __name__ == '__main__': app.run()
2 render_template
main.py
# -*- coding: utf-8 -*-
# @Time : 2021/12/5 15:57
# @Author : dzg
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/login')
def login():
return render_template('login.html')
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>使用者登入</h1> <form method="post"> <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit" value="登入"> </form> </body> </html>
1. 向html傳值:一個
1. 向html傳值:多個
或者:
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
{{a1}}
{{a2}}
{{a3}}
</body>
</html>
3 redirect
# -*- coding: utf-8 -*- # @Time : 2021/12/5 15:57 # @Author : dzg from flask import Flask, render_template,redirect app = Flask(__name__) @app.route('/redirect') def re_direct(): return redirect('https://www.baidu.com') if __name__ == '__main__': app.run()
4 jsonify
# -*- coding: utf-8 -*- # @Time : 2021/12/5 15:57 # @Author : dzg from flask import Flask, render_template, redirect, jsonify app = Flask(__name__) @app.route('/json') def my_json(): user_dict = { 'name': 'dzg', 'age': 18 } return jsonify(user_dict) if __name__ == '__main__': app.run()