flask-web分页和上传图片

效果图
编辑页面
flask00.png

一、分页

  • paginate(self, page=None, per_page=None, error_out=True, max_per_page=None)
    一般就传前两个参数就行
@blue.route('/all_stu/')
def all_stu():
    if request.method == 'GET':
        # 从url中获取page参数
        page = int(request.args.get('page', 1))
        pg = Student.query.paginate(page, 5)
        # 获取当页参数
        stus = pg.items
        return render_template('stus.html', stus=stus, pg=pg)

然后将pg和stus传入html模板文件解析即可

<table>
        <thead>
	        <th>编号</th>
	        <th>姓名</th>
	        <th>年龄</th>
        </thead>

        <tbody>
        {% for stu in stus %}
        <tr>
            <td>{{ loop.index}}</td>
            <td>{{ stu.s_name}}</td>
            <td>{{ stu.s_age }}</td>
        </tr>

        {% endfor %}
        </tbody>

</table>
    <p>当前第{{ pg.page }}页,共{{ pg.pages }}页</p>
    {% if pg.has_prev %}
    <a href="{{ url_for('app.all_stu')}}?page={{ pg.prev_num}}">上一页</a>
    {% endif %}

    {% for i in pg.iter_pages() %}
        {% if i %}
        <a href="{{ url_for('app.all_stu')}}?page={{i}}">{{i}}</a>
        {% else %}
            ...
        {% endif %}
    {% endfor %}

    {% if pg.has_next %}
    <a href="{{ url_for('app.all_stu')}}?page={{ pg.next_num}}">下一页</a>
    {% endif %}

二、关联模型

  • 一对多
    在一个表中定义一个外键(多的一方)
    db.ForeignKey(‘关联表名.id’) 例如:
g_id = db.Column(db.Integer, db.ForeignKey('grade.id'), nullable=True)

另一个表定义一个关联字段(为一的一方)
关联字段db.relatonship(‘关联的模型名’,backref=‘反向引用参数’) 例如:

# 定义了一个关联关系字段,和反向引用backref参数
s_g = db.relationship('Student', backref='g')
  • 多对多
    定义外键字段是通过中间表,db.Table(表名,子段)
    关联字段db.relationship(‘关联的模型名’,secondary=‘中间表’,backref=‘反向引用参数’)
    relationship定义的字段,可以放在任意一个模型中
s_c = db.Table('s_c',
               db.Column('s_id', db.Integer, db.ForeignKey('student.id')),
               db.Column('c_id', db.Integer, db.ForeignKey('course.id'))
               )

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    c_name = db.Column(db.String(10), unique=True, nullable=False)
    stu = db.relationship('Student', secondary=s_c, backref='cou')

上传图片

  • 视图函数
@blue.route('/edit_stu/<int:id>/', methods=['GET','POST'])
def edit_stu(id):
    if request.method == 'GET':
        stus = Student.query.get(id)
        return render_template('edit.html',stus=stus)
    if request.method == 'POST':
        # 接受图片,并保存图片
        icon = request.files.get('image')
        # 获取项目的根路径
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # 获取媒体文件的路径
        STATIC_DIR = os.path.join(BASE_DIR, 'static')
        MEDIA_DIR = os.path.join(STATIC_DIR, 'media')
        # 随机生成图片名称
        filename = str(uuid.uuid4())
        a = icon.mimetype.split('/')[-1:][0]
        name = filename + '.' + a
        print(name)
        # 拼接图片地址
        path = os.path.join(MEDIA_DIR, name)
        # 保存
        icon.save(path)
        print(icon)
        #修改用户的头像icon字段
        stu = Student.query.get(id)
        stu.icon = name
        stu.save()
        # 重定向
        return redirect(url_for('app.all_stu'))
  • stus.html文件增加图片和编辑的标签
<td><img src="/static/media/{{ stu.icon }}" style="width: 100px"></td>
<td><a href="{{ url_for('app.edit_stu',id=stu.id)}}">编辑</a></td>
  • edit.html 文件内容如下:
{% extends 'base_main.html' %}

{% block content %}

<form action="" method="post" enctype="multipart/form-data">
    <p>姓名:{{stus.s_name}}</p>
    <p>头像:<input type="file" name="image"></p>
    <p><input type="submit" value="提交"></p>
</form>

{% endblock %}
发布了53 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42874994/article/details/86630285