当前位置:网站首页>flask_restful中的输出域(Resource、fields、marshal、marshal_with)
flask_restful中的输出域(Resource、fields、marshal、marshal_with)
2022-07-27 10:05:00 【IT之一小佬】
示例代码:
import json
from datetime import datetime
from flask_restful import Resource, fields, marshal_with, marshal
# 基本例子
resource_fields = {
'name': fields.String,
'address': fields.String,
'date_updated': fields.DateTime(dt_format='rfc822'),
}
class UserInfo(object):
def __init__(self, name, address, date_updated=datetime.now()):
self.name = name
self.address = address
self.date_updated = date_updated
print(UserInfo('dgw', 'beijing'))
print(UserInfo('dgw', 'beijing').name, UserInfo('dgw', 'beijing').address)
print(json.dumps(marshal(UserInfo('dgw', 'beijing'), resource_fields)))
class Todo(Resource):
@marshal_with(resource_fields, envelope='resource')
def get(self, **kwargs):
return UserInfo('dgw', 'beijing')
# 输出域别名
resource_fields2 = {
'open_name': fields.String(attribute='name'),
'address': fields.String,
'date_updated': fields.DateTime(dt_format='rfc822'),
}
print(json.dumps(marshal(UserInfo('dgw', 'beijing'), resource_fields2)))
# # 输出域默认值
class UserInfo2(object):
def __init__(self, address):
self.address = address
resource_fields3 = {
'open_name': fields.String(default='add_dgw'),
'address': fields.String,
'date_updated': fields.DateTime(dt_format='rfc822', default=str(datetime.now())),
}
print(json.dumps(marshal(UserInfo2(address='beijing'), resource_fields3)))
# # 自定义输出域
class UserInfo2(object):
def __init__(self, address, flag, date_updated=datetime.now()):
self.address = address
self.date_updated = date_updated
self.flags = flag
class UrgentItem(fields.Raw):
def format(self, value):
return "Urgent" if value & 0x01 else "Normal"
resource_fields4 = {
'open_name': fields.String(default='add_DGW'),
'address': fields.String,
'date_updated': fields.DateTime(dt_format='rfc822'),
'priority': UrgentItem(attribute='flags'),
}
print(json.dumps(marshal(UserInfo2(address='beijing', flag=0), resource_fields4)))
print(json.dumps(marshal(UserInfo2(address='beijing', flag=1), resource_fields4)))
# # 复杂结构
resource_fields = {'name': fields.String}
resource_fields['address'] = {}
resource_fields['address']['line 1'] = fields.String(attribute='addr1')
resource_fields['address']['line 2'] = fields.String(attribute='addr2')
resource_fields['address']['city'] = fields.String
resource_fields['address']['state'] = fields.String
resource_fields['address']['zip'] = fields.String
data = {'name': 'bob', 'addr1': 'shanghai', 'addr2': '', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
print(json.dumps(marshal(data, resource_fields)))
# 嵌套域
address_fields = {}
address_fields['line 1'] = fields.String(attribute='addr1')
address_fields['line 2'] = fields.String(attribute='addr2')
address_fields['city'] = fields.String(attribute='city')
address_fields['state'] = fields.String(attribute='state')
address_fields['zip'] = fields.String(attribute='zip')
resource_fields = {}
resource_fields['name'] = fields.String
resource_fields['billing_address'] = fields.Nested(address_fields)
resource_fields['shipping_address'] = fields.Nested(address_fields)
address1 = {'addr1': 'qingdao', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
address2 = {'addr1': 'nanjing', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
address3 = {'line 1': 'wuhan', 'line 2': 'tianmen', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
address4 = {'addr1': 'wuhan', 'addr2': 'tianmen', 'city2': 'New York', 'state': 'NY2', 'zip': '11002'}
data1 = {'name': 'bob', 'billing_address': address1, 'shipping_address': address2}
data2 = {'name': 'bob', 'billing_address': address3, 'shipping_address': address4}
print(json.dumps(marshal(data1, resource_fields)))
print(json.dumps(marshal(data2, resource_fields)))
运行结果:

边栏推荐
- 数学推理题:张王李赵陈五对夫妇聚会,见面握手
- Xiandai 004
- 多点双向重发布和路由策略
- Text processing tool in shell, cut [option parameter] filename Description: the default separator is the built-in variable of tab, awk [option parameter] '/pattern1/{action1}filename and awk
- Matlab low-level source code realizes the median filtering of the image (used to eliminate some miscellaneous points on the image)
- File upload vulnerability bypass method
- Sorting out some open source projects of speech recognition
- 语音数据采集-实时语音数据可视化
- gyp ERR! configure error. gyp ERR! stack Error: gyp failed with exit code: 1
- Key points of ES6 class inheritance
猜你喜欢

Oracle resizing data files

How to turn off the application of computer self startup

Sub query of database performance series

Matlab底层源代码实现图像的中值滤波(用于消除图像上一些杂点)

线代004

文件上传漏洞绕过方法

Word2vec principle and application and article similarity (recommended system method)

Xiandai 003

FTP 服务器

Ant advanced -path and fileset
随机推荐
Pyautogui realizes automatic office -rpa small case
Matlab- draw date and duration diagram
mount. Nfs: access denied by server while mounting
安装CUDA失败的情况nsight visual studio edition失败
01_ Movie recommendation (contentbased)_ Object portrait
Pyautogui实现自动化办公-RPA小case
这种动态规划你见过吗——状态机动态规划之股票问题(上)
Switch port mirroring Configuration Guide
Mail server
Xiandai 003
Two architectures of ETL (ETL architecture and ELT Architecture)
语音识别的一些开源项目整理
使用 LSM-Tree 思想基于.NET 6.0 C# 写个 KV 数据库(案例版)
Matlab low-level source code realizes the median filtering of the image (used to eliminate some miscellaneous points on the image)
Matlab-实时编辑器介绍
Basic statement of database operation
sql注入
Robotframework+eclispe environment installation
使用 Kmeans聚类实现颜色的分割
怎样关闭电脑开机自启动的应用