栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Flask框架初学-02

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Flask框架初学-02

一、路由规则

路由的请求和响应流程:

1、路由:
@app.route(‘/’)
def test():
PASS

2、路由的变量规则:
String (缺省值) 接受任何不包含斜杠的文本
int 接受正整数 *
float 接受正浮点数
path 类似 String,但可以包含斜杠
uuid 接受 UUID 字符串 uuid = uuid.uuid4()

example:

# key就是变量名,默认是字符串类型的
@app.route('/getcity/')
def get_city(key):
    print(type(key))
    return data.get(key)

# 带单参的路由
@app.route('/add/')
def add(num):
    result = num + 18
    return str(result)

# 带多参的路由
@app.route('/add//')
def add2(num1,num2):
    if num1>0 and num2>0:
        result = num1 + num2
        return str(result)
    return '输入的两个数必须大于0'

@app.route('/add1/')
def add1(money):
    return str(money)

@app.route('/index/')
def get_path(p):
    return p

@app.route('/test/')
def get_uid(uid):
    return ui

结果:

3、返回值:
类型:html、字符串,dict,tuple,response,WSGI

# 返回html
@app.route('/index1')
def index1():
    return '北京'

# 返回tuple
@app.route('/index2')  # 未成功
def index2():
    return ('beijing','shanghai','shenzhen')

# 返回response
@app.route('/index3')
def index3():
    return Response('大家想好中午吃什么了吗?')

# 返回字符串
@app.route('/index4')
def index4():
    print(request.headers)
    print(request.path)
    print(request.base_url)
    print(request.url)
    return 'welcome everyone!'

# 重定向跳转,返回模板界面
@app.route('/register2',methods=['GET','POST'])
def register2():
    username = request.form.get('username')
    password = request.form.get('password')
    repassword = request.form.get('repassword')
    if password == repassword and username != '':
        user = https://blog.csdn.net/weixin_42724501/article/details/{'username':username,'password':password}
        users.append(user)
        # 重定向到名为index的路径'/'
        return redirect(url_for('index'))
        # return 'register success !'
    # 返回模板界面
    return render_template('register2.html')


结果:

endpoint 与 url_for的结合使用:

# endpoint 为路径命名
@app.route('/',endpoint='index')
def hello_word():
    return render_template('index.html')

@app.route('/test')
def test():
    # 该url为:http://127.0.0.1:5000/ 
    url = url_for('index')
    print(url)

4、对象

request对象

request方法/属性作用
request.path获取当前请求路由
request.full_path获取当前请求的完整路径
request.form.get(‘’)获取post请求数据
request.args.get(‘’) —>get请求获取get请求数据
request.headers获取请求头部信息
request.base_url获取请求的

response对象

response方法/属性作用
response(‘字符串’,headers={key:value})
response = make_response(‘…’)
response.headers[‘aaa’] = ‘abc’修改响应结果头部字段aaa的值
response.content_type获取响应结果的内容类型
response.headers获取响应结果的头部信息
response.status_code获取响应结果的状态码
response.status获取响应结果的状态信息

视图函数的返回值:
response响应:
1、str 自动转化为response对象
2、dict json
3、response对象 response对象
4、make_response() response对象
5、redirect() 重定向—>302
6、render_template 模板渲染

二、模板

模板: (网页,即template下的html文件)
模板的语法:
1、在模板中获取view中传递的变量值:https://blog.csdn.net/weixin_42724501/article/details/{{ 变量名key }}

render_template(‘模板文件名’,keyvalue,keyvalue,…)

@app.route('/register')
def register():
    # 默认从templates文件夹里查询
    r = render_template('register2.html')
    print(r)
    return r

2、模板中接收值
接收列表值:
https://blog.csdn.net/weixin_42724501/article/details/{{ list.0 }} 或 https://blog.csdn.net/weixin_42724501/article/details/{{ list[0] }}
接收字典值:
https://blog.csdn.net/weixin_42724501/article/details/{{ dict.key }} 或 https://blog.csdn.net/weixin_42724501/article/details/{{ dict.get(key) }}
接收对象值:
https://blog.csdn.net/weixin_42724501/article/details/{{ girl.name }}
应用外部文件名:
url_for(‘static’,filename = ‘css/style.css’)
申明变量进行使用1:
{% set username = ‘zhangsan’ %}
https://blog.csdn.net/weixin_42724501/article/details/{{ username }}
申明变量进行使用2:
{% with num=1— %}
https://blog.csdn.net/weixin_42724501/article/details/{{ num }}
{% endwith %}

example:

app1.py

from flask import Flask,request,render_template

import settings

app = Flask(__name__)
app.config.from_object(settings)


class Girl:
    def __init__(self,name,addr):
        self.name = name
        self.gender = '女'
        self.addr = addr

@app.route('/show')
def show():
    name = 'haha'
    age = 18
    friends = ['haha', 'hehe', 'xixi', 'qiaqia']
    dicts = https://blog.csdn.net/weixin_42724501/article/details/{'gift1':'项链','gift2':'鲜花','gift3':'戒指'}
    # 创建对象
    girlfriend = Girl('翠花','江西')
    return render_template('show.html',name=name,age=age,friends=friends,dicts=dicts,girl=girlfriend)

if __name__ == '__main__':
    app.run()

show.html




    
    Title


用户信息展示

用户名是:https://blog.csdn.net/weixin_42724501/article/details/{{name}} ---- https://blog.csdn.net/weixin_42724501/article/details/{{age}} --- https://blog.csdn.net/weixin_42724501/article/details/{{gender}}
https://blog.csdn.net/weixin_42724501/article/details/{{friends[0]}} https://blog.csdn.net/weixin_42724501/article/details/{{friends.1}} https://blog.csdn.net/weixin_42724501/article/details/{{friends[2]}} https://blog.csdn.net/weixin_42724501/article/details/{{friends[3]}}
https://blog.csdn.net/weixin_42724501/article/details/{{dicts.gift1}} https://blog.csdn.net/weixin_42724501/article/details/{{dicts.get('gift2'}}
https://blog.csdn.net/weixin_42724501/article/details/{{girl.name}} --- https://blog.csdn.net/weixin_42724501/article/details/{{girl.gender}} --- https://blog.csdn.net/weixin_42724501/article/details/{{girl.age}}

{#动态创建#}

结果:

3、控制块


{% if 条件 %}
条件为True后执行的语句
{% else %}
条件为False后执行的语句
{% endif %}

{% for 变量 in 可迭代对象 %}
for要执行的语句
{% endfor %}

可以使用loop变量
loop.index 序号从1开始
loop.index0 序号从0开始
loop.revindex 序号倒转
loop.revindex0
loop.first 是否第一个 布尔类型
loop.last 是否最后一个 布尔类型

example:

app2.py

from flask import Flask,request,render_template

import settings

app = Flask(__name__)
app.config.from_object(settings)


@app.route('/show')
def show1():
    girls = ['孙艺珍','松韵','赵丽颖','杨紫','胡冰卿','孙雯']
    users = [
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha1', 'password': '123', 'addr': '浙江', 'phone': '10000000000'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha2', 'password': '124', 'addr': '浙江', 'phone': '10000000001'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha3', 'password': '125', 'addr': '上海', 'phone': '10000000002'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha4', 'password': '126', 'addr': '北京', 'phone': '10000000003'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha5', 'password': '127', 'addr': '江苏', 'phone': '10000000004'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha6', 'password': '128', 'addr': '江西', 'phone': '10000000005'},
    ]
    return render_template('show_controlblock.html',girls=girls,users=users)

if __name__ == '__main__':
    app.run()

show_controlblock.html




    
    演示控制块
    


{# ul...li #}
{# ol...li #}

{# https://blog.csdn.net/weixin_42724501/article/details/{{girls}} #}

    {% for girl in girls %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% endfor %}

    {% for girl in girls %} {% if girl|length >= 3 %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% else %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% endif %} {% endfor %}

{% for user in users %} {% endfor %}
https://blog.csdn.net/weixin_42724501/article/details/{{ user.username }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.password }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.addr }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.phone }}

{% for user in users %} {% endfor %}
https://blog.csdn.net/weixin_42724501/article/details/{{ loop.index0 }} https://blog.csdn.net/weixin_42724501/article/details/{{ loop.index }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.username }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.password }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.addr }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.phone }}

结果:

4、过滤器
过滤器的本质就是函数
模板语法中过滤器:
https://blog.csdn.net/weixin_42724501/article/details/{{ 变量名 | 过滤器 }}

https://blog.csdn.net/weixin_42724501/article/details/{{ 变量名 | 过滤器(*args) }}

常见的过滤器:
1、safe : 转义 保留样式,不使标签进行转义,让其依然可展示样式
2、capitalize : 单词首字母大写
3、lower/upper:单词大小写转换
4、title : 一句话中的每个单词的首字母大写
5、reverse : 单词字母倒拼
6、format : 格式转换
7、truncate : 返回一个截断的长度字串
8、列表中存在的过滤器:
https://blog.csdn.net/weixin_42724501/article/details/{{ girls | first }}
https://blog.csdn.net/weixin_42724501/article/details/{{ girls | last }}
https://blog.csdn.net/weixin_42724501/article/details/{{ girl | length }}
https://blog.csdn.net/weixin_42724501/article/details/{{ [1,3,5,7,9] | sum }}
https://blog.csdn.net/weixin_42724501/article/details/{{ [2,0,1,5.8,3] | sort }}
9、字典中存在的过滤器:
获取值:

 {% for v in users.0.values() %}
	 

https://blog.csdn.net/weixin_42724501/article/details/{{ v }}

{% endfor %}

获取键:

{% for v in users.0.keys() %}
     

https://blog.csdn.net/weixin_42724501/article/details/{{ v }}

{% endfor %}

获取键值对:

{% for k,v in users.0.items() %}
   

https://blog.csdn.net/weixin_42724501/article/details/{{ k }}---https://blog.csdn.net/weixin_42724501/article/details/{{ v }}

{% endfor %}

10、自定义过滤器
1、通过flask模块中的add_template_filter方法
def replace_hello(value):
print(‘---->’,value)
value = value.replace(‘hello’,‘’)
print(‘=======>’,value)
return value.strip()
app.add_template_filter(replace_hello,‘replace’)
2、使用装饰器完成
@app.template_filter(‘listreverse’)
def reverse_list(li):
temp_li = list(li)
temp_li.reverse()
return temp_li

example:

app3.py

from flask import Flask,request,render_template

import settings

# 包含过滤器、判断条件if、循环条件for

app = Flask(__name__)
app.config.from_object(settings)

@app.route('/show')
def show1():
    girls = ['孙艺珍','松韵','赵丽颖','杨紫','胡冰卿','孙雯']
    users = [
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha1', 'password': '123', 'addr': '浙江', 'phone': '10000000000'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha2', 'password': '124', 'addr': '浙江', 'phone': '10000000001'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha3', 'password': '125', 'addr': '上海', 'phone': '10000000002'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha4', 'password': '126', 'addr': '北京', 'phone': '10000000003'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha5', 'password': '127', 'addr': '江苏', 'phone': '10000000004'},
        https://blog.csdn.net/weixin_42724501/article/details/{'username': 'haha6', 'password': '128', 'addr': '江西', 'phone': '10000000005'},
    ]
    girls.append('zhangsan')
    msg = '520快乐!'
    n1 = 'hello'
    return render_template('show_controlblock.html',girls=girls,users=users,msg=msg,n1=n1)


@app.route('/')
def hello_word():
    msg = 'hello everyone hello world'
    li = [3,4,5]
    return render_template('define_filter.html',msg=msg,li=li)

# 第一种方式
# 过滤器本质就是函数
def  replace_hello(value):
    print('---->',value)
    value = value.replace('hello','')
    print('=======>',value)
    return value.strip()

app.add_template_filter(replace_hello,'replace')

# 第二种方式 装饰器
@app.template_filter('listreverse')
def reverse_list(li):
    temp_li = list(li)
    temp_li.reverse()
    return temp_li

if __name__ == '__main__':
    app.run()

show_controlblock.html




    
    演示控制块
    


{# ul...li #}
{# ol...li #}

{# https://blog.csdn.net/weixin_42724501/article/details/{{girls}} #}

    {% for girl in girls %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% endfor %}

    {% for girl in girls %} {% if girl|length >= 3 %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% else %}
  • https://blog.csdn.net/weixin_42724501/article/details/{{ girl }}
  • {% endif %} {% endfor %}

{% for user in users %} {% endfor %}
https://blog.csdn.net/weixin_42724501/article/details/{{ user.username }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.password }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.addr }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.phone }}

{% for user in users %} {% endfor %}
https://blog.csdn.net/weixin_42724501/article/details/{{ loop.index0 }} https://blog.csdn.net/weixin_42724501/article/details/{{ loop.index }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.username }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.password }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.addr }} https://blog.csdn.net/weixin_42724501/article/details/{{ user.phone }}

define_filter.html




    
    过滤器的使用


当前用户共:https://blog.csdn.net/weixin_42724501/article/details/{{ girls | length }} 人

{# 过滤器转义 #} https://blog.csdn.net/weixin_42724501/article/details/{{ len(girls) }}
https://blog.csdn.net/weixin_42724501/article/details/{{ msg | safe }}
https://blog.csdn.net/weixin_42724501/article/details/{{ n1 | capitalize }}
https://blog.csdn.net/weixin_42724501/article/details/{{ n1 | upper }}
https://blog.csdn.net/weixin_42724501/article/details/{{ n2 | lower }}
https://blog.csdn.net/weixin_42724501/article/details/{{ n1 | reverse }}
https://blog.csdn.net/weixin_42724501/article/details/{{ '%s id %d' | format('lili',18 }}
https://blog.csdn.net/weixin_42724501/article/details/{{ 'hello world' | truncate(7) }} {# 列表过滤器的使用 #} https://blog.csdn.net/weixin_42724501/article/details/{{ girls | first }}
https://blog.csdn.net/weixin_42724501/article/details/{{ girls | last }}
https://blog.csdn.net/weixin_42724501/article/details/{{ girl | length }}
https://blog.csdn.net/weixin_42724501/article/details/{{ [1,3,5,7,9] | sum }}
https://blog.csdn.net/weixin_42724501/article/details/{{ [2,0,1,5.8,3] | sort }}

https://blog.csdn.net/weixin_42724501/article/details/{{ users.0 }}
{% for v in users.0.values() %}

https://blog.csdn.net/weixin_42724501/article/details/{{ v }}

{% endfor %}
{% for k,v in users.0.items() %}

https://blog.csdn.net/weixin_42724501/article/details/{{ k }}---https://blog.csdn.net/weixin_42724501/article/details/{{ v }}

{% endfor %}

结果:

11、复用
模板继承:
需要模板继承的情况:
1、多个模板具有完全相同的顶部和底部
2、多个模板具有相同的模板内容,但是内容中部分不一样
3、多个模板具有完全相同的模板
标签:
{% block name %}
{% endblock %}
步骤:1、先在父模板中使用标签留出变化区(注意:样式和脚本需要提前预留)
{% block name %}
{% endblock %}
2、子模板继承父模板
{% extends ‘父模板名称’ %}
3、再在子模板中通过父模板中响应名称的变量名,进行填充
{% block name %}
变化内容
{% endblock %}

include:包含
使用场景:在A,B,C页面都有共同的部分,但是其他页面没有这部分
步骤:
1、先定义一个公共的模板部分:.html
2、*使用include导入进需要使用的文件(注意:文件夹必须是在template里面)
{% include '文件夹/.html’ %}

宏:macro
1、把它看作是jinja2的一个函数,这个函数可以返回一个HTML字符串
2、目的:代码可以复用,避免代码冗余
定义的两种方式:
1、在模板中直接定义:
类似:macro1.html 中定义方式
2、将所有宏提取到一个模板中:macro.html
使用时进行导入:
{% import ‘macro.html’ as 调用名 %}
https://blog.csdn.net/weixin_42724501/article/details/{{ 调用名.宏(参数值) }}

example:

app4.py

from flask import Flask,request,render_template

import settings

app = Flask(__name__)
app.config.from_object(settings)

@app.route('/base')
def load_inherit():
    return render_template('inherit.html')

@app.route('/')
def index():
    return render_template('inherit2.html')

@app.route('/welcome')
def welcome():
    return render_template('include.html')

@app.route('/macro')
def use_macro():
    return render_template('macro/macro1.html')

@app.route('/macro1')
def use_macro1():
    return render_template("macro/macro2.html")

if __name__ == '__main__':
    app.run()

inherit.html




    
    
      {% block title %}父模板的title{% endblock %}
    
    
    {% block mycss %}
    {% endblock %}


  
  
{% block middle %} {% endblock %}
{% block myjs %} {% endblock %}

inherit2.html

{% extends 'base.html' %}
{% block title %}
    首页
{% endblock %}
{% block mycss %}
    
    <# link rel="stylesheet" href="../static/css/style.css" #>
    
{% endblock %}
{% block myjs %}
    
{% endblock %}

{% block middle %}
    
{% endblock %}

header.html




    
    头部


include.html




    
    欢迎页面


{% include 'common/header.html' %}

macro/macro1.html




    
    


{# 定义宏 #}
{% macro form(action,value='登录',method='post') %}
  


{% endmacro %} {# 调用宏 #} https://blog.csdn.net/weixin_42724501/article/details/{{ form('/') }}

macro/macro.html

{# 定义宏 #}
{% macro form(action,value='登录',method='post') %}
  


{% endmacro %}

macro/macro2.html




    
    宏的使用2


{% import 'macro/macro.html' as f %}
https://blog.csdn.net/weixin_42724501/article/details/{{ f.form('welcome',value='注册')   }}

{# 申明变量进行使用 #}}
{% set username = 'zhangsan' %}
https://blog.csdn.net/weixin_42724501/article/details/{{ username }}

{% with num=1--- %}
    https://blog.csdn.net/weixin_42724501/article/details/{{ num }}
{% endwith %}



总结:
变量:https://blog.csdn.net/weixin_42724501/article/details/{{ name }}
块:
{% if 条件 %} …{% endif %}
{% for 条件 %} …{% endfor %}
{% block 条件 %} …{% endblock %}
{% macro 条件 %} …{% endmacro %}

{% include ‘’ %} 包含
{% import ‘’ %} 导入
{% extends ‘’ %} 继承

https://blog.csdn.net/weixin_42724501/article/details/{{ url_for(‘static’,filename=‘’) }}
https://blog.csdn.net/weixin_42724501/article/details/{{ 宏name(***) }}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号