Flask #python后端框架学习笔记
PyCharm
app.py
总文件下的app.py文件,AI添加了部分注释:
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
class User:
def __init__(self, username, email):
self.username = username
self.email = email
# 首页路由
@app.route('/')
def hello_world():
# 创建User对象
user = User(username ="LDS", email="xx@qq.com")
# 将user对象渲染到index.html模板中并返回
return render_template('index.html', user=user)
# 个人中心路由
@app.route("/profile")
def profile():
return "我是个人中心!"
# 博客列表路由
@app.route("/blog/list")
def blog_list():
return "博客列表!"
# 博客详情路由,使用参数传递
@app.route("/blog/<int:blog_id>")
def blog_detail(blog_id):
return render_template("blog_detail.html", blog_id=blog_id, username="XX")
# 图书列表路由,使用查询字符串传参
@app.route('/book/list')
def book_list():
# 获取当前页数,默认为1
page = request.args.get("page", default=1, type=int)
return f"获取的是第{page}的图书列表!"
# filter演示路由
@app.route("/filter")
def filter_demo():
# 创建User对象
user = User(username="lds123456", email="XX@qq.com")
# 将user对象渲染到filter.html模板中并返回
return render_template("filter.html", user=user)
# 静态文件路由
@app.route("/static")
def static_demo():
# 返回静态文件展示页面
return render_template("static.html")
if __name__ == '__main__':
# 运行应用
app.run()
templates
创建总文件时自带的特殊文件夹
blog.detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>博客详情</title>
</head>
<body>
<!-- 在此处添加一个段落标签 -->
<p>您的用户名是:{{ username }}</p>
<!-- 在此处添加一个一级标题标签,显示访问的博客详情的ID -->
<h1>访问的博客详情是:{{ blog_id }}</h1>
</body>
</html>
filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过滤器使用demo</title>
</head>
<body>
{{ user.username }}-{{ user.username|length }}
</body>
</html>
index.html
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
{{ user.username }} / {{ user.email }}
</body>
</html>
static.html
<!--这是一个 HTML5 文档类型声明-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <!--声明页面使用的字符集-->
<title>Title</title> <!--网页标题-->
<link rel="stylesheet" href="{{ url_for('static', filename='CSS/style.css') }}"> <!--引入外部样式表-->
<script src="{{ url_for('static', filename='js/my.js') }}"></script> <!--引入外部 JavaScript 文件-->
</head>
<body>
<img src="{{ url_for('static', filename='image/0.jpg') }}" alt=""> <!--插入图片-->
</body>
</html>
static
创建的二级文件夹
CSS
style.css
body{
background-color: pink;
}
image
0.jpg
js
my.js
alert("my.js中执行的!");