#!/usr/bin/env python
import requests
import os


def upload_file(url, file_loc, cookies=None, headers=None,
                file_type='application/vnd.ms-excel'):
    """Upload a file using an end point using requests posting of
    a multipart encoded file
    
    Based on source from http://stackoverflow.com/a/22974646
    
    :param url: URL of end point
    :param file_loc: location of the file
    :param cookies: optional dictionary of cookies or a CookieJar
    :param headers: optional dictionary of headers
    :param file_type: optional file type. Defaults to excel.
    :returns: request return object
    """
    file_name = os.path.basename(file_loc)
    file_params = {
        # controls the contents of the file; see open()
        'file': (file_name, open(file_loc, 'rb'), file_type),
        # controls the title of the file and this can easily be any param
        'filename': ('', file_name)
    }
    params = {
        'url': url,
        'cookies': cookies,
        'headers': headers,
        'files': file_params,
    }
    try:
        res = requests.post(**params)
    except:
        print("upload_file() is unable to upload the file")
        raise
    return res


if __main__ == "__name__":
    # find os agnostic location of file path for files/data.xlsx
    file_loc = os.path.join('files', 'data.xlsx')
    res = upload_file(url, file_loc)