Flask
1.初识Flask
1.1先谈一下python框架区别
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Flask框架:
谈一下对python框架:
django:大而全,内部提供ORM,Admin,中间件,Form,ModelForm,session,缓存,信号,CSRF
flask:小而轻,可扩展性强
tornado:小而轻,异步非堵塞
wsgi:最基本的都是这个
django:wsgiref
flask:werkzurg
jinja2
1.2我们先看一下flask简单使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask app = Flask(__name__) @app.route("/index") def index(): return "index" if __name__ == "__main__": app.run()
1.3来聊一聊flask启动原理:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 先创建一个对象 app = Flask(__name__) 启动方式一:参数默认就是这个,内部调用启动方式二 app.run("127.0.0.1",5000) 启动方式二: from werkzeug.serving import run_simple run_simple("127.0.0.1",8888,app) 分析:程序监听中,如果执行app() = app.__call__ ;详细看我博客python内置函数
1.4配置参数
1.5,response
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
方式一:直接返回字符串 return "" 方式二:返回文件 静态文件配置:app = Flask(__name__,template_folder="templates") from flask import render_template return render_template("login.html") 方式三:重定向 from flask import redirect return redirect("/index")
1.6,路由控制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@app.route("/login",methods=["POST","GET"])
1.7request参数获取:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import request print(request.args)#get 获取url?参数 print(request.form)#post 获取的是前端form表单里面的值 print(request.files)#post 获取的是文件 print(request.get_json())#post 获取的是json print(request.get_data())#post 获取的是字节
1.8 模板变量传递以及渲染
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
**打散传参 from flask import render_template dic = {"name":"zhangsan","age":11} return render_template("login.html",dic=dic,**dic) 前端如何写 <h1>{{name}}{{age}}</h1> <h2>{{dic}}</h2> <h3>{{dic.name}}</h3> <h3>{{dic["age"]}}</h3> 关于for循环: {%for obj in arr%} {{obj.name}} {%endfor%}
1.9session
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
app.secret_key = "djaskdlas" from flask import session session["userinfo"] = "zhangsan" session.get("userinfo") del session["userinfo"] """ 为了将账号密码加密需要由上面的配置, flask只有session session就是cookie会放在浏览器 """
-----------------------------------------------------------------------------------------------------------------------------------------