当前位置:网站首页>[flask tutorial] flask development foundation and introduction
[flask tutorial] flask development foundation and introduction
2022-06-25 12:57:00 【Coconut brine Engineer】
One 、Flask Medium Hello World
from flask import Flask
app = Flask(__name__)
@app.route('/') // route
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Two 、Flask Routing and reverse routing
1) Custom routing
Import required request
Add route :
@app.route('/user')
def hello():
return 'Hello user'
Check out the browser :
Appoint HTTP Method :
@app.route('/login', methods=['GET', 'POST'])
def hello():
return 'Hello user'
Transfer of parameters on route :
@app.route('/user/<id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/user/query_user')
def hello_getid():
id=request.args.get('id')
return 'Hello user!'+id

2) Reverse routing
Backward derivation of route through view function .
Import required url_for
@app.route('/user/query_user')
def hello_getid():
id=request.args.get('id')
return 'Hello user!'+id
@app.route('/query_url')
def query_url():
return 'query url:'+url_for('hello_getid')

3、 ... and 、Flask Template
use Python Generate HTML Very boring , And it's pretty cumbersome , Because you have to do it manually HTML Do turn Meaning to ensure the security of the application . So ,Flask Equipped with a Jinja2 template engine .
You can use render_template() Method to render the template . One thing you need to do Cutting is to pass the template name and the parameters you want as keywords into the variables of the template .
1) Basic example
mian.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run()
Flask Will be in templates Looking for templates in the folder . therefore , If your application is a module , this A folder should be at the same level as the module ; If it's a bag , So this folder is a subdirectory of the package :
/templates/index.html
<!doctype html>
<title>Hello from Flask</title>
{
% if name %}
<h1>Hello {
{
name }}!</h1>
{
% else %}
<h1>Hello World hhh!</h1>
{
% endif %}
The directory structure is as follows :
2) Transfer the required data to the template
app.py
@app.route('/')
def hello_world():
content = " Pass you something "
return render_template("index.html",content=content)
/templates/index.html
<!doctype html>
<title>Hello from Flask</title>
{
% if name %}
<h1>Hello {
{
name }}!</h1>
{
% else %}
<h1>{
{
content}}</h1>
{
% endif %}

3) Pass more complex data to the template :user class
models.py
class User(object):
def __init__(self,user_id,user_name):
self.user_id=user_id
self.user_name=user_name
templates/user_index.html
<!doctype html>
<title>Hello from Flask</title>
{
% if name %}
<h1>hello {
{
user.user_name }}!</h1>
{
% else %}
<h1>hello {
{
user.user_id}}</h1>
{
% endif %}
main.py
from flask import Flask,request,url_for,render_template
from models import User
app = Flask(__name__)
@app.route('/')
def hello_world():
content = " Pass you something "
return render_template("index.html", content=content)
@app.route('/user')
def user_index():
user = User(1,'hhhh')
return render_template("user_index.html",user=user)
if __name__ == '__main__':
app.run()
It is shown in the figure below :
4) Conditional template rendering
main.py
@app.route('/query_user/<user_id>')
def query_user(user_id):
user = None
if int(user_id)==1:
user =User(1,'hhhhh')
return render_template("user_id.html",user=user)
user_id.html
<!doctype html>
<title>Hello from Flask</title>
{
% if user %}
<h1>hello {
{
user.user_name }}!</h1>
{
% else %}
<h1>no this user</h1>
{
% endif %}
It is shown in the figure below :

Four 、Flask Message prompt and exception reminder
Flask Provide message flash mechanism in , You can simply give feedback to users . The message flashing system usually records information at the end of the request , And in the next ( And only in the next ) request Access recorded information in . The presentation of these messages is usually combined with a template layout .
Use flash() Method can flash a message . To manipulate the message itself , Please use get_flashed_messages() function , And it can also be used in templates .
1) Message tip
main.py
from flask import Flask,request,url_for,render_template, flash
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_world():
flash("hello")
return render_template("index.html")
if __name__ == '__main__':
app.run()
index.html
<!doctype html>
<title>Hello from Flask</title>
<h1>Hello !</h1>
<h2>{
{
get_flashed_messages()[0]}}</h2>
2) for instance : Login message prompt
index.html
<!doctype html>
<title>Hello from Flask</title>
<h1>Hello !</h1>
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
<h2>{
{
get_flashed_messages()[0]}}</h2>
mian.py
def login():
form = request.form
username = form.get('username')
password = form.get('password')
if not username:
flash(' Please enter a user name ')
return render_template("index.html")
if not password:
flash(' Please input a password ')
return render_template('index.html')
if username == 'admin' and password== 'admin':
flash(' Landing successful ')
return render_template('index.html')
else:
flash(' Wrong user name or password ')
return render_template('index.html')
The operation results are as follows :
3) exception handling
mian.py
@app.errorhandler(404)
def not_found(e):
return render_template('404.html')
404.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>404</title>
</head>
<body>
<h1> The page you're looking for doesn't exist </h1>
</body>
</html>
The operation results are as follows :
边栏推荐
- GNSS receiver technology and application review
- nacos无法修改配置文件Mysql8.0的解决方法
- Koa frame
- 地理空间搜索:kd树的实现原理
- Jupyter notebook theme font setting and automatic code completion
- My first experience of go+ language -- a collection of notes on learning go+ design architecture
- 德国举行全球粮食安全团结会议
- JS array de duplication
- Foreach method of array in JS
- Command line garbled
猜你喜欢
随机推荐
英语口语 - 弱读
Baidu search stability analysis story
GNSS receiver technology and application review
Module 5 (microblog comments)
买基金在哪里开户安全?还请赐教
Resolved: could not find artifact XXX
字节跳动Dev Better技术沙龙来啦!参与活动赢好礼,限时免费报名中!
Matlab simulation of m-sequence
torch.tensor拼接与list(tensors)
Optimal solution for cold start
利用cmd(命令提示符)安装mysql&&配置环境
yolov5训练使用的负样本图片
How to implement a high-performance load balancing architecture?
2021-10-21
Differences between JS and JQ operation objects
Slice() and slice() methods of arrays in JS
Visual studio2019 link opencv
flutter 收到推送后自动消失问题
Koa 框架
STM32 在flash中存储float数据





![[转]以终为始,详细分析高考志愿该怎么填](/img/77/715454c8203d722e246ed70e1fe0d8.png)

