当前位置:网站首页>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
边栏推荐
- Apache SSI remote command execution vulnerability
- Breadth first search
- You may need an additional loader to handle the result of these loaders.
- All in one 1319 - queue for water
- What is the real HTAP? (1) Background article
- Map structure
- [BJDCTF2020]EasySearch 1
- Background coupon management
- Eval and assert execute one sentence Trojan horse
- Dasctf2022.07 enabling game password WP
猜你喜欢

Breadth first search

Explain cache consistency and memory barrier

信息化项目风险控制与应用

Use of "PHP Basics" delimiters

Massive data Xiao Feng: jointly build and govern opengauss root community and share a thriving new ecosystem
![[netding cup 2020 rosefinch group]nmap 1 two solutions](/img/fa/b1349cb42b5768b7510217239ba73a.png)
[netding cup 2020 rosefinch group]nmap 1 two solutions

UVM Introduction Experiment 1

Attack and defense World Lottery

Realization of backstage brand management function

说透缓存一致性与内存屏障
随机推荐
如何卸载--奇安信安全终端管理系统
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
Flask project configuration
Login to homepage function implementation
One book 1201 Fibonacci sequence
第2章 前台数据展现
Leetcode56. Consolidation interval
Using ecological power, opengauss breaks through the performance bottleneck
Record a PG master-slave setup and data synchronization performance test process
Realization of specification management and specification option management functions
Have a good laugh
Demo:st05 find text ID information
"Basic knowledge of PHP" implement mathematical operations in PHP
SSTI template injection
Help send some recruitment. If you are interested, you can have a look
vCenter7.0管理Esxi7.0主机
Eval and assert execute one sentence Trojan horse
众昂矿业:新能源行业快速发展,氟化工产品势头强劲
情人节,我用字符画出了一个对象!
while Loop