flask-day03

3 篇文章 0 订阅
1 篇文章 0 订阅

SQLAlchemy是一个常用的数据库抽象层和对象关系映射器,我们这里通过SQLAlchemy来访问mysql数据库和创建模型(models)

1、链接数据库和数据库查询

首先,我们需要安装SQLAlchemy可以通过

pip install Flask-SQLAlchemy

链接mysql数据库还需安装pymysql来驱动。

pip install pymysql

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy # 导入SQLAlchemy

from Stu.views import stu

def create_app():

    BASE_DIR = os. path.dirname(os.path.dirname(os.path.abspath(__file__)))

    templates_dir = os.path.join(BASE_DIR, 'templates')
    static_dir = os.path.join(BASE_DIR, 'static')

    app = Flask(__name__, template_folder=templates_dir,
                static_folder=static_dir)
    app.register_blueprint(blueprint=stu, url_prefix='/stu')

    # 下面配置链接数据库的基本设置
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://' \
                                            'root:password@Ip:port/db_name'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    SQLAlchemy(app=app)

    return app

在app/models.py 创建模型

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy() # 创建db对象

class Student(db.Model):
    # 创建模型字段
    s_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    s_name = db.Column(db.String(20), unique=True)
    s_age = db.Column(db.Integer, default=18)
    #重构表名
    __tablename__ = 'student'

在app/views.py中创建创建表和删除表的路由

import random

from flask import Blueprint, render_template, url_for,redirect

from Stu.models import db, Student

stu = Blueprint('stu', __name__)

@stu.route('/createtable/')
def create_db():
    """创建学生表"""
    db.create_all()
    return '创建成功'


@stu.route('/deltable/')
def del_stu():
    """删除学生表"""
    db.drop_all()
    return '删除成功'

我们通过访问路由就可以在mysql数据库中创建出模型定义的表结构的表,这里是是通过我们创建的db对象通过create_all()和drop_all()方法来创建和删除表,如果我们还有其他的模型的话,已经创建的表不会重复创建也不会覆盖原先已创建的表,只会创建为未被创建的模型,drop_all()慎用,会删除你所创建的所有表。

表创建好了我们就需要向表中添加数据,创建一个路由来向表中添加数据

@stu.route('/createstu/')
def create_stu():
    """创建学生信息成功"""
    stu = Student() # 创建一个学生对象
    stu.s_name = '小米%d' % random.randrange(1000)
    stu.s_age = '%d' % random.randrange(20)

    db.session.add(stu)
    # 如果未成功提交到数据库进行回滚
    try:
        db.session.commit()
    except:
        db.session.rollback()

    return '创建学生成功'

每访问一次路由就创建一条数据,也就是表中的一行。

查询数据库中的数据
flask支持原生的SQL语句进行查询

@stu.route('/stulist/')
def stu_all():
    """查询数据库所有学生信息"""
    # stus = Student.query.all()
    sql = 'select * from student;'
    stus = db.session.execute(sql)

    return render_template('stulist.html', stus=stus)


@stu.route('/studetail/')
def stu_detail():
    """查询具体某一学生信息"""
    # 使用原生sql
    # sql = "select * from student where s_name='小米166'"
    # stus = db.session.execute(sql)

    # 使用filter
    # stus = Student.query.filter(Student.s_name=='小米166')

    # 使用filter_by
    stus = Student.query.filter_by(s_name='小米760')

    return render_template('stulist.html', stus=stus)


@stu.route('/updatestu/')
def upate_stu():
    """更某一新学生信息"""
    # 第一种方式
    # stu = Student.query.filter_by(s_id=5).first()
    # stu.s_name = '小明'

    Student.query.filter(Student.s_id==5).update({'s_name': '王大锤111'})

    # 把修改后的提交到数据库
    db.session.commit()

    return redirect(url_for('stu.stu_all'))


@stu.route('/deletestu/')
def delete_stu():
    """删除某一学生信息"""

    stu = Student.query.filter(Student.s_id==5).first()
    db.session.delete(stu)
    db.session.commit()
    return redirect(url_for('stu.stu_all'))

这里要注意我们在用django查询的时候:
Django:
stus = Student.objects.filter(s_id=1)
查询查出来是一个对象列表
Flask:
stus = Student.query.filter(Student.s_id==1)(注意双等号)或者
stus = Student.query.filter_by(s_id=1)
查询出来也是储存在QueryBase 对象列表里的

2、模板渲染

app/views.py 路由

@stu.route('/scores/')
def scores():
    scores_list = [25, 26, 36, 15, 95, 60, 45]
    content_h2 = '<h2>into the new world</h2>'
    content_h3 = '  <h3>徐孝元</h3>  '
    return render_template('scores.html', content_h2=content_h2,
                           scores=scores_list,
                           content_h3=content_h3)

渲染页面
templates/scores.html

{% extends 'base_main.html' %}

{% block title %} 分数页面 {% endblock %}


{% block header %}
    {% for score in scores %}
        {{ loop.first }}
        {{ loop.index }}
        {{ loop.index0 }}
        {{ loop.last }}
        {{ loop.length }}
        {{ loop.revindex }}
        {{ loop.revindex0 }}
        {% if loop.first %}
        <li style="color: red">{{ score }}</li>
        {% elif loop.index == 3 %}
        <li style="color: yellow">{{ score }}</li>
        {% elif loop.last %}
            <li style="color: green">{{ score }}</li>
        {% else %}
            <li>{{ score }}</li>
        {% endif %}
    {% endfor %}
<hr>
<ur>
    <li>{{ content_h2 }}</li>
    <li>{{ content_h2|safe }}</li>
    <li>{{ content_h2|striptags }}</li>

    <li>{{ content_h3 }}</li>
    <li>{{ content_h3|length }}</li>
    <li>{{ content_h3|safe }}</li>
    <li>{{ content_h3|trim|length }}</li>

</ur>
<ul>
    {% for i in config %}
        <li>{{ i }}, 首字母:{{ i|first }},
            最后一个字母:{{ i|last }}, 小写:{{ i|lower }}, 大写:{{ i|upper }},
            首字母大写:{{ i|capitalize }}
        </li>
    {% endfor %}
</ul>

{% from 'functions.html' import show_goods %}
{% from 'functions.html' import say %}

{{ show_goods('可爱多', '1') }}
<br>
{{ show_goods('梦龙', '2') }}
<hr>
{{ say() }}
{% endblock %}

里面是一些基本的Jinja2模板引擎的语法

templates/functions.html
macro(宏)的使用

{% macro show_goods(goods_name, goods_id) %}
    商品的id:{{ goods_id }}
    商品的名称:{{ goods_name }}
{% endmacro %}


{% macro say() %}
    <h1>你好</h1>
     <h1>你真好</h1>

{% endmacro %}

{% macro show_stus(id, name, age) %}
    学生id:{{ id }}
    学生姓名:{{ name }}
    学生年龄:{{ age }}
{% endmacro %}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值