Flask

1.Flask前奏

网上找一个破解的专业版pycham,很好会有很多代码提示,省去很多配置

2.项目配置

Debug、Host、Port配置

3.URL视图

有参数的URL
@app.route('/blog/<blog_id>')
def blog_detail(blog_id):  # put application's code here
    return '你访问的博客id是:%s'%blog_id

@app.route('/book/list')
def book_list():  # put application's code here
    page=request.args.get("page",default=1,type=int)
    return f"您获取的是第{page}页的图书!"

4.Jinja2模板

定义一个路由
from flask import Flask,render_template

@app.route('/')
def hello_world():  # put application's code here
    user = User('lzy', 'xx@qq.com')
    person = {
        'username': user.username,
        'age': 18
    }
    return render_template('index.html', user=user, person=person)

渲染模板:render_template

渲染变量:user=user

定义路由页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>lzy的首页</title>
</head>
<body>

    <h1>lzy and hq</h1>
    <h1>{{ user.username}}/{{ user.email }}</h1>
    <div>{{ person['username'] }} {{ person['age'] }}</div>
     }}
</body>
</html>

页面中使用变量:{{user.username}}  或者{{person['username']}}

自定义过滤器三部曲
1.自定义过滤器
def datetime_format(value, format='%Y-%m-%d %H:%M:%S'):
    return value.strftime(format)

app.add_template_filter(datetime_format, "dformat")
2.配置app函数
@app.route('/filter')
def filter_demo():  # put application's code here
    user = User('lzy', 'xx@qq.com')
    mytime=datetime.now()
    return render_template("filter.html", user=user,mytime=mytime)
3.使用自定义的过滤器:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>过滤器使用demo</title>
</head>
<body>
{{ user.username }}--{{ user.username|length }}
<div>
    {{ mytime|dformat }}
</div>
</body>
</html>

内置过滤器
{{ user.username|length }}

控制语句
if:
{% if age>18 %}
    <div>您已经成年</div>
{% elif age <18 %}
    <div>您未成年</div>
{% else %}
    <div>您刚成年</div>
{% endif %}
for:
{% for book in books %}
    <div>书名:{{ book.name}},作者:{{ book.author }}</div>
{% endfor %}

模板继承
{% extends "base.html" %}
{% block title %}
    我是子模版的标题
{% endblock %}


{% block body %}
    我是子模版的body
{% endblock %}

css、js、image的引入
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">#css文件
    <script src="{{ url_for('static',filename='js/my.js')  }}"></script>#引入js文件
</head>
<body>

<img src="{{ url_for('static',filename='images/1.png') }}" alt="">#引入图片
</body>
</html>

5.数据库

连接mysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

HOSTNAME = "127.0.0.1"#主机名
PORT = 3306#端口号
USERNAME = "root"#用户名
PASSWORD = "*******"#密码
DATABASE = "database_learn"*创建的数据库的名称
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)
    email = db.Column(db.String(100), nullable=False)

db.create_all()
增删改查:
@app.route('/user/add')
def user_add():  # put application's code here
    user1 = User(username="lzy", password="123456")
    db.session.add(user1)
    db.session.commit()
    return '用户添加成功'

@app.route('/user/query')
def user_query():  # put application's code here
    # user=User.query.get(1)
    # print(user.id,user.username)
    users = User.query.filter_by(username="lzy")
    for user in users:
        print(user.username)
    return "数据查找成功"

@app.route('/user/update')
def user_update():  # put application's code here
    user = User.query.filter_by(username="lzy").first()
    user.username = "lzy爱hahaha"
    db.session.commit()
    return "修改成功"

@app.route('/user/delete')
def user_delete():  # put application's code here
    user = User.query.get(1)
    db.session.delete(user)
    db.session.commit()
    return "删除成功"

创建外键:
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)
    email = 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"))#外键
建立联系
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)
    email = 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")#backref
模型迁移三部曲

note:第一步完成一次之后,都只要运行后面两句代码

from flask_migrate import Migrate

migrate = Migrate(app, db)

#1 创建初始化环境
flask db init

#2 生成迁移脚本
flask db migrate

#3 执行迁移脚本
flask db upgrade
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值