create_category.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

###########################
#######   LICENSE   #######
###########################

# Copyright (c) 2014-2016, Anodot Ltd. <info@anodot.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
#    following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
#    following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
#    products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import json
import logging
import argparse
import requests
requests.packages.urllib3.disable_warnings()

################################
# Function name: print_license                         
# Params: None                                              
# Returns: Anodot's license                             
###############################
def print_license():
    text = '''
Copyright (c) 2014-2016, Anodot Ltd. <info@anodot.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
   following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
   following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
   products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    '''

    print(text)

##################################
# Function name: msg                                           
# Params: None                                                    
# Returns: Returns the help message                     
#################################
def msg(name=None):
    return '''create_category.py
         Create a category for events.

         - Print Anodot's license: python create_category.py --license
         - Create a category without an image: python create_category.py --category_name <the category's name> --token <the API's token>
         - Create a category with an image: python create_category.py --category_name <the category's name> --image_url <the image's url under secure server> --token <the API's token>

        NOTE: Image_url - A url to the image that will be displayed as an icon for the category [optional]
                          The ImageUrl must be located under a secure server - for example  https://myServer/myImage.png
        '''


def main():
    logging.basicConfig(filename='create_category.log',level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
    logger = logging.getLogger(__name__)
    logger.info('Starting a run')

    parser = argparse.ArgumentParser(description='', usage=msg())
    parser.add_argument('--category_name', required=False, default=None, help="The category's name")
    parser.add_argument('--image_url', required=False, default=None, help="The image's url that will be displayed as an icon. Must be under a secure server (https)")
    parser.add_argument('--token', required=False, default=None, help="The Anodot's API token")
    parser.add_argument('--license', required=False, action='store_true', help="Print Anodot's license")

    args = parser.parse_args()

    if(args.license):
        logger.info('user asked to print the license')
        print_license()
        exit()

    if(args.token is None):
        logger.error('--token is mandatory when creating a new category')
        raise Exception("--token is mandatory when creating a new category")
    elif(args.category_name is None):
        logger.error('--category_name is mandatory when creating a new category')
        raise Exception("--category_name is mandatory when creating a new category")
    else:
        if(args.image_url is None):
            logger.info('User asked to create a category without an image url')
            body = {"category":{"name":args.category_name}}
        else:
            logger.info('User asked to create a category with an image url')
            body = {"category":{"imageUrl":args.image_url, "name":args.category_name}}

        logger.info('Sending http request to create a category: ' + json.dumps(body))
        response = requests.post('https://api.anodot.com/api/v1/user-events/categories?token=' + args.token, headers={'Content-Type': 'application/json'}, data=json.dumps(body))
        if(response.status_code == 200):
            logger.info('Category was created: ' + response.content)
            print "Category was created: " + response.content
        else:
            logger.error('Category creation failed: ' + 'status code: ' + str(response.status_code) + ' response body: ' + response.content)
            print 'Category creation failed: ' + 'status code: ' + str(response.status_code) + ' response body: ' + response.content

if __name__ == "__main__":
    main()
 

Was this article helpful?
0 out of 0 found this helpful
-->