flask框架json数据的拿取和返回操作示例


Posted in Python onNovember 28, 2019

本文实例讲述了flask框架json数据的拿取和返回操作。分享给大家供大家参考,具体如下:

json数据结构:以套票票网站的城市数据为例,拿到数据莫慌,

1 先分析数据结构,有几个大的字段(‘returnCode'和‘retuenValue'字段,只有一个字段作为定义,另一个字段作为保留(无需处理)

2 键表----> 拆分'returnValue‘确定数据库表结构,('A‘[]城市首字母表 和  城市具体信息字段{}表)

3 将拿到的数据拆分插入到数据库中

4 将数据库的数据以JSON 的形式返回给用户

(a)拿到的数据:

}
 "returnCode": "0",
 "returnValue": {
  "A": [
   {
    "id": 3643,
    "parentId": 0,
    "regionName": "阿坝",
    "cityCode": 513200,
    "pinYin": "ABA"
   },
   {
    "id": 3090,
    "parentId": 0,
    "regionName": "阿克苏",
    "cityCode": 652901,
    "pinYin": "AKESU"
   },
   {
    "id": 3632,
    "parentId": 0,
    "regionName": "阿拉善",
    "cityCode": 152900,
    "pinYin": "ALASHAN"
   },
   {
    "id": 899,
    "parentId": 0,
    "regionName": "安康",
    "cityCode": 610900,
    "pinYin": "ANKANG"
   },
   {
    "id": 196,
    "parentId": 0,
    "regionName": "安庆",
    "cityCode": 340800,
    "pinYin": "ANQING"
   },
   {
    "id": 758,
    "parentId": 0,
    "regionName": "鞍山",
    "cityCode": 210300,
    "pinYin": "ANSHAN"
   },
   {
    "id": 388,
    "parentId": 0,
    "regionName": "安顺",
    "cityCode": 520400,
    "pinYin": "ANSHUN"
   },
   {
    "id": 454,
    "parentId": 0,
    "regionName": "安阳",
    "cityCode": 410500,
    "pinYin": "ANYANG"
   }
  ],

B....C....D....Z省略其他大写字母开头的城市,以A开头的城市名为例

(b)表结构,建立外键models.py

from App.ext import db
#定义城市名大写字母类,在数据的最外层
class Letter(db.Model):
  id = db.Column(db.Integer,primary_key =True,autoincrement=True)
  letter = db.Column(db.String(8),unique=True,nullable=False)
#定义城市类,嵌套层
class City(db.Model):
  id = db.Column(db.Integer,primary_key = True,autoincrement = True)
  parentId = db.Column(db.Integer,nullable = False,defaut=0)
  regionName = db.Column(db.String(30),nullable = False)
  cityCode = db.Column(db.Integer)
  pinYin = db.Column(db.String(128))
  #建立外键‘首字母'
  first_letter = db.Column(db.String(8),db.ForeignKey(Letter.letter))

(c)addcities.py插入数据:

from flask_restful.representations import json
from sqlalchemy.dialects.mysql import pymysql
def add_cities():
#链接数据库
  db = pymysql.Connect(host= '10.0.118.135',user = 'root',password ='xxxxxxx',database = 'tpp6666',port = 3306)
  cursor = db.cursor()
  #读取拿到的数据,遍历数据
  with open('citylist.json')as cl:
    returnValue = json.load(cl).get('returnValue')
    for key in returnValue:
      for city in returnValue.get(key):
         db.begin()
         #插入数据,以每一个大写字母为一个字段插入,以字典的形式
         cursor.execute(
           'insert into city(id,parentId,regionName,cityCode,pinYin,first_letter) values({},{},"{}",{},"{}","{}");'.format(
             city['id'], city['parentId'], city['regionName'], city['cityCode'], city['pinYin'], key))
         db.commit()
if __name__ == '__main__':
  add_cities()

(d)CityAPI.py读取数据并以JSON的形式返回 :

from flask_restful import Resource, fields, marshal_with
from App.models import Letter, City
#字段的格式化:
city_fields = {
  'id': fields.Integer,
  '父编号': fields.Integer(attribute='parentId'),#起别名attribute
  '名称': fields.String(attribute='regionName'),
  '拼音': fields.String(attribute='pinYin'),
  '城市编码': fields.Integer(attribute='cityCode'),
  '首字母': fields.String(attribute='first_letter')
}
value_fields = {
  'A': fields.List(fields.Nested(city_fields)),
  'B': fields.List(fields.Nested(city_fields)),
  'C': fields.List(fields.Nested(city_fields)),
  'D': fields.List(fields.Nested(city_fields)),
  'E': fields.List(fields.Nested(city_fields)),
  'F': fields.List(fields.Nested(city_fields)),
  'G': fields.List(fields.Nested(city_fields)),
  'H': fields.List(fields.Nested(city_fields)),
  'J': fields.List(fields.Nested(city_fields)),
  'K': fields.List(fields.Nested(city_fields)),
  'L': fields.List(fields.Nested(city_fields)),
  'M': fields.List(fields.Nested(city_fields)),
  'N': fields.List(fields.Nested(city_fields)),
  'P': fields.List(fields.Nested(city_fields)),
  'Q': fields.List(fields.Nested(city_fields)),
  'R': fields.List(fields.Nested(city_fields)),
  'S': fields.List(fields.Nested(city_fields)),
  'T': fields.List(fields.Nested(city_fields)),
  'W': fields.List(fields.Nested(city_fields)),
  'X': fields.List(fields.Nested(city_fields)),
  'Y': fields.List(fields.Nested(city_fields)),
  'Z': fields.List(fields.Nested(city_fields)),
}
result_fields = {
  'returnCode': fields.Integer,
  'returnValue': fields.Nested(value_fields)
}
#整体逻辑定义都在这里:
@marshal_with是flask内置的Json序列化的方法,

在Django里json序列化是json.dumps()

class CityResrouce(Resource):
  @marshal_with(result_fields)
  def get(self):
    #定义外层字段为空字典{},存放数据
    returnValue = {}
    # 拿到所有的首字母
    letters = Letter.query.all()
    for letter in letters:
      # 根据首字母拿到每个首字母对应的所有城市
      # filter拿到的结果是一个BaseQuery对象。
      # 如果直接答应BaseQuery对象,它会输出SQL语句
      # 如果想要打印BaseQuery里的所有数据,调用all()方法可以拿到BaseQuery里的所有数据
      cities = City.query.filter(City.first_letter == letter.letter)
      # dict = {letter.letter: cities}
      # print(dict)
      returnValue[letter.letter] = cities.all()
    return {'returnCode': 0, 'returnValue': returnValue}

(d)api__init__.py:

from flask_restful import Api
from App.Apis.CityAPI import CityResrouce
from App.Apis.UserAPI import UerResource
api = Api()
def init_api(app):
  api.init_app(app=app)
api.add_resource(CityResrouce, '/cities/')

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

Python 相关文章推荐
Python语言编写电脑时间自动同步小工具
Mar 08 Python
Python continue语句用法实例
Mar 11 Python
Python里隐藏的“禅”
Jun 16 Python
在Debian下配置Python+Django+Nginx+uWSGI+MySQL的教程
Apr 25 Python
解决python3爬虫无法显示中文的问题
Apr 12 Python
Python绘制并保存指定大小图像的方法
Jan 10 Python
在Python中构建增广矩阵的实现方法
Jul 01 Python
Pandas0.25来了千万别错过这10大好用的新功能
Aug 07 Python
python画微信表情符的实例代码
Oct 09 Python
Python 实现敏感目录扫描的示例代码
May 21 Python
Python流程控制语句的深入讲解
Jun 15 Python
python xlwt模块的使用解析
Apr 13 Python
Python 生成一个从0到n个数字的列表4种方法小结
Nov 28 #Python
django 框架实现的用户注册、登录、退出功能示例
Nov 28 #Python
python 变量初始化空列表的例子
Nov 28 #Python
在Python中预先初始化列表内容和长度的实现
Nov 28 #Python
python使用 cx_Oracle 模块进行查询操作示例
Nov 28 #Python
在python中创建指定大小的多维数组方式
Nov 28 #Python
python3.x 生成3维随机数组实例
Nov 28 #Python
You might like
《猛禽小队》:DC宇宙的又一超级大烂片
2020/04/09 欧美动漫
PHP实现批量修改文件后缀名的方法
2015/07/30 PHP
浅谈php中变量的数据类型判断函数
2017/03/04 PHP
js资料toString 方法
2007/03/13 Javascript
ExtJS 2.0实用简明教程 之Border区域布局
2009/04/29 Javascript
JS 实现双色表格实现代码
2009/11/24 Javascript
cument.execCommand()用法深入理解
2012/12/04 Javascript
$.get获取一个文件的内容示例代码
2013/09/11 Javascript
js中的scroll和offset 使用比较的实例与分析
2013/09/29 Javascript
jQuery实现div随意拖动的实例代码(通用代码)
2016/01/28 Javascript
javascript每日必学之继承
2016/02/23 Javascript
jQuery 选择同时包含两个class的元素的实现方法
2016/06/01 Javascript
ReactJs快速入门教程(精华版)
2016/11/28 Javascript
JavaScript 事件对内存和性能的影响
2017/01/22 Javascript
JavaScript数据结构学习之数组、栈与队列
2017/05/02 Javascript
详解vue mint-ui源码解析之loadmore组件
2017/10/11 Javascript
对vue中methods互相调用的方法详解
2018/08/30 Javascript
js中位运算的运用实例分析
2018/12/11 Javascript
手写Vue弹窗Modal的实现代码
2019/09/11 Javascript
vue使用keep-alive实现组件切换时保存原组件数据方法
2020/10/30 Javascript
[01:14:10]2014 DOTA2国际邀请赛中国区预选赛 SPD-GAMING VS Orenda
2014/05/22 DOTA
python Django批量导入不重复数据
2016/03/25 Python
python 读取竖线分隔符的文本方法
2018/12/20 Python
Python-copy()与deepcopy()区别详解
2019/07/12 Python
python字符串替换re.sub()方法解析
2019/09/18 Python
基于python requests selenium爬取excel vba过程解析
2020/08/12 Python
python Timer 类使用介绍
2020/12/28 Python
10分钟理解CSS3 Grid布局
2018/12/20 HTML / CSS
幼教毕业生自我鉴定
2014/01/12 职场文书
《诚实与信任》教学反思
2014/04/10 职场文书
教师考核评语
2014/04/28 职场文书
购房协议书范本(无房产证)
2014/10/07 职场文书
公司租房协议书
2014/10/14 职场文书
解析python中的jsonpath 提取器
2022/01/18 Python
SQL Server数据库查询出现阻塞之性能调优
2022/04/10 SQL Server
Go语言编译原理之变量捕获
2022/08/05 Golang