• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

flask写基础的sqlHelper类

武飞扬头像
菜鸟小超
帮助1

学新通

写一个SQLHelper类:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class SQLHelper:

    @staticmethod
    def add(record):
        db.session.add(record)
        return SQLHelper.session_commit()

    @staticmethod
    def add_all(records):
        db.session.add_all(records)
        return SQLHelper.session_commit()

    @staticmethod
    def delete(record):
        db.session.delete(record)
        return SQLHelper.session_commit()

    @staticmethod
    def update():
        return SQLHelper.session_commit()

    @staticmethod
    def query_all(model):
        return model.query.all()

    @staticmethod
    def query_by_id(model, record_id):
        return model.query.get(record_id)

    @staticmethod
    def query_by_field(model, **kwargs):
        return model.query.filter_by(**kwargs).all()

    @staticmethod
    def session_commit():
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            reason = str(e)
            return reason

在这个扩展的SQLHelper类中,我们添加了以下几个方法:

  • add_all():一次性添加多条记录到数据库。
  • query_all():获取表中所有的记录。
  • query_by_id():根据ID查询记录。
  • query_by_field():根据字段查询记录。

这个类提供了更全面的数据库操作,但是请注意,根据你的实际需求,你可能需要添加更多的方法。

下面是如何使用这个SQLHelper类的例子:

from flask import Flask, request
from models import Post
from sqlhelper import SQLHelper

@app.route('/add_post', methods=['POST'])
def add_post():
    title = request.form.get('title')
    content = request.form.get('content')
    post = Post(title=title, content=content)
    SQLHelper.add(post)
    return 'Post added successfully!', 200

@app.route('/get_post', methods=['GET'])
def get_post():
    post_id = request.args.get('id')
    post = SQLHelper.query_by_id(Post, post_id)
    if post:
        return f'Title: {post.title}, Content: {post.content}', 200
    else:
        return 'Post not found!', 404

在这个例子中,我们不仅添加了博客文章,还根据文章的id查询了博客文章。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfifcb
系列文章
更多 icon
同类精品
更多 icon
继续加载