当前位置:网站首页>Flask Framework Beginner-06-Add, Delete, Modify and Check the Database
Flask Framework Beginner-06-Add, Delete, Modify and Check the Database
2022-08-04 01:35:00 【Liu Moxin】
Learn how to be in the previous sectionflask中连接数据库,使得flaskModel classes in can be mapped one-to-one with tables and fields in the database.This section will specifically describe how to operate on model objects,So as to realize the operation of the database.
小知识点:
CDN:内容分发网络,构建在现有网络基础之上的智能虚拟网络,依靠部署在各地的边缘服务器,通过中心平台的负载均衡'内容分发'、调度等功能模块,Allow users to intercept nearby 所需内容,Increase user access response speed and hit rate
一、查询
1、模型类.query.filter_by 简单查询
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询所有 | 模型类.query.all | select * from user; |
查询一个 | 模型类.query.get() | |
有条件的查询 | 模型类.query.filter_by(字段名 = 值) | select * from user where 字段名=值 |
模型类.query.filter_by(字段名 = 值).firdst() | select * from user where 字段名=值 limit 0,1 |
Except for the model class.query.filter_by(),There is also a model class.query.filter()的查询方式,两者不同的地方在于:
- 模型类.query.filter() Inside is a boolean condition 模型类.query.filter(模型名.字段名 == 值)
- 模型类.query.filter_by() Inside is an equivalent 模型类.query.filter_by(字段名 = 值)
2、模型类.query.filter()
简单查询
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询所有,返回一个列表 | 模型类.query.filter.all() | select * from user; |
Query the first of all results,返回一个对象 | 模型类.query.filter.first() | select * from user where 字段名=值 |
模糊查询
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询User中以t结尾的数据 | User.query.filter(User.username.endswith(‘t’)).all() | select * from User where username like ‘%t’; |
查询User中以t开头的数据 | User.query.filter(User.username.startswith(‘t’)).all() | select * from User where username like ‘t%’; |
查询User中包含t的数据 | User.query.filter(User.username.contains(‘t’)).all() | select * from User where username like ‘%t%’; |
查询User中包含t的数据 | User.query.filter(User.username.like(‘%t%’)).all() | select * from User where username like ‘%t%’; |
Multi-condition judgment query :需要先导入sqlalchemy
from sqlalchemy import or_, and_, not_, __gt__,__lt__,__ge__(gt equal),__le__(le equal)
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询User中username以t结尾或者包含i的所有数据 | User.query.filter(or_(User.username.like(‘t%’),User.username.contains(‘i’))).all() | select * from User where username like ‘%t’ or username like '%i%; |
查询User中username包含i并且rdatetine>2021-12-15 00:00:00的所有数据 | User.query.filter(and_(User.rdatetime. __ gt __ (‘2021-12-15 00:00:00’), User.username.contains(‘i’))).all() | select * from User where username like '%i% and rdatetime>‘2021-12-15 00:00:00’; |
查询User中phone为18176641567的所有数据 | User.query.filter(User.phone.in_([‘18176641567’,‘’,‘’])).all() | seslect * from User where phone in (‘18179641567’,‘’,‘’); |
如果要检索的字段是字符串 (varchar, db.String) :
User.username.startswith('')
User.username.endswith('')
User.username.contains('')
User.username.like('')
User.username.in_(['','',''])
User.username == 'zzz'
If the field to be retrieved is an integer or a date:
User,age.__lt__(18)
User.rdatetime.__gt__('')
User.age.__le__(18)
User.age.__ge__(18)
User.age.between(15,30)
If multiple conditions are retrieved together:
and_
or_
not_
排序 :order_by
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询UserAll data in and return in reverse order | User.query.order_by(-User.id).all() | select * from user desc; |
查询User中包含iAll data and based onrdatetime正序返回 | User.query.filter(User.username.contains(‘i’)).order_by(‘rdatetime’).all() | select * from user where username like '%i% order by rdatetime; |
查询User中包含iAll data and based onrdatetime倒序返回 | User.query.filter(User.username.contains(‘i’)).order_by(-User.rdatetime).all() | select * from user where username like '%i% order by rdatetime desc; |
限制:limit
查询 | 模型类操作 | Corresponding database statement |
---|---|---|
查询User中根据idThe first two data in positive order | User.query.order_by(‘id’).limit(2).all() | select * from User order by id limit 2; |
Skip the first two records before fetchingUsertwo records in | User.query.offset(2).limit(2).all() | select * from User order by id limit 2,4 ; |
二、删除
1、逻辑删除(定义数据库中的表的时候,添加一个字段isdelete,通过此字段控制是否删除)
id = request.args.get('id')
user = User.query.get(id)
user.isdelete = True
db.session.commit()
2、物理删除
id = request.args.get('id')
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
三、更新
id = request.args.get('id')
username = request.args.get('username')
phone = request.args.get('phone')
user = User.query.get(id)
user.phone = phone
user.username = username
db.session.commit()
四、添加
user = User()
user.xxx = xxx
db.session.add(user)
db.session.commit()
五、Example
项目结构
settings.py
class Config:
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/flaskday06'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_ECHO = True
class DevelopmentConfig(Config):
ENV = 'development'
DEBUG = True
class ProductionConfig(Config):
ENV = 'production'
DEBUG = True
apps下的__ init __.py
from flask import Flask
import settings
from apps.user.view import user_bp
from ext import db
def create_app():
app = Flask(__name__,template_folder='../templates',static_folder='../static')
app.config.from_object(settings.DevelopmentConfig)
# 初始化db
db.init_app(app)
app.register_blueprint(user_bp)
return app
ext下的__ init __.py
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
db = SQLAlchemy()
app.py
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from apps.user.models import User
from apps import create_app
from ext import db
app = create_app()
manager = Manager(app = app)
migrate = Migrate(app = app, db = db)
manager.add_command('db',MigrateCommand)
@manager.command
def init():
print('初始化')
if __name__ == '__main__':
manager.run()
models.py
from datetime import datetime
from ext import db
class User(db.Model):
id = db.Column(db.Integer,primary_key = True,autoincrement = True)
username = db.Column(db.String(15),unique=True,nullable=False)
password = db.Column(db.String(64),nullable=False)
phone = db.Column(db.String(11),nullable=False,unique= True)
isdelete = db.Column(db.Boolean,default=False)
rdatetime = db.Column(db.DateTime,default = datetime.now())
def __str__(self):
return self.username
view.py
import hashlib
from flask import Blueprint, request, render_template, url_for
from sqlalchemy import or_, and_, not_
from werkzeug.utils import redirect
from apps.user.models import User
from ext import db
user_bp = Blueprint('user',__name__)
# 注册
@user_bp.route('/register',methods=['POST','GET'])
def register():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
repassword = request.form.get('repassword')
phone = request.form.get('phone')
if password == repassword:
user = User()
user.username = username
user.password = hashlib.md5(password.encode('utf-8')).hexdigest()
user.phone = phone
db.session.add(user)
db.session.commit()
return redirect(url_for('user.user_center'))
return render_template('user/register.html',msg='The user confirms that the password is incorrect!')
return render_template('user/register.html')
# 用户中心
@user_bp.route('/')
def user_center():
users = User.query.filter(User.isdelete == False).all()
return render_template('user/center.html',users = users)
# 登录
@user_bp.route('/login')
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
new_password = hashlib.md5(password.encode('utf-8')).hexdigest()
user_list = User.query.filter_by(username=username)
print(user_list)
for u in user_list:
if u.password == new_password:
return '用户登录成功!'
else:
return render_template('user/login.html',msg='用户名或密码有误!')
print(u)
return 'testing'
return render_template('user/login.html')
# 检索
@user_bp.route('/search')
def search():
keyword = request.args.get('search')
# 查询
user_list = User.query.filter(or_(User.username.contains(keyword),User.phone.contains(keyword)))
return render_template('user/center.html',users=user_list)
# 删除
@user_bp.route('/delete',endpoint='delete')
def user_delete():
id = request.args.get('id')
# 获取该id的用户
user = User.query.get(id)
# 1、逻辑删除
user.isdelete = True
""" # 2、物理删除 db.session.delete(user) """
# 提交
db.session.commit()
return redirect(url_for('user.user_center'))
# 更新
@user_bp.route('/update',endpoint='update',methods=['GET','POST'])
def user_update():
if request.method == 'POST':
id = request.form.get('id')
username = request.form.get('username')
phone = request.form.get('phone')
user = User.query.get(id)
user.phone = phone
user.username = username
db.session.commit()
return redirect(url_for('user.user_center'))
else:
id = request.args.get('id')
user = User.query.get(id)
return render_template('user/update.html',user=user)
@user_bp.route('/test')
def test():
username = request.args.get('username')
user = User.query.filter_by(username=username).first()
print(user.username,user.rdatatime)
user = User.query.filter_by(username=username).last()
print(user.username, user.rdatatime)
return 'test'
@user_bp.route('/select')
def user_select():
# 根据主键查询用户
user = User.query.get(1)
user1 = User.query.filter(User.username == 'tom').all()
user2 = User.query.filter(User.username == 'tom').first()
# 相当于 select * from User where username like 't%';
user_list = User.query.filter(User.username.startswith('t')).all()
user_list2 = User.query.filter(User.username.like('%t%')).all()
user_list3 = User.query.filter(or_(User.username.like('t%'), User.username.contains('i'))).all()
user_list4 = User.query.filter(and_(User.rdatetime>'2021-12-15 00:00:00', User.username.contains('i'))).all()
user_list5= User.query.filter(and_(User.rdatetime.__gt__('2021-12-15 00:00:00'), User.username.contains('i'))).all()
user_list6 = User.query.filter(not_(User.username.contains('i'))).all()
user_list7 = User.query.filter(User.phone.in_(['18179641567','',''])).all()
user_list8= User.query.filter(User.rdatetime.between('2021-12-05 00:00:00','2021-12-15 23:00:00')).all()
user_list9 = User.query.order_by(-User.id).all()
user_list10 = User.query.filter(User.username.contains('i')).order_by('rdatetime').all()
user_list11 = User.query.filter(User.username.contains('i')).order_by(-User.rdatetime).all()
# limit的使用 + offset偏移
user_list12 = User.query.order_by('id').limit(2).all()
usee_list13 = User.query.offset(1).limit(2).all()
return render_template('user/select.html',user=user,user1=user1,user2=user2,user_list=user_list,
user_list2=user_list2,user_list3=user_list3,user_list4=user_list4,user_list5=user_list5,
user_list6=user_list6,user_list7=user_list7,user_list8=user_list8,user_list9=user_list9,
user_list10=user_list10,user_list11=user_list11,user_list12=user_list12,usee_list13=usee_list13)
center.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户中心</title>
<script crossorigin="anonymous" integrity="sha384-nrOSfDHtoPMzJHjVTdCopGqIqeYETSXhZDFyniQ8ZHcVy08QesyHcnOUpMpqnmWq" src="https://lib.baomitu.com/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div><a href="{
{ url_for('user.register') }}">注册</a> <a href="{
{ url_for('user.login') }}">登录</a> <a href="">退出</a> </div>
<div>
<h1>所有用户信息如下:</h1>
搜索: <input type="text" name="search" placeholder="输入用户名或手机号码"><input type="button" value="搜索" id="search">
<br>
{% if users %}
<table border="1" cellspacing="0" width="50%" >
<tr>
<td>序号</td>
<td>用户名</td>
<td>电话</td>
<td>注册时间</td>
<td>操作</td>
</tr>
{% for user in users %}
<tr>
<td>{
{ loop.index }}</td>
<td>{
{ user.username }}</td>
<td>{
{ user.phone }}</td>
<td>{
{ user.rdatetime }}</td>
<td>
<a href="{
{ url_for('user.update') }}?id={
{ user.id }}">更新</a>
<a href="{
{ url_for('user.delete') }}?id={
{ user.id }}">删除</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p style="color:red; font-size: 20px;">当前还没有任何用户,抓紧时间注册吧!!!</p>
{% endif %}
</div>
<script> $('#search').click(function(){
let content = $("input[name='search']").val(); <!-- alert(content);--> location.href = '{
{ url_for('user.search') }}?search='+content }) </script>
</body>
</html>
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action='{
{ url_for("user.register") }}' method="POST">
<input type="text" name="username" placeholder="用户名"><br>
<input type="password" name="password" placeholder="密码"><br>
<input type="password" name="repassword" placeholder="确认密码"><br>
<input type="text" name="phone" placeholder="手机号码"><br>
<input type="submit" value="用户注册" >
</form>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>用户登录</h1>
<p style="color:red">{
{ msg }}</p>
<form action='{
{ url_for("user.login") }}' method="POST">
<input type="text" name="username" placeholder="用户名"><br>
<input type="password" name="password" placeholder="密码"><br>
<input type="submit" value="用户登录" >
</form>
</body>
</html>
select.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
user-----{
{ user }}------{
{ user.username }}-------{
{ user.rdatetime }}
<br>
user1----{
{ user1 }}
<br>
user2-----{
{ user2 }}
<br>
user_list----{
{ user_list | length }}
<br>
user_list2-----{
{ user_list2 | length }}
<br>
user_list3-----{
{ user_list3 | length }}
<br>
user_list4-----{
{ user_list4 | length }}
<br>
user_list5-----{
{ user_list5 | length }}
<br>
user_list6------{
{ user_list6 | length }}
<br>
user_list7------{
{ user_list7 | length }}
<br>
user_list8------{
{ user_list8 | length }}
<br>
user_list9------{
{ user_list9 | length }}
<br>
user_list10-----{
{ user_list10 | length }}
<br>
user_list11------{
{ user_list11 | length }}
<br>
user_list12------{
{ user_list12 | length }}
<br>
user_list13------{
{ user_list13 | length }}
<br>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户更新</title>
</head>
<body>
<h1>用户更新操作</h1>
<form action="{
{url_for('user.update')}}" method="post">
<input type="hidden" name="id" value="{
{ user.id }}">
<p><input type="text" name="username" value="{
{ user.username}}"> </p>
<p><input type="text" name="phone" value="{
{ user.phone}}"> </p>
<p><input type="submit" value="更新用户"> </p>
</form>
</body>
</html>
终端运行
python app.py runserver
运行结果
边栏推荐
- typescript56 - generic interface
- Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
- Analysis of usage scenarios of mutex, read-write lock, spin lock, and atomic operation instructions xaddl and cmpxchg
- typescript52 - simplify generic function calls
- 2022 China Computing Power Conference released the excellent results of "Innovation Pioneer"
- 网络带宽监控,带宽监控工具哪个好
- 114. How to find the cause of Fiori Launchpad routing error by single-step debugging
- HBuilderX的下载安装和创建/运行项目
- Variable string
- flask框架初学-06-对数据库的增删改查
猜你喜欢
随机推荐
《Greenplum构建实时数据仓库实践》简介
DDTL:远距离的域迁移学习
typescript54 - generic constraints
flask框架初学-06-对数据库的增删改查
typescript50-交叉类型和接口之间的类型说明
《The Google File System》新说
FeatureNotFound( bs4.FeatureNotFound: Couldn‘t find a tree builder with the features you requested:
typescript48 - type compatibility between functions
【虚拟户生态平台】虚拟化平台安装时遇到的坑
VR panorama shooting online exhibition hall, 3D panorama brings you an immersive experience
Flask框架初学-05-命令管理Manager及数据库的使用
【store商城项目01】环境准备以及测试
boot issue
多渠道打包
typescript58 - generic classes
jmeter分布式压测
initramfs详解----添加硬盘驱动并访问磁盘
持续投入商品研发,叮咚买菜赢在了供应链投入上
600MHz频段来了,它会是新的黄金频段吗?
pygame 中的transform模块