idataapi-transform
idataapi-transform is a pure python, full async support Toolkit, to transform data from one location/format to another location/format, provide command line interface for easy use, and python module with powerful features
It's currently used in IDataAPI team for efficiency work
Provide

You can read data from one of
- API(http)
- ES(ElasticSearch)
- CSV
- XLSX
- JSON
- Redis
- MySQL
- MongoDB
and convert to
- CSV
- XLSX
- JSON
- TXT
- Redis
- MySQL
- MongoDB
- Kafka
Features:
- with asyncio support and share same API
- Baesd on Template Method and Factory Method
- Every failure network read operation will log to error log before retry 3(default) times
- Every failure network write operation will log to error log before retry 3(default) times
- Command line support for simple usage, python module provide more features
- Every Getter and Writer support filter, you can alter or drop your data in filter
- Auto header generation(csv/xlsx)/table generation(mysql) based on your data
- APIGetter, will request next page automatically,each page will retry max_retry before fail
- APIBulkGetter support bulk processing for APIGetter/url object, you can feed iterable object or async generator
- easy to use concurrent control for APIBulkGetter
- support normal call back and async call back
- persistent task to disk
catalog
Requirment
- python version >= 3.5.2
- If you need MySQL enable, your python version should be >= 3.5.3
- If you need MongoDB enable, your platform should not be windows
Installation
python3 -m pip install idataapi-transform
# shell, run
transform --help # explanation of each parameter and create configure file
# edit ~/idataapi-transform.ini to config elasticsearch hosts, redis, mysql etc...
# Install MySQL module, if your python version >= 3.5.3
python3 -m pip install 'PyMySQL<=0.9.2,>=0.9'
python3 -m pip install aiomysql
# Install MongoDB module, if your platform is not Windows
python3 -m pip install motor
Command line interface Example
- Read data from [API, ES, CSV, XLSX, JSON, Redis, MySQL, MongoDB]
- Write data to [CSV, XLSX, JSON, TXT, ES, Redis, MySQL, MongoDB]
read data from Elasticsearch convert to CSV
will read at most 500 items from given index: knowledge20170517, and write to ./result.csv
transform ES csv "knowledge20170517" --max_limit=500
read data from API convert to XLSX
will read all items from given api url, until no more next page, and save to dest(/Users/zpoint/Desktop/result.xlsx), dest is optional, default is ./result.xlsx
transform API xlsx "http://xxx/post/dengta?kw=中国石化&apikey=xxx" "/Users/zpoint/Desktop/result"
read data from JSON convert to csv
will read items from json file, and save to ./result.csv
transform JSON csv "/Users/zpoint/Desktop/a.json"
read data from CSV convert to xlsx
will read items from csv file, and save to ./result.xlsx
transform CSV xlsx "./a.csv"
read data from Elasticsearch convert to CSV with parameters
save csv with file encoding "gbk" (--w_encoding)
specific index: knowledge20170517, (knowledge20170517)
when read from Elasticsearch, specific request body (--query_body)
body = {
"size": 100,
"_source": {
"includes": ["location", "title", "city", "id"]
}
}
before write to csv, add timestamp to each item, and drop items with null city (--filter)
# create a file name my_filter.py (any filename will be accepted)
import time
def my_filter(item): # function name must be "my_filter"
item["createtime"] = int(time.time())
if item["city"]:
return item # item will be write to destination
# reach here, means return None, nothing will be write to destination
Shell:
transform ES csv "knowledge20170517" --w_encoding gbk --query_body '{"size": 100, "_source": {"includes": ["location", "title", "city", "id"]}}' --filter ./my_filter.py
Read data from API write to Redis
- redis key name: my_key
- redis store/read support LIST and HASH, default value is LIST, you can change it with --key_type parameter
will read data from ./a.csv, and save to redis LIST data structure, KEY: my_key
transform API redis "http://xxx/post/dengta?kw=中国石化&apikey=xxx" my_key
Read data from Redis write to csv
will read data from redis key my_key, read at most 100 data, and save to ./result.csv
transform Redis csv my_key --max_limit 100
Read data from API write to MySQL
- auto create table if not exist
will read data from API, read at most 50 data, and save to MySQL table: my_table
transform API MYSQL 'http://xxx' my_table --max_limit=50
Read data from MySQL write to redis
will read data from MySQL table my_table, each read operation fetch 60 items, and save to a redis LIST name result, result is the default key name if you don't provide one
transform MYSQL redis my_table --per_limit=60
Read data from MongoDB write to csv
- you can provide --query_body
will read at most 50 data from "my_coll", and save to ./result.csv
transform mongo csv my_coll --max_limit=50
Python module support
ES to csv
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
async def example():
body = {
"size": 100,
"_source": {
"includes": ["likeCount", "id", "title"]
}
}
es_config = GetterConfig.RESConfig("post20170630", "news", max_limit=1000, query_body=body)
es_getter = ProcessFactory.create_getter(es_config)
csv_config = WriterConfig.WCSVConfig("./result.csv")
with ProcessFactory.create_writer(csv_config) as csv_writer:
async for items in es_getter:
# do whatever you want with items
csv_writer.write(items)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
API to xlsx
import time
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
yesterday_ts = int(time.time()) - 24 * 60 * 60
def my_done_if(items):
# RAPIConfig will fetch next page until
# 1. no more page or
# 2. reach max_limit or
# 3. error occurs
# if you want to terminate fetching in some condition, you can provide done_if function
if items[-1]["publishDate"] < yesterday_ts:
return True
return False
async def example():
api_config = GetterConfig.RAPIConfig("http://xxxx")
# or you can use: api_config = GetterConfig.RAPIConfig("http://xxxx", done_if=my_done_if)
getter = ProcessFactory.create_getter(api_config)
xlsx_config = WriterConfig.WXLSXConfig("./result.xlsx")
with ProcessFactory.create_writer(xlsx_config) as xlsx_writer:
async for items in getter:
# do whatever you want with items
xlsx_writer.write(items)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
CSV to xlsx
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
async def example():
csv_config = GetterConfig.RCSVConfig("./result.csv")
getter = ProcessFactory.create_getter(csv_config)
xlsx_config = WriterConfig.WXLSXConfig("./result.xlsx")
with ProcessFactory.create_writer(xlsx_config) as xlsx_writer:
for items in getter:
# do whatever you want with items
xlsx_writer.write(items)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
API to redis
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
async def example():
api_config = GetterConfig.RAPIConfig("http://xxx")
getter = ProcessFactory.create_getter(api_config)
redis_config = WriterConfig.WRedisConfig("key_a")
with ProcessFactory.create_writer(redis_config) as redis_writer:
async for items in getter:
# do whatever you want with items
await redis_writer.write(items)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
redis to MySQL
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
def my_filter(item):
# I am a filter
# Every getter or writer created by ProcessFactory.create can set up a filter
# every data will be pass to filter before return from getter, or before write to writer
# you can alter data here, or drop data here
if item["viewCount"] > 10:
return item
# if don't return anything(return None) means drop this data
async def example():
api_config = GetterConfig.RAPIConfig("http://xxxx", filter_=my_filter)
getter = ProcessFactory.create_getter(api_config)
mysql_config = WriterConfig.WMySQLConfig("my_table")
with ProcessFactory.create_writer(mysql_config) as mysql_writer:
async for items in getter:
# do whatever you want with items
await mysql_writer.write(items)
# await mysql_config.get_mysql_pool_cli() # aiomysql connection pool
# mysql_config.connection # one of the connection in previous connection pool
# mysql_config.cursor # cursor of previous connection
# you should alaways call 'await mysql_config.get_mysql_pool_cli()' before use connection and cursor
# provided by GetterConfig.RMySQLConfig and WriterConfig.WMySQLConfig
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
MongoDB to redis
import asyncio
from idataapi_transform import ProcessFactory, GetterConfig, WriterConfig
async def example():
mongo_config = GetterConfig.RMongoConfig("coll_name")
mongo_getter = ProcessFactory.create_getter(mongo_config)
redis_config = WriterConfig.WRedisConfig("my_key")
with ProcessFactory.create_writer(redis_config) as redis_writer:
async for items in mongo_getter:
# do whatever you want with items
await mysql_writer.write(items)
# print(mongo_config.get_mysql_pget_mongo_cli()) # motor's AsyncIOMotorClient instance
# provided by GetterConfig.RMongoConfig and WriterConfig.WMongoConfig
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
Bulk API to ES or MongoDB or Json