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安装Imaging报错:The _imaging C module is not installed问题解决方法
Aug 22 Python
Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子
Oct 23 Python
Python使用django框架实现多人在线匿名聊天的小程序
Nov 29 Python
Python实现的爬取网易动态评论操作示例
Jun 06 Python
python3第三方爬虫库BeautifulSoup4安装教程
Jun 19 Python
解决Python 中英文混输格式对齐的问题
Jul 16 Python
python面向对象实现名片管理系统文件版
Apr 26 Python
Python之修改图片像素值的方法
Jul 03 Python
Python如何筛选序列中的元素的方法实现
Jul 15 Python
Python几种常见算法汇总
Jun 02 Python
Python Django中间件使用原理及流程分析
Jun 13 Python
python批量更改目录名/文件名的方法
Apr 18 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
php Mysql日期和时间函数集合
2007/11/16 PHP
PHP以指定字段为索引返回数据库所取的数据数组
2013/06/30 PHP
PHP中对数组的一些常用的增、删、插操作函数总结
2015/11/27 PHP
PHP与Ajax相结合实现登录验证小Demo
2016/03/16 PHP
jQuery 扩展对input的一些操作方法
2009/10/30 Javascript
jquery isType() 类型判断代码
2011/02/14 Javascript
jQuery中 noConflict() 方法使用
2013/04/25 Javascript
js设置function参数默认值(适合没有传参情况)
2014/02/24 Javascript
Bootstrap3 模态框使用实例
2017/02/22 Javascript
自带气泡提示的vue校验插件(vue-verify-pop)
2017/04/07 Javascript
vue.js如何更改默认端口号8080为指定端口的方法
2017/07/14 Javascript
详解基于vue的移动web app页面缓存解决方案
2017/08/03 Javascript
利用jQuery实现简单的拖曳效果实例代码
2017/10/20 jQuery
三种Webpack打包方式(小结)
2018/09/19 Javascript
微信小程序封装自定义弹窗的实现代码
2019/05/08 Javascript
layer弹出层取消遮罩的方法
2019/09/25 Javascript
jstree中的checkbox默认选中和隐藏示例代码
2019/12/29 Javascript
jQuery 移除事件的方法
2020/06/20 jQuery
python实现xlsx文件分析详解
2018/01/02 Python
Python 将pdf转成图片的方法
2018/04/23 Python
Python 爬虫之Beautiful Soup模块使用指南
2018/07/05 Python
Windows 下python3.8环境安装教程图文详解
2020/03/11 Python
Python实现在线批量美颜功能过程解析
2020/06/10 Python
Python如何读写CSV文件
2020/08/13 Python
Python实现爬取网页中动态加载的数据
2020/08/17 Python
Java中compareTo和compare的区别
2016/04/12 面试题
致标枪运动员广播稿
2014/02/06 职场文书
财务支持类个人的自我评价
2014/02/14 职场文书
技校学生个人职业生涯规划范文
2014/03/03 职场文书
个人委托书范本
2014/04/02 职场文书
村庄绿化方案
2014/05/07 职场文书
灵山大佛导游词
2015/02/04 职场文书
2015年爱国卫生月活动总结
2015/03/26 职场文书
2015小学音乐教师个人工作总结
2015/07/21 职场文书
办公室规章制度范本
2015/08/04 职场文书
68句权威创业名言
2019/08/26 职场文书