调用phone库,查询手机号码归属地(4)
需要安装pymysql,phone库
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, pymysql, logging, phone
from urllib import urlencode, urlopen
reload(sys)
sys.setdefaultencoding('utf8')
LOG_FORMAT = "[%(asctime)s] - %(levelname)s - %(message)s"
LOG_FILE = logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT)
def getPagephone(data):
f=phone.Phone().find(data)
logging.info('data = %s'%data)
logging.info('phone-f = %s'%f)
if not f is None:
res = {u'resultcode': u'200', u'error_code': 0, u'reason': u'Return Successd!', u'result': f}
return res
else:
res = {u'resultcode': u'300'}
return res
#对api接口返回数据处理。
def resTest(resdata):
if resdata["resultcode"] == "200":
#返回有效结果
logging.info('resdata = %s'%resdata["result"])
return resdata["result"]
else:
#定义字典,resdata["resultcode"]为接口返回的Error code
Errorinfo = {'province':'Error code', 'city':resdata["resultcode"]}
return Errorinfo
#处理字典为单元组列表
def dictDate(data):
province = data["province"]
city = data["city"]
res.append((phoneNum, province, city))
#将省和市处理为一个元素:辽宁,葫芦岛
resz = [(res[0][0],res[0][1]+','+res[0][2])]
logging.info('resz = %s'%resz)
return resz
#连接数据库
dblink = pymysql.connect(
host = "10.10.10.31",
user = "abc",
password = "123456",
database = "test",
charset = "utf8")
#查询数据
def select(db):
cursor = db.cursor()
cursor.execute("select phoneNum from test.userinfo where location=''")
#cursor.execute("select phoneNum from test.userinfo order by id;")
# 使用 fetchone() 方法获取单条数据.fetchall()获取所有行
data = cursor.fetchall()
#print data
return data
#插入数据
def install(db, data):
cursor = db.cursor()
sql = "update `test`.`userinfo` set location=%s where phoneNum = %s"
#data=(第一个%s,第二个%s)
data = (data[0][1], data[0][0])
cursor.execute(sql, data)
db.commit()
if __name__ == "__main__":
logging.info('resz = %s'%dblink)
for phoneNum in select(dblink):
phoneNum = phoneNum[0]
logging.info('phoneNum = %s'%phoneNum)
res = []
resdate = resTest((getPagephone(phoneNum)))
#通过函数dictDate处理为单元组列表,[('12676512732', u'\u6d52\u6c5f,\u6e19\u5dde')]
resUlt = dictDate(resdate)
install(dblink, resUlt)
dblink.close()
调用API接口,查询手机号码归属地(1)https://www.cnblogs.com/outsrkem/p/11219743.html
调用API接口,查询手机号码归属地(2)https://www.cnblogs.com/outsrkem/p/11221003.html
调用API接口,查询手机号码归属地(3)https://www.cnblogs.com/outsrkem/p/11221604.html
调用phone库,查询手机号码归属地(4)https://www.cnblogs.com/outsrkem/p/11236509.html
作者:Outsrkem
原文链接:https://www.cnblogs.com/outsrkem/p/11236509.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。