conda reate -n flask python
conda activate flask
pip install flask -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
首先项目的结构
static(文件夹,放css,js,图片文件等)
templates(文件夹,放html文件)
1.第一个flask项目.py
from flask import Flask#flask包中导入Flask类
app=Flask(__name__)#使用Flask类创建一个对象
#创建路由和试图函数的映射
@app.route("/")
def hello():
return "hello world"
if __name__=="__main__":
app.run()
app.run(debug=True,host="0.0.0.0",port="5001")
有参路由,路由传参
查询字符串的方式传参:http://172.20.10.5:5000/book/list?page=9,默认page=1
from flask import Flask,request
app=Flask(__name__)
#1.url:http[80]/https[443]://www.域名.com:port/path
@app.route("/")
def hello():
return "hello world"
@app.route("/profile")
def profile():
return "个人中心"
#2.有参路由,路由传参
@app.route("/blog/" )
def blog_detail(blog_id):
return "您访问的博客是:%d" %blog_id
#3.查询字符串的方式传参:http://172.20.10.5:5000/book/list?page=9,默认page=1
@app.route("/book/list")
def book_list():
page=request.args.get(key="page",default=1,type=int)
return f"这是第{page}页"
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
1.templates/blog.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<titel>博客titel>
head>
<body>
<h1>博客id是:{{blog_id}}h1>
<p>博客名是:{{user_name}}p>
<div>{{user.username}}/{{user.email}}div>
<div>{{person.u}}/{{person["e"]}}div>
body>
html>
2.模板渲染.py
from flask import Flask,render_template
app=Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")#1.自动去templates目录下面找index.html文件,并渲染
@app.route("/blog/" )
def blog_detail(blog_id):
return render_template("blog.html",blog_id=blog_id,user_name="zoe")#2.传参数给html去渲染,html:{{var_name}}
class User:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route("/information")
def information():
user=User(username="张三",email="111@zs")
person={"u":"李四","e":"222@ls"}
return render_template("blog.html",user=user,person=person)#3.传的参数是对象,字典。
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
传到html的变量处理再渲染,这时用管道操作符(|),连接自带的过滤器或者自定义的过滤器.
1.filter.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<titel>titel>
head>
<body>
<div>{{user.username}}长度是:{{user.username|length}}div>
<div>{{mytime|dformat}}div>
body>
html>
2.过滤器.py
from flask import Flask,render_template
from datetime import datetime
app=Flask(__name__)
class User:
def __init__(self,username,email):
self.username=username
self.email=email
#2.自定义过滤器
def datetime_format(value,format="%Y年%m月%d日 %H:%M"):
return value.strftime(format)
app.add_template_filter(datetime_format,"dformat")#将自定义的datetime_format,以dformat为名添加到app的过滤器中
@app.route("/filter")
def filter():
user=User(username="张三",email="111@zs")
mytime=datetime.now()
return render_template("filter.html",user=user,mytime=mytime)#1.user这里在html中会用到自带的过滤器,给出变量的length
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
1.control.html
DOCTYPE html>
<html lang="en">
<head>
<meta chatset="UTF-8">
<title>控制语句if与fortitle>
head>
<body>
{% if age>18 %}
<div>你已成年div>
{% elif age==18 %}
<div>你今年成年div>
{% else %}
<div>你未成年啊div>
{% endif %}
{% for book in books %}
<div>书名:{{book.name}},作者:{{book.author}}div>
{% endfor %}
body>
html>
2.控制语句.py
from flask import Flask,render_template
app=Flask("__name__")
@app.route("/control")
def control():
age=8
books=[{"name":"三国演义","author":"罗贯中"},{"name":"水浒传","author":"施耐庵"}]
return render_template("control.html",age=age,books=books)
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
1.base.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}title>
head>
<body>
这是base文字
{% block body %}{% endblock %}
body>
html>
2.child1.html
{% extends "base.html"%}
{% block title %}
child1的title
{% endblock %}
{% block body %}
child1的body
{% endblock %}
3.模板继承.py
from flask import Flask,render_template
app=Flask("__name__")
@app.route("/child1")
def child1():
return render_template("child1.html")
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
在html文件里加载static里面的css,js,picture等文件。
1.alert.js
alert("js执行的弹窗");
2.style.css
body{
background-color:pink;
}
3.static.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态文件加载title>
<link rel="stylesheet" href="{{url_for('static',filename='css/style.css')}}">
<script src="{{url_for('static',filename='js/alert.js')}}">script>
head>
<body>
<img src="{{url_for('static',filename='img/1.jpg')}}" alt="">
body>
html>
4.加载静态文件.py
from flask import Flask,render_template
app=Flask("__name__")
@app.route("/my_static")
def my_static():
return render_template("static.html")
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
这里可以参考博文。
然后在flask环境中
pip install pymysql
pip install flask-sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="xxxx"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)#1.sqlalchemy读取app的config,然后自动连接,
#2.测试sql是否连接成功,输出(1,),表示连接成功
with app.app_context():
with db.engine.connect() as conn:
rs=conn.execute(text("select 1"))
print(rs.fetchone())
@app.route("/")
def hello():
return "hello"
if __name__=="__main__":
app.run()
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="xxxx"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)
#1.ORM对象关系映射,一个ORM模型与数据库中的一个表对应:创建一个类就是创建了一张表,实例化一个对象就是插入了一条数据
class User(db.Model):
__tablename__="user"#表名
id=db.Column(db.Integer,primary_key=True,autoincrement=True)#设为主键,自动增长
username=db.Column(db.String(100),nullable=False)#不可置空
password=db.Column(db.String(100),nullable=False)
with app.app_context():
db.create_all()#开始创建表
#1.增:
@app.route("/user/add")
def add_user():
user=User(username="张三",password="123")#1.创建ORM对象
db.session.add(user)#2.将ORM对象添加到db.session
db.session.commit()#3.将db.session中的改变同步到数据库中
return "用户创建成功"
#2.查询:get查找(根据主键查找);filter_by查找
@app.route("/query")
def query():
#1.get查找
# user=User.query.get(1)
# print(f"{user.id}:{user.username}--{user.password}")
#2.filter_by查找
users=User.query.filter_by(username="张三")#是一个Query类数组
for user in users:
print(user.username)
return "查找成功"
#3.改:
@app.route("/user/update")
def update_user():
user=User.query.filter_by(username="张三").first()
user.password="gai"
db.session.commit()
return "数据修改成功"
#4.删:
@app.route("/user/delete")
def delete_user():
user=User.query.get(1)
db.session.delete(user)
db.session.commit()
return "删除成功"
@app.route("/")
def hello():
return "hello"
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="190023"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)
class User(db.Model):
__tablename__="user"#表名
id=db.Column(db.Integer,primary_key=True,autoincrement=True)#设为主键,自动增长
username=db.Column(db.String(100),nullable=False)#不可置空
password=db.Column(db.String(100),nullable=False)
class Article(db.Model):
__tablename__="article"
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
title=db.Column(db.String(200),nullable=False)
content=db.Column(db.Text,nullable=False)
#添加两表之间的外键
author_id=db.Column(db.Integer,db.ForeignKey("user.id"))
#添加两表之间的对象关系
author=db.relationship("User",backref="articles")#article.author返回User的对象,user.articles返回Article的对象
with app.app_context():
db.create_all()
#增
@app.route("/article/add")
def ar_ad():
article1=Article(title="西游记",content="xxxxxxxxxxxxxxxx")
article1.author=User.query.get(2)
article2=Article(title="红楼梦",content="yyyyyyyyyyyyyyyy")
article2.author=User.query.get(2)
#添加到session中
db.session.add_all([article1,article2])
#session中的数据同步到数据库中
db.session.commit()
return "文章添加成功"
#查
@app.route("/article/query")
def ar_qu():
user=User.query.get(2)
for article in user.articles:
print(article.title)
return "文章查找成功"
if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
set flask环境
pip install flask-migrate
pip install flask-migrate --upgrade
pip install flask-sqlalchemy --upgrade
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="190023"
DATABASE="database_flask"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)
migrate=Migrate(app,db)
#ORM模型映射的三步
#1.flask db init:秩序执行一次,相当于仓库初始化
#2.flask db migrate:识别ORM模型的改变,生成迁移脚本
#3.flask db upgrade: