当前位置:网站首页>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 '})
边栏推荐
- 1176 questions of Olympiad in informatics -- who ranked K in the exam
- How to play with the purchase of SAP variant materials? Look at this article and you will understand
- The response of the database interface is very slow
- Virtual machine cloning
- openGauss之TryMe初体验
- Solve the problem of slow batch insertion of MySQL JDBC data
- containerd拉取私库镜像失败(kubelet)
- 如何在qsim查看软件对象的实例?
- Solution to the program design of the sequence structure of one book (Chapter 1)
- How to log in multiple wechat on the computer
猜你喜欢

ERP production operation control Huaxia

pytorch_demo1

UVM入门实验1

Graph node deployment and testing

Solution to the program design of the sequence structure of one book (Chapter 1)

I drew a Gu ailing with characters!

pytorch_ demo1

"PHP Basics" PHP statements and statement blocks

Attack and defense World Lottery

Using ecological power, opengauss breaks through the performance bottleneck
随机推荐
Shenzhi Kalan Temple
I drew a Gu ailing with characters!
Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
Five day travels to Beijing
On Valentine's day, I drew an object with characters!
After installing mysql, docker entered the container and found that he could not log in to MySQL
如何在qsim查看软件对象的实例?
SSTI template injection
STM32 small bug summary
1024 | in the fourth year officially called Menon, the original intention is still there, and continue to move forward
QT creator code style plug-in beautifier
File name wildcard rules for kettle
[target detection] yolov6 theoretical interpretation + practical test visdrone data set
1176 questions of Olympiad in informatics -- who ranked K in the exam
2022/7/26 exam summary
Solve the problem of slow batch insertion of MySQL JDBC data
The response of the database interface is very slow
My senior
借生态力量,openGauss突破性能瓶颈
regular expression