当前位置:网站首页>Flask one to many database creation, basic addition, deletion, modification and query
Flask one to many database creation, basic addition, deletion, modification and query
2022-07-27 08:25:00 【Csdn__ F】
Common types of database fields
| data type | explain |
|---|---|
| Integer | An integer (*****) |
| String (size) | String with length limit (*****) |
| Text | Some longer unicode Text (*****) |
| DateTime | Expressed as Python datetime Object's Time and date (*****) |
| Float | Store floating point values |
| Boolean | Store Boolean values |
| DECIMAL | Decimal system , Mostly used for price |
One to many model class creation
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# 1. The establishment of a one to many relationship : One party establishes a relationship , Establish foreign keys by multiple parties
# Professional model
class Sub(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32))
# One party defines the relationship , relation Stu Model , Stu Is the model class name ,
# backref The value of is to " In many ways " Used to query " a party " Of
stu = db.relationship('Stu', backref='sub')
# Student model
class Stu(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32))
# Multi party definition of foreign keys , relation sub.id
# sub It is the table name in the database, not the model class name
sub_id = db.Column(db.Integer, db.ForeignKey('sub.id'))
Flask-RESTful Provide RequestParser class , Used to help us verify and transform request data . It is designed to provide simple and unified access Flask.request The entry of any variable in the object
RequestParser() Optional fields for verification parameters ( part )
| Optional parameters | effect | Case study |
|---|---|---|
| type | Parameter type | type=int |
| help | Error message | help=“id Do not be empty ” |
| required | Whether must ( The default is Flase) | required=True |
| choices | A specific value | choices=[‘ male ’,‘ Woman ’] |
| default | If you don't pass , The default value is | default=18 |
Additions and deletions
Inquire about
from flask import Blueprint, jsonify
from models.model import *
from flask_restful import marshal, fields, reqparse
def get(self):
# Get all the data of one party
sub = Sub.query.all()
# Serialized data
# marshal() Method to serialize data directly
# sub: Data to serialize
# {id...}: Fields to serialize
data = marshal(sub, {
"id": fields.Integer,
"name": fields.String,
})
# return json Format response
return jsonify({
'code': 200, 'msg': ' Data acquisition success ', 'data': data})
increase
def post(self):
# structure RequestParser() object
# Instantiation
req = reqparse.RequestParser()
# Add verification field
req.add_argument("name")
# Optional parameters ( part )
# type=int # Parameter type
# help="id Do not be empty " # Error message
# required=True # Whether must
# action="append" # How to deal with parameters with the same name ,append Additional ,store Keep the first
# choices=[' male ',' Woman '] # A specific value
# default=18 # If you don't pass , The default value is
# Start inspection processing
args = req.parse_args()
#
s1 = Sub(
name=args["name"],
)
db.session.add(s1)
# Commit transaction
db.session.commit()
return jsonify({
'code': 200, 'msg': ' Data added successfully '})
modify
def put(self):
req = reqparse.RequestParser()
req.add_argument("id")
args = req.parse_args()
# The first method
# Directly modifying
Sub.query.filter(Sub.id == args["id"]).update(
args
)
# The second method
# First get Then assign value and modify
sub = Sub.query.filter(Sub.id == args["id"]).first()
# assignment
sub.name=args["name"]
# Commit transaction
db.session.commit()
return jsonify({
'code': 200, 'msg': ' Data modified successfully '})
Delete
def delete(self):
req = reqparse.RequestParser()
req.add_argument("id")
args = req.parse_args()
Sub.query.filter(Sub.id == args['id']).delete()
db.session.commit()
return jsonify({
'code': 200, 'msg': ' Data deletion successful '})
边栏推荐
- regular expression
- STM32 small bug summary
- Design and development of GUI programming for fixed-point one click query
- Help send some recruitment. If you are interested, you can have a look
- MCDF顶层验证方案
- Attack and defense world MFW
- Lua iterator
- [golang] golang develops wechat official account web page authorization function
- Solid smart contract development - 3.3-solid syntax control structure
- while Loop
猜你喜欢

The seta 2020 international academic conference will be held soon. Welcome to attend!

【目标检测】YOLOv6理论解读+实践测试VisDrone数据集

IBM3650M4实体机安装VCenter7.0

Node installation and debugging

Vcenter7.0 managing esxi7.0 hosts

Is redis really slowing down?

On Valentine's day, I drew an object with characters!

"PHP Basics" tags in PHP
![[target detection] yolov6 theoretical interpretation + practical test visdrone data set](/img/ad/78835eea4decc15e0981e6561b875f.png)
[target detection] yolov6 theoretical interpretation + practical test visdrone data set

Data extraction 2
随机推荐
Mqtt instruction send receive request subscription
[target detection] yolov6 theoretical interpretation + practical test visdrone data set
JS basic knowledge - daily learning summary ①
OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)
Qt Creator代码风格插件Beautifier
"PHP Basics" PHP statements and statement blocks
Translation character '/b' in C #
[netding cup 2020 rosefinch group]nmap 1 two solutions
You may need an additional loader to handle the result of these loaders.
redis配置文件下载
PHP realizes data interaction with MySQL
Prevent cookies from modifying ID to cheat login
Solve the problem of slow batch insertion of MySQL JDBC data
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation
[MRCTF2020]PYWebsite 1
On data security
IBM3650M4实体机安装VCenter7.0
An ordinary autumn recruitment experience
It's better to be full than delicious; It's better to be drunk than drunk
Use of "PHP Basics" Boolean