当前位置:网站首页>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
边栏推荐
- Vcenter7.0 installation of ibm3650m4 physical machine
- "PHP Basics" tags in PHP
- ERP production operation control Huaxia
- File name wildcard rules for kettle
- The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions
- Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
- Flask project configuration
- You may need an additional loader to handle the result of these loaders.
- Shenzhi Kalan Temple
- Luogu Taotao picks apples
猜你喜欢

说透缓存一致性与内存屏障

开怀一笑

OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)

Introduction to depth first search (DFS)

SSTI template injection

Block, there is a gap between the block elements in the row

"Basic knowledge of PHP" implement mathematical operations in PHP

Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?

Redis configuration file download

After downloading URL loader and specifying the size of the image with limit, the image will not be displayed
随机推荐
Containerd failed to pull private database image (kubelet)
Realization of background channel group management function
OPPO 自研大规模知识图谱及其在数智工程中的应用
Database startup report error_ user_ connect_ times > 0 error
Flask one to many database creation, basic addition, deletion, modification and query
带宽 与 货币
Local Oracle reported ora-12514: tns: the listener cannot recognize the requested service at present
Stored procedure test 1 -- first acquaintance of love
P7 Day1 get to know the flask framework
Use of string type "PHP Basics"
All in one 1329 cells (breadth first search)
"PHP Basics" tags in PHP
Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
Virtual machine cloning
regular expression
Help send some recruitment. If you are interested, you can have a look
XxE & XML vulnerability
You may need an additional loader to handle the result of these loaders.
Management of product pictures
JS rotation chart