1. 程式人生 > 程式設計 >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,"regionName": "阿克蘇","cityCode": 652901,"pinYin": "AKESU"
   },{
    "id": 3632,"regionName": "阿拉善","cityCode": 152900,"pinYin": "ALASHAN"
   },{
    "id": 899,"regionName": "安康","cityCode": 610900,"pinYin": "ANKANG"
   },{
    "id": 196,"regionName": "安慶","cityCode": 340800,"pinYin": "ANQING"
   },{
    "id": 758,"regionName": "鞍山","cityCode": 210300,"pinYin": "ANSHAN"
   },{
    "id": 388,"regionName": "安順","cityCode": 520400,"pinYin": "ANSHUN"
   },{
    "id": 454,"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程式設計有所幫助。