flask之web网关、三件套、配置、路由(参数、转化器及自定义转化器)、cbv、模板语言、session

时间:2021-09-30 05:19:08

1.wsgiref.py

from wsgiref.simple_server import make_server

def mya(environ, start_response):
print(environ)
print(start_response)
start_response('200 OK', [('Content-Type', 'text/html')])
if environ.get('PATH_INFO') == '/index':
with open(r'index.html', 'rb') as f: data = f.read() elif environ.get('PATH_INFO') == '/login':
with open('login.html', 'rb') as f:
data = f.read()
else:
data = b'<h1>Hello, web!</h1>'
# 返回数据,用列表的方式
return [data] if __name__ == '__main__':
myserver = make_server('', 8011, mya)
print('监听8011')
myserver.serve_forever()
# http://127.0.0.1:8011/index

2.werzeug.py

from werkzeug.wrappers import Request, Response

@Request.application
def hello(request):
print(request)
return Response('Hello World!') if __name__ == '__main__':
from werkzeug.serving import run_simple
# run_simple('127.0.0.1', 4000, hello)
run_simple('localhost',4000,hello)

3.三件套

from flask import Flask,render_template,redirect,jsonify,request
app=Flask(__name__) '''
1 返回字符串
2 返回模板:render_template
3 跳转:redirect
4 json返回 ''' @app.route("/")
def index(): return "ojbk" @app.route("/index")
def index1():
return render_template("index.html") @app.route("/home")
def home():
return redirect("/index") @app.route("/json")
def json1():
data_dic={'name':"jason",'age':38}
return jsonify(data_dic) if __name__ == '__main__':
app.run()

4.配置文件



from  flask import Flask
app = Flask(__name__)
#方式一
# 只能配置下面俩个
# app.debug=True
# app.secret_key="asdjja"
#方式二,以字典的形式
# app.config['DEBUG']=True
#方式三 ,以文件的形式
app.config.from_pyfile("settings.py")
#方式四 ,以类的形式(*****)
# app.config.from_object("settings.test") @app.route("/")
def index():
return "fdsfk" if __name__ == '__main__':
app.run() #settings.py
# DEBUG=True class comment:
DEBUG = True class test(comment):
pass class onlin(comment):
pass

5.路由本质

from  flask import Flask
app = Flask(__name__) # @app.route("/") #@decorator
def index():
return "ok" app.add_url_rule("/index", view_func=index) if __name__ == '__main__':
app.run()

6.cbv.py

from  flask import Flask,views,url_for
app = Flask(__name__) #简单模式 # class IndexView(views.View):
# methods = ['GET']
# #给dispatch_request加装饰器
# #decorators = [login, ]
# def dispatch_request(self):
# print('Index')
# return 'Index!'
# def post(self):
# pass
# def get(self):
# pass
#
# app.add_url_rule('/index1', view_func=IndexView.as_view(name='index1')) # name=endpoint
#相当于app.add_url_rule('/index2', view_func=view) view.__name__=index1 #或者,通常用此方式
class IndexView(views.MethodView):
methods = ['GET']
# decorators = [auth, ] def get(self):
return 'Index.GET' def post(self):
return 'Index.POST'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint if __name__ == '__main__':
app.run()

7.路由转化器

from  flask import Flask,views,url_for, redirect
app = Flask(__name__) @app.route("/index/",endpoint='a',methods=["POST","GET"],strict_slashes=True)
def index():
print(url_for('b'))
return redirect(url_for('b')) @app.route('/inde1/', endpoint='b')
def index():
return 'hahha'
@app.route("/index2")
def index2():
return "吃饭去了" if __name__ == '__main__': app.run()

8.自定义转化器

#1 写类,继承BaseConverter
#2 注册:app.url_map.converters['regex'] = RegexConverter
# 3 使用:@app.route('/index/<regex("\d+"):nid>') 正则表达式会当作第二个参数传递到类中
from flask import Flask, views, url_for
from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) class RegexConverter(BaseConverter):
"""
自定义URL匹配正则表达式
"""
def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex def to_python(self, value):
"""
路由匹配时,匹配成功后传递给视图函数中参数的值
"""
return int(value)+123 def to_url(self, value):
"""
使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
"""
val = super(RegexConverter, self).to_url(value)
return val+"json"
# 添加到flask中
app.url_map.converters['regex'] = RegexConverter
@app.route('/index/<regex("\d+"):nid>')
def index(nid):
print(nid)
print(url_for('index', nid='888'))
return 'Index' if __name__ == '__main__':
app.run()

9.模板语言

from  flask import Flask,render_template,Markup
app = Flask(__name__) USERS = {
1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
} def func1(flag):
return Markup(f"<h1>jason dsb ?{flag}</h1>" ) @app.route("/index")
def index():
data=USERS
flag=True
htm="<h1>jason dsb</h1>"
return render_template("index1.html",data=data,flag=flag,name="sb",name1="sb1",htm=htm,func=func1) if __name__ == '__main__':
app.run()

10.session原理

from  flask import Flask,session
app = Flask(__name__)
app.secret_key="sdasjdiashdiah"
app.config["SESSION_COOKIE_NAME"]="jason" # app.session_interface @app.route("/")
def index():
session['name']="jason"
return "ok" @app.route("/index")
def index1():
print(session['name'])
return "123" if __name__ == '__main__':
app.run()

11.templatess

<!-- detail.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>详细信息 {{info.name}}</h1>
<div>
{{info.text}}
</div>
</body>
</html> <!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="{{url_for('detail',nid=k)}}">查看详细</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
<!--index1.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> </head>
<body>
{% for k,v in data.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="/detail/{{k}}">查看详细</a></td>
</tr>
{% endfor %} {% if flag %}
{{name}}
{% else %}
{{name1}}
{% endif %}
<br> {{htm|safe}} {{func("yes")}} </body>
</html>
<!--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="登录">{{error}}
</form>
</body>
</html>