python + docker, 实现天气数据 从FTP获取以及持久化(四)-- 数据准备

前情提要

在之前的文章里,我们已经掌握从FTP上面下载天气数据然后插入到数据库中。

但是如何将我们已有的数据放到生产环境中呢?

 

思考

首先,我们先简单的理一理现在的情况。

目前: FTP上面已有半个月的天气数;每天会有2个txt文件产生 (每个文件大小约为 50~60 kb),由天气供应商负责上传到FTP上。 如图所示:

思路1:

经过简单的测试,每次读取一个txt文件然后写入数据库的时间大约为1s, 因此,可以考虑写一个小工具,从FTP上依次读取所有的txt, 然后插入数据库。也就是利用小工具到现场后再准备数据。

 

思路2:

直接将数据库文件导出,然后到现场部署的时候导入。

 

想好了就是干

① 思路1的解决方案

由于之前已经写好了FTP读取以及数据库插入数据的方法,这里只需要简单封装一下,即可满足我们的功能。 ~~~show me the code ~~

def fetch_insert_all_data():
    ftp = FTPUtil('xxx.xxx.xxx.xxx')
    ftp.Login('xxxxxx', 'xxxxxx')

    # create database and tables
    nRet = preparation()
    if nRet != 0:
        print "Connect MySQL DB error!"
        return

    # fetach all data from FTP and insert into database
    for file in ftp.listFiles():
        remote_file = file
        local_file = file
        if ftp.DownLoadFile(local_file, remote_file):
            print "Download file {0} from FTP ok.".format(remote_file)
            list_weather_tumple = decode_weather_from_txt(local_file)
            nRet2 = insert_or_update_weather_data(list_weather_tumple)
            if nRet2 >= 0:
                print "Insert or update weather {0} ok.".format(remote_file)
            else:
                print "Insert or update weather {0} error!".format(remote_file)

            delete_file(local_file)
        else:
            print "Download file {0} from FTP error!".format(remote_file)

    ftp.close();

 

 

② 思路2的解决方案

首先,不得不说,虽然这种办法不用撸代码,但是需要 play 数据库啊; 经过了不断地尝试以及查找 。。。总结如下:

1. 导出数据库表(在 terminal上输入)

# mysqldump   -u root  -p weather_db  weather > /var/lib/mysql/weather.sql

按照提示,输入正确的password, 我们就可以看到导出的文件啦!

 

2. 导入数据库表 

2.1 首先需要进入MySQL命令行

# mysql -u root -pxxxx

 

2.2 建立数据库

mysql> create database weather_db
mysql> use weather_db

这一点非常重要:因为我们的导出文件是基于数据库表的,数据库表需要依附于数据库

 

2.3 运行 SQL脚本

这里不得不吐槽一下,网上的童鞋说可以在terminal上面直接执行 SQL文件, 但是我这里一直出错!!! 

当我 “不小心” (瞎尝试) 在MySQL的命令行中运行脚本, where amazing happend !!

 

OK, 让我们查看一下数据库表和数据,

~大功告成~

总结

总的来说,两种方法各有千秋:

方案1 需要花费更多的时间(收集 1天数据耗时约为 1s)。

方案2 需要我们将数据导入后,也许还需要再做一些插入操作(再插入几天的数据)。

 

 

Lastly, 感谢大家的收看,如果有更好建议也欢迎留言交流。

posted @ 2018-07-13 16:29  TonyZhang24  阅读(723)  评论(0编辑  收藏  举报