频道栏目
首页 > 资讯 > 其他综合 > 正文

在flask中json数据的拿取和返回操作实例

18-07-20        来源:[db:作者]  
收藏   我要投稿

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}
相关TAG标签
上一篇:MySQL大表数据归档问题的解决办法
下一篇:MySql用case...when..THEN..endcase实现获取星期名存储过程的代码实例
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站