当前位置:网站首页>[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 :
边栏推荐
- torch. Tensor splicing and list (tensors)
- 几分钟上线一个网站 真是神器
- (7) Pyqt5 tutorial -- > > window properties and basic controls (continuous update)
- nacos无法修改配置文件Mysql8.0的解决方法
- Using CMD (command prompt) to install MySQL & configure the environment
- 顺序表的折半查找法
- MySQL adds, modifies, and deletes table fields, field data types, and lengths (with various actual case statements)
- Jupyter notebook theme font setting and automatic code completion
- Differences between JS and JQ operation objects
- 1251- Client does not support authentication protocol MySql错误解决方案
猜你喜欢

架构师必备的七种能力

Summer Ending

利用cmd(命令提示符)安装mysql&&配置环境

Update PIP & Download jupyter Lab

3+1保障:高可用系统稳定性是如何炼成的?

2021-09-02

It is extraordinary to make a move, which is very Oracle!

Capabilities required by architects

AI assisted paper drawing of PPT drawing

MySQL writes user-defined functions and stored procedure syntax (a detailed case is attached, and the problem has been solved: errors are reported when running user-defined functions, and errors are r
随机推荐
[AI helps scientific research] fool drawing of loss curve
leetcode - 384. 打乱数组
Idea2017 how to set not to automatically open a project at startup
Elemntui's select+tree implements the search function
LeetCode链表题解技巧归纳总结
Write regular isosceles triangle and inverse isosceles triangle with for loop in JS
Common colors for drawing
STM32 stores float data in flash
Circular exercises of JS
Common software numerical filtering methods (I) have been applied
为何数据库也云原生了?
Optimal solution for cold start
更新pip&下载jupyter lab
QT TCP UDP network communication < theory >
Slice() and slice() methods of arrays in JS
Possible problems when idea encounters errors occurred while compiling module (solved)
地理空间搜索:kd树的实现原理
Geospatial search: implementation principle of KD tree
Negative sample image used in yolov5 training
Summer Ending