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

 更新时间:2019年11月28日 10:18:38   作者:@溪竹  
这篇文章主要介绍了flask框架json数据的拿取和返回操作,结合实例形式分析了flask框架针对json格式数据的解析、数据库操作与输出等相关操作技巧,需要的朋友可以参考下

本文实例讲述了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 合并/拆分Excel的实现示例

    Python 合并/拆分Excel的实现示例

    有时对于多个工作表需要进行合并或拆分,以便进行浏览总结,本文主要介绍了Python 合并/拆分Excel的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • Django处理Ajax发送的Get请求代码详解

    Django处理Ajax发送的Get请求代码详解

    在本篇文章里小编给大家整理了关于Django处理Ajax发送的Get请求代码知识点,有需要的朋友们参考学习下。
    2019-07-07
  • python实现计算器功能

    python实现计算器功能

    这篇文章主要为大家详细介绍了python实现计算器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • 对TensorFlow中的variables_to_restore函数详解

    对TensorFlow中的variables_to_restore函数详解

    今天小编就为大家分享一篇对TensorFlow中的variables_to_restore函数详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • 一行代码python实现文件共享服务器

    一行代码python实现文件共享服务器

    这篇文章主要介绍了一行代码python实现文件共享服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • python 多线程死锁问题的解决方案

    python 多线程死锁问题的解决方案

    这篇文章主要介绍了python 多线程死锁问题的解决方案,帮助大家更好的理解和学习python 锁,感兴趣的朋友可以了解下
    2020-08-08
  • 基于Tensorflow使用CPU而不用GPU问题的解决

    基于Tensorflow使用CPU而不用GPU问题的解决

    今天小编就为大家分享一篇基于Tensorflow使用CPU而不用GPU问题的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • python文件编写好后如何实践

    python文件编写好后如何实践

    在本篇文章里小编给大家分享了关于python文件编写好后如何实践的相关内容,需要的朋友们可以参考下。
    2020-07-07
  • django query模块

    django query模块

    这篇文章主要介绍了django query模块,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • python爬虫开发之Beautiful Soup模块从安装到详细使用方法与实例

    python爬虫开发之Beautiful Soup模块从安装到详细使用方法与实例

    这篇文章主要介绍了python爬虫开发之Beautiful Soup模块详细使用方法与实例,需要的朋友可以参考下
    2020-03-03

最新评论