&&&&&

# -*- coding: utf-8 -*
import requests
import time
import datetime
import sys
import pymysql
reload(sys)
sys.setdefaultencoding('utf-8')


def qiHuo(url):
    response = requests.get(url)
    response =response.json()
    return response


def getContractId():
    url = "https://fd.qihuoniu.com/mktdata/contractdatalist.ashx?version=1.0.0&packtype=338&contracttypeid=2&proxyid=33"
    dataList = qiHuo(url)['data']
    contractIdList =[]
    mapdict ={}
    for data in dataList:
        mapdict[data['contractid']] =  data['symbol']
        contractIdList.append(data['contractid'])
    return contractIdList,mapdict



def shiJianList(start,end):
    datelist = []
    datestart = datetime.datetime.strptime(str(start), '%Y%m%d')
    dateend = datetime.datetime.strptime(str(end), '%Y%m%d')
    while datestart < dateend:
        datestart += datetime.timedelta(days=1)
        shijian = datestart.strftime('%Y%m%d')+"000000"
        datelist.append(shijian)
    return datelist


def connectmysql(host,port,user,passwd,db,charset='utf8'):
    """
    连接数据库、创建游标,返回连接对象、游标对象
    """
    try:
        conn = pymysql.connect(host=str(host),port=int(port),user=str(user),passwd=str(passwd),db=str(db),charset=str(charset))
        cursor = conn.cursor()
        return conn,cursor
    except Exception as e:
        return e


def test(shiJian,contractId):
    url = "https://fd.qihuoniu.com/mktdata/futureskline.ashx?version=1.0.0&packtype=338&contracttypeid=2&proxyid=33&contractid=%s&type=6&count=200&time=%s&ba=2" % (contractId,shiJian)
    data = qiHuo(url)
    return data



if __name__ =="__main__":


    start = 20180301
    end =   20180516
    timeList = shiJianList(start,end)
    contractIdList,mapdict = getContractId()
    for contractId in contractIdList:
        conn, cursor = connectmysql("mysqlip", 3306, "root", '密码', '数据库')
        name  = mapdict[contractId]
        for shiJian in timeList:
            try:
                resoponseData = test(shiJian,contractId)['data']
                data =  resoponseData['timedata'][-1]
                picePoint = resoponseData['nowv']
                try:
                    piceIndex =  list(str(picePoint)).index('.')
                except:
                    piceIndex = 0

                openPoint = resoponseData['openp']
                try:
                    openIndex = list(str(openPoint)).index('.')
                except:
                    openIndex = 0

                highPoint = resoponseData['highp']
                try:
                    highIndex = list(str(highPoint)).index('.')
                except:
                    highIndex = 0

                lowPoint = resoponseData['lowp']
                try:
                    lowIndex = list(str(lowPoint)).index('.')
                except:
                    lowIndex = 0

                closePoint = resoponseData['nowv']
                try:
                    closeIndex = list(str(closePoint)).index('.')
                except:
                    closeIndex = 0
            except:
                time.sleep(3)
                data = test(shiJian, contractId)['data']['timedata'][-1]
            pirce = data['nowv']  # 当前价格
            pirce2 =list(str(pirce))
            if piceIndex != 0:
                pirce2.insert(piceIndex,'.')
            pirce = ''.join(pirce2)


            time2 = str(shiJian)[:-2]
            datetimeObj = time.strptime(time2, "%Y%m%d%H%M%S")
            time2 = time.strftime("%Y-%m-%d %H:%M:%S", datetimeObj)

            diff = data['updown']  # 涨跌值
            diff_rate = data['updownrate']  # 涨跌幅度%

            open = data['openp']  # 开盘价格
            open2 = list(str(open))
            if openIndex != 0:
                open2.insert(openIndex,'.')
            open =''.join(open2)

            high = data['highp']  # 今日最高
            high2 = list(str(high))
            if highIndex !=0:
                high2.insert(highIndex,'.')
            high =''.join((high2))

            low = data['lowp'] # 今日最低
            low2 =list(str(low))
            if lowIndex !=0:
                low2.insert(lowIndex,'.')
            low =''.join(low2)

            close = data['nowv']  # 昨日收盘价
            close2 = list(str(close))
            if closeIndex !=0:
                close2.insert(closeIndex,'.')
            close = ''.join(close2)

            sql = "insert into `data_alist4`(name,time,diff,diff_rate,open,high,low,close) values('%s','%s','%s','%s','%s','%s','%s','%s');" % (str(name),  str(time2), str(diff), str(diff_rate), str(open), str(high), str(low), str(close))
            cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()




&&&&