Flask框架
文档请访问: https://dormousehole.readthedocs.io/en/latest/
基本框架
这基本就是flask核心: MVT
路由
# 基础demo1
@app.route("/index") # 这里是路由决定了浏览器访问的url
def index_function():
return "这是主页"
# 返回html页面demo
@app.route("/index")
def index_function():
with open("index.html") as f:
content = f.read()
return content
# 取出url携带的数据demo
@app.route("/index/<user_id>") # <user_id>表示匹配url时,这里的数据提取出来
def index_function(user_id): # <>里接收到是数据,函数形参必须一致
return "<h1>这是%s的个人主页</h1>" % user_id
# 取出url携带的数据并渲染到前端demo,此处会涉及修改前端页面
@app.route("/index")
def index_function():
with open("index.html") as f:
content = f.read()
# 将html页面里的xxx特殊字符串替换成user_id
content = content.replace("xxx", user_id)
# 替换后的页面返回
return content
# demo返回JSON
@app.route("/xxx")
def xxx_function():
json_dict = {
“user_id”: 1,
"user_name": "喵喵"
}
return jsonify(json_dict)
# 重定向demo
@app.route("/xxx")
def xxx_function():
# return redirect('http://www.xxx.com') # 重定向某网址
# 当然也可以重定向自己写的url路径 例如:
# return redirect(url_for('index_function')) # 注意url_for中写得视图函数的名字得是字符串
# 带参数重定向
return redirect(url_for('index_function'), user_id=1)
# 自定义状态码
@app.route('/404')
def cannot_find():
return '状态码为 404', 404
数据库(使用SQLAlchemy)
"""
1.首先应在models包中建立models.py
2.导入应用的包
2. 连接提前准备好的数据库,
3. 创建字段
"""
# demo
# 要导入的包
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
# 连接MySQL数据库,格式为mysql+pymysql://数据库用户名:密码@数据库地址:端口号/数据库的名字?数据库格式
engine = create_engine(‘'mysql+pymysql://root:mysql@127.0.0.1:3306/myflask?charset=utf8'’)
Base = declarative_base() # 生成SQLORM基类
# 设置字段
class User(Base):
__tablename__ = 'user' # 对应MySQL中的数据表的名字
# 创建字段
id = Column(Integer, primary_key=True)
user_id = Column(String(50), nullable=False)
user_name = Column(String(50), nullable=False)
head_img = Column(string(200))
short_description = Column(String(300))
# 使用models.py的demo
@app.route("/profile_v8/<user_id>")
def profile_v8(user_id):
# 1. 查询数据库
# 创建session对象
DBSession = sessionmaker(bind=engine) # 创建与数据库的会话,返回的是一个类
session = DBSession() # 生成链接数据库的实例
# 获取返回数据的第一行
obj = session.query(User).filter(User.user_id == user_id).one()
# 关闭session
session.close()
# 2. 模板渲染
return render_template("profile.html", user_name=obj.user_name, head_img=obj.head_img, short_description=obj.short_description)