2.3、 建立模型以及对应的CRUD操作
在本节中,创建了USER用户类
和BLOG博文类
两个对象类,并实现了其基本的增删改查的操作。
# flaskr/models.py
from flask import g
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column,Integer,String,TIMESTAMP,ForeignKey,Text
from werkzeug.security import check_password_hash,generate_password_hash
from sqlalchemy.exc import IntegrityError
Base:SQLAlchemy = g.db
# 在此文件中创建对应的模型
# 创建用户类
class User(Base.Model):
__tablename__ = "user"
id = Column(Integer,primary_key=True,autoincrement=True)
username = Column(String(20),nullable=True,unique=True)
password_hash = Column(String(255),nullable= True)
# 生成hash密码
@staticmethod
def hash_password(password):
return generate_password_hash(password)
# 验证密码
def verify_password(self,password):
return check_password_hash(self.password_hash,password)
# 创建用户
@classmethod
def create(cls,username,password):
if cls.read_by_username(username) is None:
user = cls(username = username,password_hash = cls.hash_password(password))
Base.session.add(user)
Base.session.commit()
return user
raise IntegrityError(None,None,None)
# 根据用户的id来读取用户
@classmethod
def read_by_id(cls,user_id):
return cls.query.filter_by(id = user_id).first()
#根据用户名来读取用户
@classmethod
def read_by_username(cls,user_name):
return cls.query.filter_by(username = user_name).first()
# 删除用户
@classmethod
def delete_user(cls,user_id):
user:User = cls.read_by_id(id=user_id)
if user:
Base.session.delete(user)
Base.session.commit()
return True
return False
# 更新密码
def update_password(self,new_pwd):
self.password_hash = self.hash_password(new_pwd)
try:
Base.session.merge(self)
Base.session.commit()
except LookupError:
return False
return True
# 创建博文类
class Blog(Base.Model):
__tablename__ = 'blog'
id = Column(Integer,primary_key=True,autoincrement=True)
author_id = Column(Integer,ForeignKey("user.id"),nullable=True)
created = Column(TIMESTAMP,nullable=True,default=Base.func.now())
title = Column(String(50),nullable=True)
body = Column(Text,nullable=True)
# 根据用户的id来获取post
@classmethod
def read_by_authorId(cls,author_id):
return cls.query.filter_by(id=author_id).first()
# 根据博文id来获取对应的内容
@classmethod
def read_by_blogId(cls,blog_id):
return cls.query.filter_by(id=blog_id).first()
# 创建博文
@classmethod
def create(cls,author_id,title,body):
blog = cls(author_id=author_id,title=title,body=body)
try:
Base.session.add(blog)
Base.session.commit()
except IntegrityError:
return None
return blog
# 更新博文内容
def update(self,new_title,new_body):
self.title = new_title
self.body = new_body
try:
Base.session.merge(self)
Base.session.commit()
except LookupError:
return False
return True
# 根据Id来删除博文
@classmethod
def delete_blog(cls,id):
blog:Blog = cls.read_by_blogId(id)
if blog:
Base.session.delete(blog)
Base.session.commit()
return True
return False
# 读取数据库中的所有博文
def read_all_blog():
return list(Base.session.query(Blog,User).join(Blog,User.id == Blog.author_id).all())
标签:return,CRUD,博客,Base,2.3,password,True,id,cls From: https://www.cnblogs.com/leo130-blogs/p/18179005