Python之Flask框架
Flask安装
pip install Flask
项目配置
debug模式 Host 端口号
from flask import Flask, request
app = Flask(__name__)
# http://192.168.31.118:5001/
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World12223!'
# http://192.168.31.118:5001/my
@app.route('/my')
def my():
return 'My name is Douge'
# http://192.168.31.118:5001/book/list 你获取的是1
# http://192.168.31.118:5001/book/list?page=2 你获取的是2
@app.route('/book/list')
def book_detail():
page = request.args.get('page',default=1,type=int)
return '你获取的是{}'.format(page)
if __name__ == '__main__':
app.run()
模版渲染 传参
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/template/detail_id/<detail_id>')
def template(detail_id): # put application's code here
return render_template('demo.html', detail_id=detail_id)
模版访问对象
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/template/detail_id/<detail_id>')
def template(detail_id): # put application's code here
obj = {
'name':'douge'
}
return render_template('demo.html', detail_id=detail_id,obj=obj)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>hello Python{{ detail_id }}</div>
<div>{{ obj }}</div>
<div>{{ obj.name }}</div>
</body>
</html>
自定义过滤器
类似Thinkphp模版里面的使用函数
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/template')
def template(): # put application's code here
obj = {
'name': 'douge'
}
return render_template('demo.html', obj=obj)
# 自定义过滤器
def filter(value):
return value.upper()
# 增加过滤器
app.add_template_filter(filter, 'filter')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#内置过滤器#}
<div>{{ obj.name | length}}</div>
{#自定义过滤器#}
<div>{{ obj.name | filter}}</div>
</body>
</html>
控制语句
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/template')
def template(): # put application's code here
obj = {
'name': 'douge',
'age': 18,
'child': ['1', '2']
}
return render_template('demo.html', obj=obj)
<div>
{{ obj }}
{#if判断#}
<div>
{% if obj.age >= 18 %}可以进入 {% endif %} {% if obj.age < 18 %} 禁止进入{% endif %}
</div>
{#for循环#}
<div>
{% for foo in obj.child %}
{{ foo }}
{% endfor %}
</div>
</div>
模版组件穿参
mode.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>test</title>
</head>
<body>
<div>
{% extends 'footer.html' %}
{% block title %} 标题 {% endblock %}
{% block content %} 内容 {% endblock %}
</div>
</body>
</html>
footer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>footer 这是一个组件</title>
</head>
<body>
<h1>footer组件</h1>
<h2>{% block title %}{% endblock %}</h2>
<h3>{% block content %}{% endblock %}</h3>
</body>
</html>
加载静态文件
<head>
<meta charset="UTF-8" />
<title>test</title>
{#引入css#}
<link rel="stylesheet" href='{{ url_for("static",filename="demo.css") }}' />
{#引入js#}
<script src='{{ url_for("static",filename="demo.js")}}'></script>
</head>
<body>
<div>
{#引入图片#}
<img class="text_img" src='{{ url_for("static",filename="test.jpg") }}' alt="" />
</div>
</body>
操作数据库(Mysql) 增删改查(CRUD)
pip install pymysql
pip install flask-sqlalchemy
连接数据库
# 从 Flask 这个包中导入 flask 这个类
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
# 配置文件
HOSTNAME = '103.*.*.36'
PORT = 3306
USERNAME = 'python_test'
DATABASE = 'python_test'
PASSWORD = 'PdpLZMk4F4Z6aYwF'
print('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,HOSTNAME, PORT,DATABASE))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,HOSTNAME, PORT,DATABASE)
db = SQLAlchemy(app)
with app.app_context():
with db.engine.connect() as conn:
rs = conn.execute(text("select 1"))
print(rs.fetchone()) #输出 (1,)
运行输出
创建数据表
# 从 Flask 这个包中导入 flask 这个类
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
# 配置文件
HOSTNAME = '103.*.*.36'
PORT = 3306
USERNAME = 'python_test'
DATABASE = 'python_test'
PASSWORD = 'PdpLZMk4F4Z6aYwF'
print('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,HOSTNAME, PORT,DATABASE))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,HOSTNAME, PORT,DATABASE)
db = SQLAlchemy(app)
# with app.app_context():
# with db.engine.connect() as conn:
# rs = conn.execute(text("select 1"))
# print(rs.fetchone()) # (1,)
# User orm
class User(db.Model):
# 映射表名
__tablename__ = 'user'
# 配置数据库元素
# id,username,password 的各自的属性(主键,类型,是否可以为空,自增等等)
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)
# 下面的语句实际上就是映射为 insert 语句
# user = User(username='法外狂徒张三', password='111111')
# 将你创建的表推到数据库
with app.app_context():
db.create_all()
Create
# 从 Flask 这个包中导入 flask 这个类
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
# 配置文件
HOSTNAME = '103.*.*.36'
PORT = 3306
USERNAME = 'python_test'
DATABASE = 'python_test'
PASSWORD = 'PdpLZMk4F4Z6aYwF'
print('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,
HOSTNAME, PORT,
DATABASE)
db = SQLAlchemy(app)
# with app.app_context():
# with db.engine.connect() as conn:
# rs = conn.execute(text("select 1"))
# print(rs.fetchone()) # (1,)
# User orm
class User(db.Model):
# 映射表名
__tablename__ = 'user'
# 配置数据库元素
# id,username,password 的各自的属性(主键,类型,是否可以为空,自增等等)
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)
# 下面的语句实际上就是映射为 insert 语句
# user = User(username='法外狂徒张三', password='111111')
# 将你创建的表推到数据库
with app.app_context():
db.create_all()
@app.route('/user/add')
def addUser():
user = User(username='法外狂徒张三', password='111111')
db.session.add(user)
db.session.commit()
return '新建用户成功'
Read
@app.route('/user/read')
def readUser():
# get 查找:根据主键查找
user = User.query.get(1)
return '查找用户成功{}{}'.format(user.id, user.username)
@app.route('/user/read')
def readUser():
# 1.get 查找:根据主键查找
# user = User.query.get(1)
# 2.使用 filter_by 查找
users = User.query.filter_by(username='法外狂徒张三')
print('this is users', users[0].username)
return '查找用户成功'
Update
@app.route('/user/update')
def updateUser():
user = User.query.filter_by(username='法外狂徒张三').first()
user.username = '法外狂徒李嘉俊'
db.session.commit()
return '修改用户成功'
Delete
@app.route('/user/delete')
def deleteUser():
# 查找
user = User.query.filter_by(username='法外狂徒李嘉俊').first()
# 从 db.session 中删除
db.session.delete(user)
# 提交删除
db.session.commit()
return '删除用户成功'
ORM模型外键与表关系
# 从 Flask 这个包中导入 flask 这个类
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
# 配置文件
HOSTNAME = '103.*.*.36'
PORT = 3306
USERNAME = 'python_test'
DATABASE = 'python_test'
PASSWORD = 'PdpLZMk4F4Z6aYwF'
print('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD,
HOSTNAME, PORT,
DATABASE)
db = SQLAlchemy(app)
# with app.app_context():
# with db.engine.connect() as conn:
# rs = conn.execute(text("select 1"))
# print(rs.fetchone()) # (1,)
# User orm
class User(db.Model):
# 映射表名
__tablename__ = 'user'
# 配置数据库元素
# id,username,password 的各自的属性(主键,类型,是否可以为空,自增等等)
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)
# 下面的语句实际上就是映射为 insert 语句
# user = User(username='法外狂徒张三', password='111111')
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"))
# backref 会自动给User模型添加一个articles的属性 来获取文章列表
author = db.relationship("User", backref="articles")
# article = Article(title="Jindouyun", content="hello world")
# article.author_id = user.id
# user = user.query.get(article.author_id)
# article.author = User.query.get(article.author_id)
# print(article.author)
# sqlalchemy/flask
# user.articles
# 将你创建的表推到数据库
with app.app_context():
db.create_all()
@app.route('/user/add')
def addUser():
user = User(username='法外狂徒张三', password='111111')
db.session.add(user)
db.session.commit()
return '新建用户成功'
@app.route('/article/add')
def article_add():
article = Article(title="Jindouyun", content="hello world")
article.author = User.query.get(1)
article1 = Article(title="Jindouyun1", content="hello world1")
article1.author = User.query.get(1)
db.session.add_all([article, article1])
# 同步到数据库
db.session.commit()
return '文章插入成功'
# http://192.168.1.7:5001/article/query
@app.route('/article/query')
def query_article():
user = User.query.get(1);
for article in user.articles:
print(article.title)
return "文章查询成功!"
# * Debugger is active!
# * Debugger PIN: 931-355-907
# Jindouyun
# Jindouyun1