您好,登录后才能下订单哦!
这期内容当中小编将会给大家带来有关怎么在flask框架中读取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框架中读取json数据了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。