当前位置:网站首页>Day5 - Flame restful request response and Sqlalchemy Foundation
Day5 - Flame restful request response and Sqlalchemy Foundation
2022-07-27 08:29:00 【qishaoawei】
Request parsing
RequestParser Processing requests
In the project created by Yiying
from flask import Flask
from views.user import user_bp # Import blueprint objects from blueprint files
# establish Flask example
app=Flask(__name__)
app.register_blueprint(user_bp) # Registered blueprint
if __name__ == '__main__':
app.run()
Storing class py file
from flask import Blueprint, jsonify
# url_prefix # Specify the prefix of all routes under the current blueprint
user_bp=Blueprint('user_bp',__name__,url_prefix='/user')
from flask_restful import Api,Resource,reqparse # Requestor Guide Package
api=Api(user_bp)
class Users(Resource):
def get(self):
#1. Instantiate the requester object
req=reqparse.RequestParser()
# 2. Add the data you want
# required=True Required help Prompt information
req.add_argument('a',required=True,help=' Required ')
# default The default is ...
req.add_argument('c',default='000')
#3. Check the data
args=req.parse_args()
print(args)
return 'sss'
api.add_resource(Users,'/users')
Return response 

req.add_argument(…) Detailed explanation of method parameters . Extra conditions can be added
for example
# Optional parameters ( part )
# type=int # Parameter type
# help=" Do not be empty " # Error message Fill in the prompt at will
# required=True # True Must fill in Flase You don't have to fill in
# action="append" # How to deal with parameters with the same name ,append Additional ,store Keep the first
# choices=[' male ',' Woman '] # A specific value You can only write what it contains
# default=18 # If you don't pass , The default value is
# type: Describe the type that the parameter should match , have access to python The standard type of : str or int
location: Describe where the parameter should appear in the request data
# Request body
parser.add_argument('name', type=int, location='form')
# Query parameters
parser.add_argument('PageSize', type=int, location='args')
# Request header
parser.add_argument('User-Agent', location='headers')
# cookie in
parser.add_argument('session_id', location='cookies')
# json In the data
parser.add_argument('user_id', location='json')
# Upload files
parser.add_argument('picture', location='files')
# Specify multiple places
parser.add_argument('text', location=['headers', 'json'])
Serializer
from flask import Blueprint,jsonify,request,json
from flask_restful import Api,Resource,marshal,fields
from models.mobel import Classify,Mcd,db
good_dp=Blueprint('good_dp',__name__,url_prefix='/goods')
api=Api(good_dp)
class GoodView2(Resource):
def get(self):
id=request.args.get('id')
m_info=Mcd.query.filter(Mcd.classify_id==id).all()
m_list=marshal(m_info,{
'name': fields.String, # character string
'price': fields.Float, # floating-point
'img': fields.String,
'classify_id': fields.Integer, # plastic
})
return jsonify({
'code':200,'msg':' To be successful ','goods':m_list})
api.add_resource(GoodView2,'/goos')
ORM And Flask-SQLAlchemy Expand
First create the configuration item of the database Linked database
install Flask-SQLAlchemy
pip install flask-sqlalchemy
Create a settings Create in a folder config.py file
Configure it inside
# Database configuration items
class DefaultConfig:
# Database type + Database operation engine :// user name : password @ Host name : port / Database name
SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:mysql password @127.0.0.1:3306/ Database name '
SQLALCHEMY_TRACK_MODIFICATIONS = False # Tracking data modification signals
SQLALCHEMY_ECHO = True # Whether to print out on the console sql sentence
Create a models Create in a folder model.py File is used to write model classes
from flask_sqlalchemy import SQLAlchemy # Guide pack
db=SQLAlchemy() # Instantiate database objects
# Create a model class
# If it is a model class , Must inherit db.Model
class UserModel(db.Model):
id=db.Column(db.Integer,primary_key=True,autoincrement=True,comment='ID')
name=db.Column(db.String(32),nullable=False,default='',comment=' user name ')
password=db.Column(db.String(64),nullable=False,default='',comment=' password ')
sex=db.Column(db.Boolean,nullable=False,default=True,comment=' Gender 0 male ,1 Woman ')
In instantiation flask Of py File to load configuration and let flask The project has a relationship with the database object
from flask import Flask
from views.user import user_bp # Import blueprint objects from blueprint files
from views.order import order_bp
from models.model import db # Import the instantiated database object
from settings.config import DefaultConfig
# establish Flask example
app=Flask(__name__)
app.register_blueprint(order_bp) # Registered blueprint
app.config.from_object(DefaultConfig) # Load the configuration
db.init_app(app) # initialization app Give Way flask The project has a relationship with the database object
if __name__ == '__main__':
app.run()
Create one in the root directory manage.py File migration
from flask_script import Manager #Manager Class operation is to run the file from the command line , Add some commands
from app import app # Import app
from models.model import db # Import the instantiated database object
from flask_migrate import Migrate,MigrateCommand # Import migration classes and migration command classes
manage=Manager(app) # The instance generates the management object of the command line
migrate=Migrate(app,db) # Generate migration objects For data migration
manage.add_command('db',MigrateCommand) # Add the migration command to the management object
# Pay attention to start it when it is written
if __name__ == '__main__':
manage.run() # Start the manager
stay python The terminal runs the command to migrate
# Initialize migration file # initialization , It only needs to be initialized once
python manage.py db init
# Generate migration file
python manage.py db migrate
# Perform the migration
python manage.py db upgrade
# Migration completed
Add, delete, change and check operation
stay order.py Write blueprints
increase
from flask import Blueprint
from flask_restful import Api,Resource,marshal,fields
from models.model import UserModel # Import model classes
from models.model import db # Import the instantiated database object
order_bp=Blueprint('order_dp',__name__,url_prefix='/order')
api=Api(order_bp)
class OrderView(Resource):
def get(self):
# Add data
u1=UserModel(
name=' Zhang San ',
password='123456',
sex=False,
)
u2=UserModel(
name=' Zhang Si ',
password='123456',
sex=True,
)
# db.session.add(u1) # Add a piece of data
db.session.add_all([u1,u2]) # Add more than one
# Be careful : Add data , Both data modification and data deletion require transaction submission
db.session.commit()
return 'order_dp'
api.add_resource(OrderView,'/order')
View the data
class OrderView(Resource):
def get(self):
# Look at all the data
query_get=UserModel.query.all()
print(query_get)
# Look at a piece of data
#query_get = UserModel.query.first()
# ## According to the query conditions , View the data
# query_get=UserModel.query.filter_by(name=' Zhang San ').first()
return marshal(query_get,{
'name':fields.String,
'password':fields.String,
'sex':fields.Integer
})
Modifying data
Be careful : Add data , Both data modification and data deletion require transaction submission
class OrderView(Resource):
def get(self):
# Modifying data
UserModel.query.filter_by(name=' Zhang San ').update({
'sex':True # What to modify
})
# Be careful : Add data , Both data modification and data deletion require transaction submission
db.session.commit()
Delete data
Be careful : Add data , Both data modification and data deletion require transaction submission
class OrderView(Resource):
def get(self):
# Delete data # Delete the data whose name is Zhang San
UserModel.query.filter_by(name=' Zhang San ').delete()
db.session.commit()
The field type of the database
Integer An integer ()
String (size) String with length limit () # Remember to put a limit on the length in brackets
Text Some longer unicode Text ()
DateTime Expressed as Python datetime Object's Time and date (****)
Float Store floating point values
Boolean Store Boolean values
PickleType Stored as a persistent Python object
LargeBinary Store an arbitrarily large binary data
边栏推荐
- [netding cup 2020 Qinglong group]areuserialz (buuctf)
- 第2章 前台数据展现
- IBM3650M4实体机安装VCenter7.0
- 缓存一致性与内存屏障
- Use of string type "PHP Basics"
- Map structure
- Design and development of GUI programming for fixed-point one click query
- Plato farm is expected to further expand its ecosystem through elephant swap
- 说透缓存一致性与内存屏障
- 众昂矿业:新能源行业快速发展,氟化工产品势头强劲
猜你喜欢

Download and usage of sequel Pro

Fluent rendering mechanism - GPU thread rendering

如何在qsim查看软件对象的实例?

Is redis really slowing down?

File name wildcard rules for kettle
![[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation](/img/44/52c7dc6871fd43223eadfd394e159e.png)
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation

Flask project configuration

Use of "PHP Basics" delimiters

1024 | in the fourth year officially called Menon, the original intention is still there, and continue to move forward

"Intermediate and advanced test questions": what is the implementation principle of mvcc?
随机推荐
Block, there is a gap between the block elements in the row
Database startup report error_ user_ connect_ times > 0 error
Flask one to many database creation, basic addition, deletion, modification and query
2022-07-26 group 4 abstract classes and interfaces
带宽 与 货币
On Valentine's day, I drew an object with characters!
Functions and arrow functions
Set set
JS basic knowledge - daily learning summary ①
Node installation and debugging
Iterators and generators
One book 1201 Fibonacci sequence
First experience of tryme in opengauss
Record a PG master-slave setup and data synchronization performance test process
[target detection] yolov6 theoretical interpretation + practical test visdrone data set
Redis configuration file download
"Intermediate and advanced test questions": what is the implementation principle of mvcc?
Flutter 渲染机制——GPU线程渲染
It's better to be full than delicious; It's better to be drunk than drunk
Binglog backup data