Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
hebingchang committed Feb 15, 2017
0 parents commit 4cd5ea1
Show file tree
Hide file tree
Showing 10 changed files with 342 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .idea/AirChina.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/markdown-navigator/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 68 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file added README.md
Empty file.
115 changes: 115 additions & 0 deletions air_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#-*- encoding: utf-8 -*-
import StringIO, requests, re, base64, zlib, xmltodict, json
from io import BytesIO
from wcf.records import *
from wcf.xml2records import XMLParser
import function.station_data

# https://github.com/ernw/python-wcfbin

class airChina():
def __init__(self):
self.provinceList = json.loads(function.station_data.provinceList_json)

def pListSearch(self, fromform, value):
if fromform == 0:
return {value: self.provinceList[str(value)]}
else:
for i in self.provinceList:
if self.provinceList[i][fromform-1].lower() == value.lower():
return {i: self.provinceList[str(i)]}
return None

def getResponse(self, action, data):
output = StringIO.StringIO()
output.write('<'+action+' xmlns="http://tempuri.org/">'+data+'</'+action+'>')
output.seek(0)

r = XMLParser.parse(output)
req = dump_records(r)

r = requests.post(url='http://106.37.208.233:20035/ClientBin/Env-CnemcPublish-RiaServices-EnvCnemcPublishDomainService.svc/binary/'+action,
data=req,
headers={'Content-Type': 'application/msbin1'})
res = r.content

buf = BytesIO(res)
r = Record.parse(buf)

print_records(r, fp=output)
output.seek(0)

pat = re.compile('<[^>]+>')
enc = pat.sub('', output.readlines()[1][1:])[:-1]

enc = base64.b64decode(enc)
enc = zlib.decompress(enc)

convertedDict = xmltodict.parse(enc)
return json.dumps(convertedDict)

#getInfo("GetProvincePublishLives", "<pid>9</pid>")
#getInfo("GetAreaIaqiPublishLive", "<area>上海市</area>")
#getInfo("GetCityDayAqiHistoryByCondition", "<cityCode>310000</cityCode>")
def getAllStationsData(self):
return json.loads(self.getResponse("GetAllAQIPublishLive", ""))["ArrayOfAQIDataPublishLive"]["AQIDataPublishLive"]

def getProvinceStationsData(self, province, type=0):
# 0: pid
# 1: Chinese name
# 2: Pinyin

if type == 0:
return json.loads(self.getResponse("GetProvincePublishLives", "<pid>"+str(province)+"</pid>"))["ArrayOfAQIDataPublishLive"]["AQIDataPublishLive"]
else:
pinfo = self.pListSearch(type, province)
if pinfo != None:
return json.loads(self.getResponse("GetProvincePublishLives", "<pid>"+str(pinfo.keys()[0])+"</pid>"))["ArrayOfAQIDataPublishLive"]["AQIDataPublishLive"]
else:
return None

def getAllProvinceName(self):
return json.loads(function.station_data.provinceList_json)

def getProvinceAllCityName(self, pid):
pjson = json.loads(function.station_data.stationList_json)
ret = []
for c in pjson[str(pid)]:
ret.append(c)

return ret

def getProvinceAllStationInfo(self, pid):
pjson = json.loads(function.station_data.stationList_json)
ret = []
for c in pjson[str(pid)]:
for s in pjson[str(pid)][c]:
ret.append(s)

return ret

def getCityAllStationInfo(self, pid, cityname):
pjson = json.loads(function.station_data.stationList_json)
try:
return pjson[str(pid)][cityname]
except:
return None

def searchCity(self, city):
sjson = json.loads(function.station_data.cityList_json)
city = str(city)
if sjson.has_key(city):
return {city: sjson[city]}
else:
for c in sjson:
if sjson[c] == city:
return {c: sjson[c]}

return None

def getCityHistory(self, city):
return json.loads(self.getResponse("GetCityDayAqiHistoryByCondition", "<cityCode>"+self.searchCity(city).keys()[0]+"</cityCode>"))["ArrayOfCityDayAQIPublishHistory"]["CityDayAQIPublishHistory"]

#def getAreaAQI(self):
# return json.loads(self.getResponse("ArrayOfIAQIDataPublishLive", u"<area>上海市</area>"))

38 changes: 38 additions & 0 deletions example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#-*- encoding: utf-8 -*-
import air_class, json
air = air_class.airChina()
'''
# Get data of all air matters from each station in China
allData = air.getAllStationsData()
print allData[0]
# Get data of all substations in one province
# type search by
# 0 pid
# 1 Chinese name
# 2 Chinese pinyin
provinceData = air.getProvinceStationsData("shanghai", type=2)
print provinceData
# Get all province names
AllProvince = air.getAllProvinceName()
print AllProvince
# Get all cities of the province(pid)
AllCity = air.getProvinceAllCityName(11)
print AllCity
# Get all stations of the province(pid)
AllProvinceStation = air.getProvinceAllStationInfo(10)
print AllProvinceStation
# Get all stations of the city(pid & city name)
AllCityStation = air.getCityAllStationInfo(10, u"苏州市")
print AllCityStation
# Get city AQI history
# param: city name or city code
cityHistory = air.getCityHistory(u"上海市")
print cityHistory
'''
Empty file added function/__init__.py
Empty file.
62 changes: 62 additions & 0 deletions function/function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# -*- encoding: utf-8 -*-

from xml.parsers.expat import ParserCreate
import json


class Xml2Json:
LIST_TAGS = ['COMMANDS']

def __init__(self, data=None):
self._parser = ParserCreate()
self._parser.StartElementHandler = self.start
self._parser.EndElementHandler = self.end
self._parser.CharacterDataHandler = self.data
self.result = None
if data:
self.feed(data)
self.close()

def feed(self, data):
self._stack = []
self._data = ''
self._parser.Parse(data, 0)

def close(self):
self._parser.Parse("", 1)
del self._parser

def start(self, tag, attrs):
assert attrs == {}
assert self._data.strip() == ''
self._stack.append([tag])
self._data = ''

def end(self, tag):
last_tag = self._stack.pop()
assert last_tag[0] == tag
if len(last_tag) == 1: # leaf
data = self._data
else:
if tag not in Xml2Json.LIST_TAGS:
# build a dict, repeating pairs get pushed into lists
data = {}
for k, v in last_tag[1:]:
if k not in data:
data[k] = v
else:
el = data[k]
if type(el) is not list:
data[k] = [el, v]
else:
el.append(v)
else: # force into a list
data = [{k: v} for k, v in last_tag[1:]]
if self._stack:
self._stack[-1].append((tag, data))
else:
self.result = {tag: data}
self._data = ''

def data(self, data):
self._data = data
36 changes: 36 additions & 0 deletions function/station_data.py

Large diffs are not rendered by default.

0 comments on commit 4cd5ea1

Please sign in to comment.