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统计列表中的重复项出现的次数的方法
Aug 18 Python
Python利用pyHook实现监听用户鼠标与键盘事件
Aug 21 Python
Python格式化css文件的方法
Mar 10 Python
python opencv实现图片旋转矩形分割
Jul 26 Python
Python unittest单元测试框架总结
Sep 08 Python
python生成lmdb格式的文件实例
Nov 08 Python
python+PyQT实现系统桌面时钟
Jun 16 Python
pytorch 实现打印模型的参数值
Dec 30 Python
Ubuntu18.04安装 PyCharm并使用 Anaconda 管理的Python环境
Apr 08 Python
Python3操作读写CSV文件使用包过程解析
Apr 10 Python
使用 django orm 写 exists 条件过滤实例
May 20 Python
如何通过python计算圆周率PI
Nov 11 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 header()函数使用说明
2008/07/10 PHP
跟我学Laravel之请求(Request)的生命周期
2014/10/15 PHP
php实现用手机关闭计算机(电脑)的方法
2015/04/22 PHP
PHP开发制作一个简单的活动日程表Calendar
2016/06/20 PHP
PHP安装GeoIP扩展根据IP获取地理位置及计算距离的方法
2016/07/01 PHP
PHP记录和读取JSON格式日志文件
2016/07/07 PHP
laravel5.6实现数值转换
2019/10/23 PHP
jquery.validate使用攻略 第三部
2010/07/01 Javascript
获取css样式表内样式的js函数currentStyle(IE),defaultView(FF)
2011/02/14 Javascript
javascript表格隔行变色加鼠标移入移出及点击效果的方法
2015/04/10 Javascript
js添加事件的通用方法推荐
2016/05/15 Javascript
简单的js计算器实现
2016/10/26 Javascript
JS常用知识点整理
2017/01/21 Javascript
Extjs gridpanel 中的checkbox(复选框)根据某行的条件不能选中的解决方法
2017/02/17 Javascript
jQuery插件artDialog.js使用与关闭方法示例
2017/10/09 jQuery
JavaScript中arguments和this对象用法分析
2018/08/08 Javascript
详解Vue组件插槽的使用以及调用组件内的方法
2018/11/13 Javascript
超好用的jQuery分页插件jpaginate用法示例【附源码下载】
2018/12/06 jQuery
python中将字典转换成其json字符串
2014/07/16 Python
python实现简单的TCP代理服务器
2014/10/08 Python
python绘图方法实例入门
2015/05/19 Python
Python实现截取PDF文件中的几页代码实例
2019/03/11 Python
Python爬取数据保存为Json格式的代码示例
2019/04/09 Python
pandas 如何分割字符的实现方法
2019/07/29 Python
python numpy存取文件的方式
2020/04/01 Python
python 装饰器的基本使用
2021/01/13 Python
德国化妆品和天然化妆品网上商店:kosmetikfuchs.de
2017/06/09 全球购物
试解释COMMIT操作和ROLLBACK操作的语义
2014/07/25 面试题
计算机售后服务承诺书
2014/05/30 职场文书
小学生竞选班干部演讲稿(5篇)
2014/09/12 职场文书
2014年语文教研组工作总结
2014/12/06 职场文书
股东大会通知
2015/04/24 职场文书
2015年维修工作总结
2015/04/25 职场文书
小时代观后感
2015/06/10 职场文书
mysql使用FIND_IN_SET和group_concat两个方法查询上下级机构
2022/04/20 MySQL
Java实现超大Excel文件解析(XSSF,SXSSF,easyExcel)
2022/07/15 Java/Android