# -*- coding: utf-8 -*-
from flask import Flask,render_template,request,redirect,session,url_for
import time app = Flask(__name__,template_folder="templates")
app.secret_key = "A" #类似于加密盐
app.config["SERVER_NAME"] = "jianping.com"
import functools
def auth(func): @functools.wraps(func) #解决函数名重复的冲突问题
def inner(*args,**kwargs):
if not session.get("user_info"):
return redirect("/login")
return func(*args,**kwargs)
print(inner.__name__)
return inner @app.route("/index",)
@auth # index = auth(index)=inner
def index():
return render_template("index.html") @app.route("/text")
@auth
def text():
return render_template("index.html") @app.route("/login",methods=["POST","GET"])
def hello_world():
if request.method == "GET":
return render_template("login.html")
else:
username = request.form.get("username")
password = request.form.get("password")
if username == "张建平" and password == "":
session["user_info"] = "QQ"
return redirect("/index")
return render_template("login.html",msg="用户名密码错误") @app.route("/one",subdomain="zhang")
def one(): return "草拟大爷" @app.route("/two",subdomain="cheng")
def two():
return "草拟妹" if __name__ == '__main__':
app.run()
flask_one
# -*- coding: utf-8 -*-
from flask import Flask,url_for,views app = Flask(__name__) def auth(func):
def inner(*args,**kwargs):
result = func(*args,**kwargs)
print("============会执行")
return result
return inner #函数方法
# @app.route("/index/<int:nid>",endpoint="xx") def index(nid):
# url_for("xx",nid=123)
print(nid)
return "Index" app.add_url_rule("/index/<int:nid>",view_func=index,defaults={"nid":444},strict_slashes=False) #加上默认值不管前端传什么值都默认用后端的,虽然用后端的 #类方法
# class IndexView(views.MethodView):
# decorators = [auth,]
# def get(self):
# v = url_for("index")
# print(v)
# return "GET————————"
# def post(self):
# return "GET=============="
#
# app.add_url_rule("/index",view_func=IndexView.as_view(name="index")) if __name__ == '__main__':
app.run()
视图
# -*- coding: utf-8 -*-
from flask import Flask,url_for,request,redirect,render_template,jsonify,make_response
from urllib.parse import urlencode,quote,unquote app = Flask(__name__) @app.route("/index",endpoint="xx")
def index():
get_data = request.args #get_data:ImmutableMultiDict
get_dict = get_data.to_dict() #将上边的结果转换为字典
get_dict["xx"] = "" #给字典设置值
url = urlencode(get_dict) #浏览器url?后边的地址 print(request.query_string) #上边的url,不过是byte类型的
val = "%E8%8D%89%E6%8B%9F%E5%A4%A7%E7%88%B7" #url中的中文显示
print(unquote(val)) #将上边的火星文转换为中文
res = "好好学习天天向上"
print(quote(res)) #将中文转换为火星文 ret = {"name":"alex"}
print(type(jsonify(ret))) #<class 'flask.wrappers.Response'>
# return jsonify(ret) #返回的结果是json字符串
response = make_response("<h1>xxxxx</h1>") #经过make_response处理之后可以有一些功能
# response.headers["xxx"] = "ooo"
# print(response)
return response if __name__ == '__main__':
app.run()
请求响应
# -*- coding: utf-8 -*-
from flask import Flask,url_for,request,redirect,render_template,jsonify,make_response,Markup
from urllib.parse import urlencode,quote,unquote
app = Flask(__name__) def text(a1,a2):
return a1+a2 @app.template_global() #设置了全局变量及时不用传也可以共享
def sb(a1,a2):
return a1+a2+100 @app.template_filter()
def db(a1,a2,a3):
return a1+a2+a3 @app.route("/index",endpoint="xx")
def index():
v1 = "字符串"
v2 = [11,22,33]
v3 = {"k1":"v1","k2":"v2"}
v4 = Markup("<input type='text' />")
v5 = "<input type='text' />" #浏览器显示字符串
return render_template("index.html",v1=v1,v2=v2,v3=v3,v4=v4,v5=v5,text=text) if __name__ == '__main__':
app.run()
模板语言
# -*- coding: utf-8 -*- from flask import Flask,session,Session
from urllib.parse import urlencode,quote,unquote
from werkzeug.local import LocalProxy app = Flask(__name__)
app.secret_key = "HQ"
app.config["SESSION_COOKIE_NAME"] = "session_key"
"""
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31)
""" @app.route("/index",endpoint="xx")
def index():
session['xxx'] = 123
session['xxx1'] = 123
return "xxx" if __name__ == '__main__':
app.run()
session
# -*- coding: utf-8 -*- from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request
app = Flask(__name__)
app.secret_key = "HQ" #一个视图函数设置,另一个视图函数取值 @app.route("/users")
def index():
# msg = request.args.get("msg","") msg = session.get("msg")
print(msg)
if msg:
del session["msg"]
v = get_flashed_messages()
print(v)
msg = ""
return render_template("flash.html",msg=msg) @app.route("/useradd")
def index_add():
session["msg"] = "添加成功======="
flash("添加成功")
return redirect("/users") if __name__ == '__main__':
app.run()
闪现
# -*- coding: utf-8 -*- from flask import Flask
app = Flask(__name__)
app.secret_key = "HQ" #类似于中间件的操作 @app.before_request
def process_request1():
print("process_request1===================1") @app.after_request
def process_response1(response):
print("process_response1==================1")
return response @app.before_request
def process_request2():
print("process_request2====================2") @app.after_request
def process_response2(response):
print("process_response2===================2")
return response @app.route("/index")
def index():
print("index")
return "INDEX" @app.route("/order")
def order():
print("order")
return "ORDER" @app.route("/text")
def text():
print("text")
return "TExT" if __name__ == '__main__':
app.run()
扩展
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1>{{msg}}</h1> <h1>welcome to my index</h1> <hr>
v1:{{v1}}
v2:{{v2}}
v3:{{v3}}
v4:{{v4}}
v5:{{v5}}
text{{text(1,2)}}
<br>
<hr>
<!--可循环-->
{% for item in v2 %}
v2:{{item}}
{% endfor %}
<hr>
<!--字典可循环-->
{% for k,v in v3.items() %}
{{k}},{{v}}
{% endfor %}
<br>
{{v3.k1}}
{{v3.get("k1")}} <hr> {{sb(1,2)}} <br>
{{1|db(2,3)}}
<hr> <!--类似于for循环-->
{% macro xxxx(name,type='text',value='') %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}" >
<input type="{{ type }}" name="{{ name }}" value="{{ value }}" >
<input type="{{ type }}" name="{{ name }}" value="{{ value }}" >
{% endmacro %} {{ xxxx("zhang")}} <hr> <img src="/static/school.png" alt=""> </body>
</html>
index.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="username">
<input type="text" name="password">
<input type="submit">
{{msg}}
</form>
</body>
</html>
login.html
测试页面
# -*- coding: utf-8 -*-
from flask import Flask,url_for
app = Flask(__name__) from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter):
"""
自定义URL匹配正则表达式
""" def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex def to_python(self, value):
"""
路由匹配时,匹配成功后传递给视图函数中参数的值
:param value:
:return:
"""
return int(value) def to_url(self, value):
"""
使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
:param value:
:return:
"""
val = super(RegexConverter, self).to_url(value)
return val app.url_map.converters["xxx"] = RegexConverter @app.route("/index/<xxx('\d+'):nid>",endpoint="xx")
def index(nid):
url_for("xx",nid=123)
return "Index" if __name__ == '__main__':
app.run()
正则表达式
前端参数传递:
{#前端url传参 {{ url_for('index',qq=7) }}#}
闪现是基于session实现的,先设置,然后删除,闪现,顾名思义,只是出现一次就消失了,flash设置值;
get_flashed_messages获取值(只能获取一次,第二次获取不到任何东西)