python SQL工具包SQLAlchemy在flask Web应用框架下的基本使用

1. 任务

在 flask 框架下,调用MySQL 数据库。

2. 示例

在安装MySQL 以及 Flask-SQLalchemy python包后,创建文件Database.py:

# -*- coding: utf-8
# !/usr/bin/env python
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)

import datetime
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm import scoped_session, sessionmaker

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///testDB.db"
flaskDB = SQLAlchemy(app)

class UserInfo(flaskDB.Model):
    """
    Database record the query times of each Bilibili Up. 
    """
    __tablename__ = "PaiHangBang"
    # key
    id = Column(Integer, primary_key=True)
    name = Column(String)
    # count = Column(Integer, default=0)
    created_date = Column(DateTime, default=datetime.datetime.now)

    def __repr__(self):
        return "<UserInfo: id:{}, name:{},created_date:{}>".format(
        self.id, self.name, self.created_date)

然后在其他的文件导入这个数据库类UserInfo并且创建:

from Database import flaskDB
flaskDB.create_all()
from Database import UserInfo

admin = UserInfo(name="rosefun")
flaskDB.session.add(admin)
flaskDB.session.commit()
print(UserInfo.query.all())

效果:

  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
[<UserInfo: id:1, name:rosefun,created_date:2021-03-03 11:22:52.007693>]

参考:

  1. flask-sqlalchemy
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页