view data_manager_gene_annotation/data_manager/data_manager.py @ 24:a70b4c3bdd8b draft

planemo upload
author scottx611x
date Thu, 23 Jun 2016 15:28:06 -0400
parents cb42506ae8ce
children 689075526eb3
line wrap: on
line source

import os
import sys
import uuid
import json
import argparse
import datetime
import requests
from requests.exceptions import ContentDecodingError

parser = argparse.ArgumentParser(description='Create data manager json.')
parser.add_argument('--out',
                    dest='output',
                    action='store',
                    help='JSON filename',
                    )
parser.add_argument('--name',
                    dest='name',
                    action='store',
                    default=uuid.uuid4(),
                    help='Data table entry unique ID'
                    )
parser.add_argument('--url',
                    dest='url',
                    action='store',
                    help='Download URL'
                    )

args = parser.parse_args()


def url_download(url, name):
    response = requests.get(url=url, stream=True)

    # Generate file_name
    file_name = response.url.split("/")[-1]

    block_size = 10 * 1024 * 1024  # 10MB chunked download
    with open(file_name, 'w+') as f:
        try:
            # Good to note here that requests' iter_content() will
            # automatically handle decoding "gzip" and "deflate" formats
            for buf in response.iter_content(block_size):
                f.write(buf)
        except (ContentDecodingError, IOError) as e:
            sys.stderr.write("Error occured downloading reference file: %s"
                             % e)
            os.remove(file_name)

    return os.path.join(os.getcwd(), file_name)


def main(args):

    # Attempt to download gene annotation file from given url
    gene_annotation_file_path = url_download(
        "http://www.scott-ouellette.com/gene_annotations/chr1-hg19_genes.gtf", args.name)

    # Update Data Manager JSON and write to file
    data_manager_entry = {
        'data_tables': {
            'gene_annotation': {
                'value': str(datetime.datetime.now()),
                'dbkey': str(args.name),
                'name': gene_annotation_file_path.split(".")[0],
                'path': gene_annotation_file_path,
            }
        }
    }

    with open(os.path.join(args.output), "w+") as f:
        f.write(json.dumps(data_manager_entry))

if __name__ == '__main__':
    main(args)