import csv
import datetime
import os
import socketserver
import time
import urllib
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import string
import joblib
import pandas as pd


day = time.strftime('%Y-%m-%d', time.localtime(time.time()))
if os.path.exists('./'+day  + ".csv")==False:
    with open('./' + day + ".csv", 'a+', newline='', encoding='utf-8') as csvfile:
        csv_write = csv.writer(csvfile)
        csv_write.writerow(['代码', '时间', '汇率'])




# a+表示以追加模式写入，如果用w会覆盖掉原来的数据。如果没有newline=''，则逐行写入的数据相邻行之间会出现一行空白。读者可以自己试一试。

class TestHTTPHandle(BaseHTTPRequestHandler):
    # dataTick = pd.read_csv(yesterday,encoding='utf-8')
    # gbm_500 = joblib.load('500model.txt')
    def do_GET(self):
        if self.path.find('code') != -1:
            self.queryString = urllib.parse.unquote(self.path.split('?', 1)[1])
            params = urllib.parse.parse_qs(self.queryString)
            code = params['code'][0]
            rate = params['rate'][0]
            ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            with open('./' + day + ".csv", 'a+', newline='', encoding='utf-8') as csvfile:
                csv_write = csv.writer(csvfile)
                csv_write.writerow([code, ctime, rate])




        self.send_response(200,message='122')  # 应答机制，接收到消息后，响应服务端，告知服务端已经收到消息，避免消息重复发送
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write('123'.encode('gbk'))


# http://183.194.213.36:58588/?dateTimeStamp=1546392660.0&lastIndex=4173.74
def start_server(port):
        # 0.0.0.0 映射测试机器的公网地址、在回掉地址测和订阅测，配置对应机器的公务地址
        #
        # http_server = HTTPServer(('0.0.0.0', int(port)), TestHTTPHandle)
        http_server =  socketserver.TCPServer(('0.0.0.0', int(port)), TestHTTPHandle)

        # http_server.server_close()
        http_server.serve_forever()
if __name__ == '__main__':
    start_server(8888)

