flask中写一个基础的sqlHelper类

写一个SQLHelper类:

python 复制代码
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类的例子:

python 复制代码
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查询了博客文章。

相关推荐
belldeep1 小时前
python:reportlab 将多个图片合并成一个PDF文件
python·pdf·reportlab
2401_857622663 小时前
SpringBoot框架下校园资料库的构建与优化
spring boot·后端·php
2402_857589363 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
FreakStudio4 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
丶21364 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
哎呦没4 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一个闪现必杀技5 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )5 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
卷心菜小温6 小时前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug