flask
安装 pip3 install flask
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'ok' if __name__ == '__main__': # 本质是 run_simple(host,port, app, **options) # app(),对象加(),执行__call__ app.run()
配置文件
from flask import Flask, render_template, redirect, jsonify app = Flask(__name__) @app.route('/') def index():
# 返回字符串 # return 'ok1'
# 返回html # name_dict = {"name":"hui"} # return render_template("index.html",name=name_dict)
# 跳转页面 # return redirect("/login")
# 返回json数据 name_dict = [{"name":"hui"},{"name":"dayehui"}] return jsonify(name_dict) # @app.route('/login') # def login(): # return "dayehui" if __name__ == '__main__': app.run()
py文件
from flask import Flask app = Flask(__name__) app.config.from_object("settings.DevelopmentConfig") @app.route('/login') def login(): return 'hui' if __name__ == '__main__': app.run()
settings.py
class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True
路由
from flask import Flask, url_for app = Flask(__name__) app.debug=True
@app.route("路由",endpoint="取别名",methods=["GET","POST"]) def login(nid): return "dayehui" # rule 路由 # endpoint 取别名,不能重复 # methods=["POST","GET"] # view_func 请求路由要走的函数 app.add_url_rule('/login/<int:nid>',view_func=login, endpoint="ha",methods=['GET','POST']) def index(): real_url = url_for("ha",nid=3) print(real_url) return real_url app.add_url_rule('/index',view_func=index,methods=['POST','GET']) if __name__ == '__main__': app.run()
请求响应
from flask import Flask,url_for,views app = Flask(__name__) app.debug = True class IndexView(views.MethodView): def get(self): return "get" def post(self): return "post" app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) if __name__ == '__main__': app.run()
登录
from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) app.debug = True USERS = { 1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"}, 2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"}, 3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"}, } @app.route('/detail/<int:nid>',methods=['GET']) def detail(nid): info = USERS.get(nid) return render_template("detail.html",info=info) @app.route('/index',methods=['GET']) def index(): return render_template('index.html',user_dict=USERS) def login(): if request.method == "GET": return render_template('login.html') else: user = request.form.get('user') pwd = request.form.get('pwd') if user == 'hui' and pwd == '123': url = url_for('index') return redirect(url) return render_template('login.html',error='用户名或密码错误') app.add_url_rule("/login",view_func=login,methods=["GET","POST"]) if __name__ == '__main__': app.run()
detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <td>{{info.name}}</td> <td>{{info['age']}}</td> <td>{{info.get('name')}}</td> <td>{{info.get('gender')}}</td> <td>{{info.get('text')}}</td> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--<h1>hello</h1>--> <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="/detail/{{k}}">查看详情</a></td> </tr> {% endfor %} </table> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> 姓名:<input type="text" name="user"> 密码:<input type="text" name="pwd"> <input type="submit" value="登录"> {{error}} </form> </body> </html>
严格模式
from flask import Flask,redirect,render_template,jsonify,views app=Flask(__name__) # strict_slashes设置路由是否为严格模式,False是非严格模式,True是严格模式,默认是严格 @app.route("/index",strict_slashes=True,redirect_to ="/login") def index(): return "ok" @app.route("/login") def login(): return "sb" @app.route("/detail/<int:nid>") def detail(nid): print(nid) return "ok" if __name__ == '__main__': app.run()
自定义URL匹配正则表达式
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): # 路由匹配时,匹配成功后传递给视图函数中参数的值 # value就正则匹配出来的结果 print('value',value,type(value)) return "asdasdasd" def to_url(self, value): 使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数 val = super(RegexConverter, self).to_url(value) print(val) return val
模板
from flask import Flask,render_template,request,redirect,session,url_for,Markup app = Flask(__name__) app.debug = True app.secret_key = 'sdfsdfsdfsdf' USERS = { 1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"}, 2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"}, 3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"}, } def func1(st,st1): return Markup(f"<h1>jsaon-gdx{st}{st1}</h1>") @app.route('/list',methods=['GET']) def list(): info=USERS return render_template('list.html',info=info,html="<h1>jsaon-gdx</h1>",html1=func1)
@app.route('/detail/<int:nid>',methods=['GET'],endpoint="sb") def detail(nid) return "ok" if __name__ == '__main__': app.run()
list.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for k,v in info.items() %} <tr> <td>{{k}}</td> <td>{{v.name}}</td> <td>{{v['name']}}</td> <td>{{v.get('name')}}</td> <td><a href="{{url_for('sb',nid=k)}}">查看详细</a></td> </tr> {% endfor %} {{html|safe}} {{html1("-DSB","-SB")}} </body> </html>
请求与响应
from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) #请求里面有哪些内容 #我们怎么定制响应 @app.route('/login.html', methods=['GET', "POST"]) def login(): # 请求相关信息 #提交的方法 print(request.method) # request.args get请求提及的数据 print(request.args) # request.form post请求提交的数据 # request.values post和get提交的数据总和 # request.cookies 客户端所带的cookie # request.headers 请求头 print(request.headers) # request.path 不带域名,请求路径 print(request.path) # request.full_path 不带域名,带参数的请求路径 # request.script_root # request.url 带域名带参数的请求路径 # request.base_url 带域名请求路径 # request.url_root 域名 # request.host_url 域名 # request.host 127.0.0.1:500 # request.files # obj = request.files['the_file_name'] # obj.save('/var/www/uploads/' + secure_filename(f.filename)) # 响应相关信息 # return "字符串" # return render_template('html模板路径',**{}) # return redirect('/index.html') # return jsonify({'k1':'v1'}) #response = make_response(render_template('index.html')) # response是flask.wrappers.Response类型 # response.delete_cookie('key') # response.set_cookie('key', 'value') # response.headers['X-Something'] = 'A value' # return response #1导入make_response #2response=make_response(4剑客) #3 操作response # return response response=make_response(render_template('index.html')) response.set_cookie('jason', 'sb') # response.delete_cookie('key') response.headers['X-Something'] = 'A value sbwewewe' return response if __name__ == '__main__': app.run()
session
from flask import Flask,session app = Flask(__name__) app.secret_key="askjdaksd" app.config['SESSION_COOKIE_NAME']="dsb" # app.session_interface ''' app.session_interface这里面看 存session, 1 调用save_session,将我们的session加密的val,读取配置文件['SESSION_COOKIE_NAME']得到key 2 将1种的key,val存储到cookies 取session 1 获取request里面的cookies,获取里面key,这个key就是['SESSION_COOKIE_NAME'],值就是加密的值 2 对该值进行解密 ''' @app.route("/") def index(): session['jason']="gdx" return "ok" @app.route("/index1") def index1(): print(session['jason']) return "ok1" if __name__ == '__main__': app.run()
闪现
a 产生信息,传给 c 页面,但是用户访问a 页面以后,不是直接跳转到c, 而是到b, 或者是其他页面,但是用户访问c页面的时候,能够把a的信息拿到
from flask import Flask,flash,get_flashed_messages,request app = Flask(__name__) app.secret_key = 'asdfasdf' #1 如果要用flash就必须设置app.secret_key = 'asdfasdf' #2 只能取一次,在取就没有了 #3 我们可以通过 flash('普通信息',category="info"),对信息做分类 #4get_flashed_messages(with_categories=True,category_filter=("error",)),with_categories以键值对的形式获取 #我们设置闪现,category_filter=("error",)进行分类信息的过滤 @app.route('/index1') def index(): #(category="message", message)) flash('超时错误',category="error") flash('普通信息',category="info") return "ssdsdsdfsd" # return redirect('/error') @app.route('/error1') def error1(): return "ok" @app.route('/error') def error(): data = get_flashed_messages(with_categories=True,category_filter=("error","info")) data1 = get_flashed_messages(with_categories=True, category_filter=("error", "info")) print("data1",data1) print("data",data) return "错误信息" if __name__ == '__main__': app.run()
请求拓展
from flask import Flask,request,render_template app = Flask(__name__) # @app.before_request # def befor1(): # print(request) # print("我是请求之前1") # return "123" # @app.before_request # def befor2(): # print("我是请求之前2") # # @app.after_request # def after1(response): # print("我是请求之后1") # return response # # @app.after_request # def after2(response): # print("我是请求之后2") # return response # @app.before_first_request # def before_first(): # print("123") #如论有没有异常都会执行,如果没有异常这个参数就是None,有就记录这个异常 # @app.teardown_request # def tear(e): # print('teardown_request') # print(e) #捕获异常,如果出现异常,而且状态就是@app.errorhandler(404), @app.errorhandler(404) def error_404(arg): print(arg) return "404错误了" # @app.errorhandler(500) # def error(arg): # print(arg) # return "500错误了" @app.template_global() def sb(a1, a2): return a1 + a2 @app.template_filter() def db(a1, a2, a3): print(a1,a2,a3) return a1 + a2 + a3 @app.route('/index') def index(): print("我是真的视图") return render_template("index.html") if __name__ == '__main__': # app.__call__ app.run()
中间件
from flask import Flask app = Flask(__name__) class MyMiddleware: def __init__(self,wsgi_app): self.wsgi_app=wsgi_app def __call__(self,environ, start_response): print("之前") res=self.wsgi_app(environ, start_response) print("之后") return res @app.route('/index') def index(): return "ok" if __name__ == '__main__': # app.__call__ app.wsgi_app = MyMiddleware(app.wsgi_app) app.run()
dayehui