예제 #1
0
 def parseargs(pgm, argv, usage):
     try:
         (opts, args) = getopt.getopt(argv, 's:j:f:o:xt',
         ['since=', 'job-category=', 'filters=', 'out=', 'xml', 'text'])
     except getopt.GetoptError, e:
         stderr(e)
         return usage_tail(pgm, usage, None)
예제 #2
0
파일: main.py 프로젝트: tsinclair/PyDeskAPI
def preparseargs(pgm, argv, usage):
    """Pick out command line options recognized by the Python API.

    Called from app_main()

    Parameters:
    pgm - name of the executable, normally path.basename(sys.argv[0])
    argv - list, normally sys.argv[1:]
    usage - command line args and options specific to this executable

    Returns two-tuple of:
    - dict of API options
    - list containing remaining argv tokens
    
    """
    import getopt
    popts = {}
    for k in ('auth', 'config', 'debug', 'log-level', 'log-console',
                        'log-disk', 'alias'):
        popts[k] = None
    argvslice, argvrem = extractargs(argv)
    try: 
        (opts, args) = getopt.getopt(argvslice, 'h',
        ['auth=', 'config=', 'log-level=', 'name=', 'debug', 'help'
         'log-console', 'log-disk', 'no-log-console', 'no-log-disk' ])
    except getopt.GetoptError, e:
        stderr(e)
        exit(usage_tail(pgm, usage, 1))
예제 #3
0
파일: job.py 프로젝트: tsinclair/PyDeskAPI
def job_search(api, since=3, **kwargs):
    """Produce list of job posted after given date."""
    debug = log.debug
    url = 'https://www.odesk.com/api/profiles/v1/search/jobs.xml'
    dp = days_ago_to_dp(since)
    keys = kwargs.keys()
    params = [('dp', dp)]
    for keyword in keys:
        param = valid_job_search_parameter(keyword)
        if param:
            params.append((param, kwargs[keyword]))
    offset=0
    count = 200
    joblist = []
    while 1:
        params.append(('page', '{0:d};{1:d}'.format(offset, count)))
        xml = send_GET(api, url, params)
        if xml is None:
            e = "Error, request failed: send_GET(api, {0:s}, {1!s}".format(url, params)
            stderr("{0:s}\n".format(e))
            log.error(e)
            return joblist
        jl = list_from_xml(xml, 'job')
        if len(jl) == 0: break
        joblist.extend(jl)
        if len(jl) < count: break
        params.pop()
        offset += count
    return joblist
예제 #4
0
def _send_request(api, url, request='get', params=None, save_xml=None):
    """Call api.xxxx_request and optionally save XML response to file.

    Parameter 'api' is an instance of class oDeskAPI
    """
    save_file = None
    pcopy = params[:] if params else None
    log.debug("send_{0:s} params: {1!r}".format(pcopy, request.upper()))
    request = request.lower()
    try:
        if request == 'get':
            response = api.get_request(url, pcopy)
        elif request == 'post':
            response = api.post_request(url, pcopy)
        elif request == 'put':
            response = api.put_request(url, pcopy)
        elif request == 'delete':
            response = api.delete_request(url, pcopy)
        else:
            e = "Unknown request type '{0:s}'".format(request)
            stderr("{0:s}\n".format(e))
            log.error(e)
            return None
    except RequestError, e:
        # api.last_error is the error code returned by server
        stderr(e)
        log.exception(e)
        # Do not change this return value.
        # Some callers may check 'if response is None: ...'
        return None
예제 #5
0
def keyword_filter(re_word, text, blacklist):
    if blacklist and not isinstance(blacklist, list):
        stderr('blacklist must be a list\n')
        return False
    for word in re_word.findall(text):
        if word in blacklist:
            return False
    return True
예제 #6
0
def parseargs(pgm, argv, usage):
    import getopt
    popts = {'bonus':None, 'comment':None, 'user':None, 'notes':None}
    try: 
        (opts, args) = getopt.getopt(argv, 'b:c:u:n:',
        ['bonus=', 'comment=', 'user='******'notes='])
    except getopt.GetoptError, e:
        stderr(e)
        return (None, None)
예제 #7
0
def parseargs(pgm, argv, usage):
    import getopt
    popts = {'brief':False, 'request':None}
    try:
        (opts, args) = getopt.getopt(argv,'br:',['brief','request='])
    except getopt.GetoptError, e:
        stderr(e)
        usage_tail(pgm, usage, 1)
        return (None, None)
예제 #8
0
def parseargs(pgm, argv):
    import getopt
    popts = {'input':None, 'tag':None, 'output':None}
    try:
        (opts, args) = getopt.getopt(argv, 'i:t:o:h',
                                ['input=', 'tag=', 'output=', 'help'])
    except getopt.GetoptError, e:
        stderr(e)
        exit(usage(pgm, 1))
예제 #9
0
def find_job_filters(popts):
    filters = popts['filters']
    if filters and test_fileobj(filters) == 0:
        return True
    home = path.expanduser('~')
    filters = path.join(home, '.odesk_jobs.filt')
    if test_fileobj(filters) == 0:
        popts['filters'] = filters;
        return True
    stderr("  --filters <filename> needs to be given.\n");
    stderr("  That file should contain at least keyword filters for sw job search.\n");
    return False
예제 #10
0
def provider_search(api, save_xml=False, **kwargs):
    """Use the provider search API to search all public providers on oDesk.    

    Parameter kwargs is expected to contain key-value pairs where the key
    is one of the keys, or the 'field_name', from the dict 'params' defined
    in  valid_provider_search_parameter().

    The utility function str2kwargs() from api.util.utility can be used to
    generate 'kwargs'.
    """
    node_name = 'providers'
    url = get_API_URL('providers')
    if save_xml: save_xml = 'providers.xml'
    params = []
    for keyword in kwargs.keys():
        parameter = valid_provider_search_parameter(keyword)
        if not parameter: continue
        if kwargs[keyword]:   # could be 'None'
            if parameter == 'sort':
                stderr('\nkwargs[keyword] = {0:s}\n'.format(kwargs[keyword]))
                value = _verify_sort(kwargs[keyword])
            else:
                value = kwargs[keyword]
            if value:
                params.append((parameter, value))
        else:
            params.append((parameter))
    # HERE
    #stderr('\nquery/provider.py:provider_search() params = {0!r}\n\n'.format(params))
    #
    offset=0
    count = 200
    providers = []
    while 1:
        # extrac parens needed, param to append is a tuple
        params.append(('page', '{0:d};{1:d}'.format(offset, count)))
        # HERE
        #stderr('send_GET params: {0:s}\n'.format(params))
        #
        xml = send_GET(api, url, params, save_xml)
        if xml is None:
            e = "Error, request failed: send_GET(api, {0:s}, {1!s}".format(url, params)
            stderr("{0:s}\n".format(e))
            log.error(e)
            return None
        pl = list_from_xml(xml, node_name)
        if len(pl) == 0: break
        providers.extend(pl)
        if len(pl) < count: break
        params.pop()
        offset += count
    return providers
예제 #11
0
def user_info(api, company, team, user_email=None, user_id=None,
                                            user_ref=None, user_name=None):
    iam = func()
    if not (user_email or user_id or user_ref or user_name):
        stderr('Missing required parameter- one of email, id, ref, name\n', iam)
        return None
    (reference, status) = find_team(api, company, team)
    if not reference:
        return None
    kwargs = {'status':'active'}
    request = ['provider__id', 'provider__reference', 'job__reference']
    engagements = team_engagements(api, team, request=request, kwargs=kwargs)
    request = []
예제 #12
0
def jobs_managed(api, company, team, request=None, **kwargs):
    """Compile a list of open jobs managed under 'company'."""
    # Need team reference for 'buyer_team_reference' parameter to Jobs HR API
    bad_result = (0, None)
    (ref, status) = find_team(api, company, team)
    if not ref:
        log.error("Failed to find team {0:s} (company {1:s})".format(team, company))
        return bad_result
    node_name = 'job'
    params = [('buyer_team__reference', ref)]
    if kwargs:
        keys = kwargs.keys()
        for key in keys:
            param = valid_jobs_managed_parameter(key)
            if param:
                params.append((param, kwargs[key]))
            elif key == 'save_xml':
                save_xml = 'jobs_managed' if kwargs[key] else None
    url = get_API_URL('jobs_hr')
    xml = send_GET(api, url, params, save_xml=save_xml)
    if xml is None:
        e = "Error, request failed: send_GET(api, {0:s}, {1!s}".format(url, params)
        stderr("{0:s}\n".format(e))
        log.error(e)
        return bad_result
    total_items = int(xml_get_tag(xml, 'total_items'))
    all_info = ['buyer_company__name','buyer_company__reference','buyer_team__id',
        'buyer_team__name','buyer_team__reference','category','company__reference',
        'company_name','created_by','created_by_name','created_time','description',
        'duration','end_date','filled_date','id','job_type','name',
        'num_active_candidates','num_candidates','num_new_candidates',
        'owner_user_id','parent_team__id','parent_team__name',
        'parent_team__reference','public_url','reference','start_date','status',
        'subcategory','title','visibility']
    if not request:
        requested_info = all_info[:]
    else:
        requested_info = list_intersect(request, all_info)
    if total_items > 0:
        result = dict_subset(list_from_xml(xml, node_name), requested_info)
    else:
        result = []
    return (total_items, result)
예제 #13
0
def provider_profile(api, provider_keys, request=None,
                        brief_listing=True, save_xml=False):
    """Fetch provider profile(s) associated with provider key(s).

    Parameter 'provider_keys' is interpreted as a string of one or more
    keys, or a tuple or list of two or more keys.

    'ciphertext' returned from provider_search() above is the 'provider_key'.
    """
    url = get_API_URL('profiles')
    url_suffix = '/brief.xml' if brief_listing else '.xml'
    node_name = 'profile'
    # 'Parameters: Accepts a provider key or list of keys'
    # E.g. "~~d4080e9142d610ea;~~d4080e9142d610ea;~~9eaf4d98034b5bd8"
    # Note: as of 2011-04-08 the list of keys format does not work? Perms?
    if isinstance(provider_keys, basestring):
        provider_keys = provider_keys.replace(' ', ';')
        provider_keys = provider_keys.split(';')
    elif isinstance(provider_keys, list) or isinstance(provider_keys, tuple):
        provider_keys = list(provider_keys)
    else:
        e = "provider_profile(api, provider_keys): provider_keys parmeter must\n"
        e += "be a string, tuple, or list."
        raise ParamFmtError(e)
    assert isinstance(provider_keys,list)
    params = ''
    for pk in provider_keys:
        params += pk + ';'
    params = params.rstrip(';')
    
    # quoting multiple strings does not work either
    # url += "'" + params + "'"+ url_suffix
    url += params + url_suffix
    xml = send_GET(api, url, params=None, save_xml=save_xml)
    if xml is None:
        e = "Error, request failed: send_GET(api, {0:s})".format(url)
        stderr("{0:s}\n".format(e))
        log.error(e)
        return None
    result = list_from_xml(xml, node_name)
    return result
예제 #14
0
파일: main.py 프로젝트: tsinclair/PyDeskAPI
def app_main(pgm, argv, usage):
    """Preparse command line and initialize the Python API.

    This is designed to be called from the executable prior to any other
    command line parsing. It will parse all the generic command line
    arguments recognised by the library and initialize the API library.

    Parameters:
    pgm - name of the executable, normally path.basename(sys.argv[0])
    argv - list, normally sys.argv[1:]
    usage - command line args and options specific to this executable

    Returns two-tuple of:
        - API instance
        - list containing remaining argv tokens after parsing
    """
    try:
        (popts, argv2) = preparseargs(pgm, argv, usage)
    except AppOptionError, e:
        stderr('{0:s\n', e)
        exit(1)
예제 #15
0
def engagement_details(api, reference_no, request=None, save_xml=None):
    """Fetch details on one engagements.
    
    Parameter 'reference_no' is the engagement reference number- same as
    'reference' returned from the query api.query.engagements(api, team)

    Parameter 'request' if given limits the information returned to a subset of: 

      [buyer_team__id, buyer_team__reference, created_time, engagement_job_type,
       engagement_start_date, engagement_title, estimated_duration,
       estimated_duration_id, hourly_charge_rate, hourly_pay_rate,
       job__reference, job__title, modified_time, offer__reference, provider__id,
       provider__reference, reference, role, status, weekly_hours_limit,
       weekly_salary_charge_amount, weekly_salary_pay_amount]

    Return value is a list of dicionary objects, one for each 'engagement'
    the query returns.
    """
    all_info = ['buyer_team__id', 'buyer_team__reference', 'created_time',
        'engagement_job_type', 'engagement_start_date', 'engagement_title',
        'estimated_duration', 'estimated_duration_id', 'hourly_charge_rate',
        'hourly_pay_rate', 'job__reference', 'job__title', 'modified_time',
        'offer__reference', 'provider__id', 'provider__reference', 'reference',
        'role', 'status', 'weekly_hours_limit', 'weekly_salary_charge_amount',
        'weekly_salary_pay_amount']
    if not request:
        requested_info = all_info[:]
    else:
        requested_info = list_intersect(request, all_info)
    node_name = 'engagement'
    url = get_API_URL('engagement', engagement_ref=reference_no)
    xml = send_GET(api, url)
    if xml is None:
        e = "Error, request failed: send_GET(api, {0:s})".format(url)
        stderr("{0:s}\n".format(e))
        log.error(e)
        return None
    result = list_from_xml(xml, node_name)
    details = dict_subset(result, requested_info)
    return details[0]
예제 #16
0
def job_details(api, job_reference, request=None, **kwargs):
    """Find all available information for a particular job."""
    # Need team reference for 'buyer_team_reference' parameter to Jobs HR API
    (ref, status) = find_team(api, company, team)
    if not ref:
        log.error("Failed to find team {0:s} (company {1:s})".format(team, company))
        return None
    node_name = 'job'
    save_xml = None
    params = [('buyer_team__reference', ref)]
    if kwargs:
        keys = kwargs.keys()
        for key in keys:
            param = valid_jobs_managed_parameter(key)
            if param:
                params.append((param, kwargs[key]))
            elif key == 'save_xml':
                save_xml = kwargs[key]
    url = get_API_URL('jobs_hr')
    xml = send_GET(api, url, params, save_xml=save_xml)
    if xml is None:
        e = "Error, request failed: send_GET(api, {0:s}, {1!s}".format(url, params)
        stderr("{0:s}\n".format(e))
        log.error(e)
        return None
    result = list_from_xml(xml, node_name)
    all_info= ['reference','title','job_type','description','public_url',
        'created_time','created_by','start_date','end_date','filled_date',
        'cancelled_date','buyer_team__reference','buyer_team__id',
        'buyer_team__name','buyer_company__reference','buyer_company__name',
        'visibility','budget','duration','category','subcategory','num_candidates',
        'num_active_candidates','num_new_candidates','last_candidacy_access_time',
        'status'] 
    if not rquest:
        requested_info = all_info[:]
    else:
        requested_info = list_intersect(request, all_info)
    return dict_subset(result, all_info)
예제 #17
0
def user_roles(api, request=None, save_xml=None):
    """Retrieve permission information of user.

    For the currently authenticated user return a list of permission information
    for each company/team the user has access to.

    Parameter 'request' is a list which limits the information returned. Must
    be a subset of:

        ['affiliation_status', 'company__name', 'company__reference',
         'engagement__reference', 'has_team_room_access', 'parent_team__id',
         'parent_team__name', 'parent_team__reference', 'permission',
         'reference', 'role', 'team__id', 'team__name', 'team__reference',
         'user__first_name', 'user__id', 'user__is_provider', 'user__last_name',
         'user__reference']

    """
    url = urls.get_API_URL('user_roles')
    xmlnode = 'userrole'
    if save_xml: save_xml = 'user_roles'
    xml = send_GET(api, url, save_xml=save_xml)
    if xml is None:
        e = "Error, request failed: send_GET(api, {0:s}".format(url)
        stderr("{0:s}\n".format(e))
        log.error(e)
        return None
    roles = list_from_xml(xml, xmlnode)
    all_info = ['affiliation_status', 'company__name', 'company__reference',
         'engagement__reference', 'has_team_room_access', 'parent_team__id',
         'parent_team__name', 'parent_team__reference', 'permission',
         'reference', 'role', 'team__id', 'team__name', 'team__reference',
         'user__first_name', 'user__id', 'user__is_provider', 'user__last_name',
         'user__reference']
    if not request:
        requested_info = all_info[:]
    else:
        requested_info = list_intersect(list(request), all_info)
    return dict_subset(roles, requested_info)
예제 #18
0
from odapi.util import stderr
from odapi.exception import AppUnknownAPIError
from odapi.urls import get_API_URL

if len(sys.argv) == 2:
    if sys.argv[1] == 'xml' or sys.argv[1] == 'json':
        fmt = sys.argv[1]
else:
    fmt = 'xml'

api_tags = ('jobs', 'providers', 'profiles', 'teams', 'companies', 'jobs_hr',
    'engagements', 'company_details', 'company_teams', 'company_teamrooms',
    'company_users', 'user_roles', 'team_users', 'payments', 'teamrooms',
    'teamroom', 'bogus', 'engagement') 


kwargs = {'company_ref':'{company_ref}',
          'team_ref':'{team_ref}',
          'user_ref':'{user_ref}',
          'engagement_ref':'{engagement_ref}',
          'fmt': fmt}

for tag in api_tags:
    try:
        url = get_API_URL(tag, **kwargs)
    except AppUnknownAPIError, e:
        stderr(e)
        assert tag == 'bogus'
        continue
    print url
예제 #19
0
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None:
    api.clean_exit(1)
if popts["request"]:
    req = strip_csv(popts["request"])
    kwargs = str2kwargs(req)
    # request =  req.split(',')
else:
    # request = None
    kwargs = None

# HERE
# stdout('\nquery/test/providers.py: kwargs = {0!r}\n'.format(kwargs))

all_providers = provider_search(api, save_xml=api.debug, **kwargs)
# HERE
if not all_providers or len(all_providers) == 0:
    stderr("No providers returned.\n")
print all_providers
api.clean_exit(0)
#########################################
for n in range(len(all_providers)):
    company = all_providers[n]
    hdr = "------ provider {0:2d} ------\n".format(n + 1)
    stdout(hdr)
    print_dict(stdout, company)
    stdout("\n")
api.clean_exit(0)
예제 #20
0
 
        "buyer_team__id, buyer_team__reference, created_time,
         engagement_job_type, engagement_start_date, engagement_title,
         estimated_duration, estimated_duration_id, hourly_charge_rate,
         hourly_pay_rate, job__reference, job__title, offer__reference,
         provider__id, provider__reference, reference, role, status,
         weekly_hours_limit, weekly_salary_charge_amount,
         weekly_salary_pay_amount"

         Default is to return all of the above.
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None: api.clean_exit(1)
if not len(args) == 1:
    stderr ("\n  ** Need engagement reference number **\n")
    api.clean_exit(usage_tail(pgm, usage, 1))
if popts['request']:
    req = strip_csv(popts['request'])
    request =  req.split(',')
else:
    request = None
ref_no = args[0]
details = engagement_details(api, ref_no, request=request, save_xml=api.debug)
if not details:
    stderr('failed to fetch engagement details\n')
    api.clean_exit(1)
print_dict(stdout, details)
api.clean_exit(0)
예제 #21
0
       "fields" should be a comma-seperated list of fields. This limits the
        information returned and should be a subset of:

        "parent_team__id, is_hidden, status, name, company_name,
         parent_team__name, company__reference, parent_team__reference,
         reference, id"

        For example: -r ""
               or   -r "id"
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None: api.clean_exit(1)
if popts['request']:
    req = strip_csv(popts['request'])
    request =  req.split(',')
else:
    request = None
teamlist = teams(api, request=request,save_xml=api.debug)
if not teamlist or len(teamlist) == 0:
    stderr('failed to fetch team list\n')
hdr = '----- team {0:2d} ----\n'
for n in range(len(teamlist)):
    header = hdr.format(n+1)
    team = teamlist[n]
    stdout(header)
    print_dict(stdout, team)
api.clean_exit(0)
예제 #22
0
    import getopt
    popts = {'brief':False, 'request':None}
    try:
        (opts, args) = getopt.getopt(argv,'br:',['brief','request='])
    except getopt.GetoptError, e:
        stderr(e)
        usage_tail(pgm, usage, 1)
        return (None, None)
    for (key, val) in opts:
        if key == '-r' or key == '--request':
            popts['request'] = to_str(val)
        elif key == '-b' or key == '--brief':
            popts['brief'] = True
        else:
            e = "Error in parseargs code: option parsed by getopt not matched."
            stderr("{0:s}\n".format(e), 'parseargs')
            popts = None
    return (popts, args)

(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parseargs(pgm, argv, usage)
if not len(args) > 0:
    stderr('No provider key(s) given...\n')
    api.clean_exit(1)
#print 'args:', args
#api.clean_exit(1)
provider_keys = ""
for key in args:
    provider_keys += "{0:s} ".format(key)
if popts['request']:
예제 #23
0
    initLogger, setLogLevel

(pgm, ext) = path.splitext(path.basename(sys.argv[0]))

# Test conversions to Python logger levels first
user_levels = ('off', 'debug', 'info', 'warning', 'error', 'critical', 'nosuch')
log_levels = (logging.NOTSET, logging.DEBUG, logging.INFO,
              logging.WARNING, logging.ERROR, logging.CRITICAL)

errors = 0
tests = 0
for n in range(6):
    # convert string log levels to logger values
    pylevel = str2loglevel(user_levels[n])
    if pylevel != log_levels[n]:
        stderr("str2loglevel({0:s}) ({1:d}) failed, got {2:d} ({3:s})\n".format(
            user_levels[n], n, pylevel, user_levels[pylevel/10])) 
        errors += 1
    tests += 1

    # convert logger levers to strings
    strlevel = loglevel2str(log_levels[n])
    if strlevel.lower() != user_levels[n]:
        stderr("loglevel2str({0:d}) failed, got {1:s}\n".format(
            log_levels[n], strlevel))
        errors += 1
    tests += 1

    # convert strings to logger levels 
    pylevel = toLogLevel(user_levels[n])
    if pylevel != log_levels[n]:
        stderr("toLogLevel({0:s}) ({1:d}) failed, got {2:d} ({3:s})\n".format(
예제 #24
0
  [OPTIONS]
  -r, --request "list,of,fields"
        The list should be a comma-seperated list of parameters. This limits the
        information returned and should be a subset of:

        "reference, status, name, owner_user_id"

         Default is to return all of the above.
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None: api.clean_exit(1)
if popts['request']:
    req = strip_csv(popts['request'])
    request =  req.split(',')
else:
    request = None
all_companies = companies(api, request=request, save_xml=api.debug)
if not all_companies or len(all_companies) == 0:
    stderr('failed to fetch company list\n')
    api.clean_exit(1)
for n in range(len(all_companies)):
    company = all_companies[n]
    hdr = '------ company {0:2d} ------\n'.format(n+1)
    stdout(hdr)
    print_dict(stdout, company)
    stdout('\n')
api.clean_exit(0)
예제 #25
0
       list should be a comma-seperated list of parameters.  This limits the
       information returned and should be a subset of:

       "parent_team__id, is_hidden, status, name, company_name,
        parent_team__name, company__reference, parent_team__reference,
        reference, id"

        Default is to return all of the above for each team.        
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None:
    api.clean_exit(1)
if not len(args) == 1:
    stderr("\n  **Need company name**, quoted if needed.\n")
    api.clean_exit(usage_tail(pgm, usage, 1))
company = args[0]
if popts["request"]:
    req = strip_csv(popts["request"])
    request = req.split(",")
else:
    request = None
teamlist = company_teams(api, company, request=request, save_xml=api.debug)
if not teamlist:
    stderr("failed to fetch company team list\n")
    api.clean_exit(1)
hdr = "----- team {0:2d} ----\n"
for n in range(len(teamlist)):
    header = hdr.format(n + 1)
    team = teamlist[n]
예제 #26
0
    popts = {'input':None, 'tag':None, 'output':None}
    try:
        (opts, args) = getopt.getopt(argv, 'i:t:o:h',
                                ['input=', 'tag=', 'output=', 'help'])
    except getopt.GetoptError, e:
        stderr(e)
        exit(usage(pgm, 1))

    for (key, val) in opts:
        if key == '-h' or key == '--help': exit(usage(pgm, 0))
        elif key == '-i' or key == '--input': popts['input'] = to_str(val)
        elif key == '-o' or key == '--output': popts['output'] = to_str(val)
        elif key == '-t' or key == '--tag': popts['tag'] = to_str(val)
        else:
            e = "Error in parseargs code: option parsed by getopt not matched."
            stderr("{0:s}\n".format(e), 'parseargs')
            exit(1)
    return (popts, args)

(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(popts, args) = parseargs(pgm, sys.argv[1:])
if not popts['input']:
    stderr("\n\tNeed input XML file.\n")
    exit(usage(pgm, 1))
if not popts['tag']:
    stderr("\n\tNeed XML node (tag) to parse on.\n")
    exit(usage(pgm, 1))

infile = popts['input']
tag = popts['tag']
outfile = popts['output']
예제 #27
0
파일: main.py 프로젝트: tsinclair/PyDeskAPI
        stderr('{0:s\n', e)
        exit(1)

    auth = popts['auth']
    config = popts['config']
    alias = popts['alias']

    # Put together keyword argument list for find_app_auth()
    kwargs = {'app_name': pgm,             # name of this executable 
              'app_alias': alias,          # --name alias 
              'app_auth': auth,            # --app_auth file
              'auth_envar': 'ODESK_AUTH'}  # environment variable 

    auth = find_app_auth(**kwargs)
    if not auth:
        stderr('No authorization file found.\n')
        exit(1)

    kwargs = {'app_auth_file': auth}
    if alias: kwargs['app_alias'] = alias
    try:
        api = oDeskAPI(config=config, **kwargs)
    except AppInitError, e:
        stderr(e)
        stderr("Failed to initialize oDeskAPI instance...\n")
        exit(1)

    if popts['debug']: api.debug = True

    init_logging(api, popts)
    # Authorize this process with odesk.com developer API
예제 #28
0
         buyer_team__name, buyer_team__reference, category, company__reference,
         company_name, created_by, created_by_name, created_time, description,
         duration, end_date, filled_date, id, job_type, name,
         num_active_candidates, num_candidates, num_new_candidates,
         owner_user_id, parent_team__id, parent_team__name,
         parent_team__reference, public_url, reference, start_date, status,
         subcategory, title, visibility"

         Default is to return all of the above.
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None: api.clean_exit(1)
if not args or not len(args) == 2:
    stderr ("\n  **Need 'company name' 'team name' **, quoted if needed.\n")
    api.clean_exit(usage_tail(pgm, usage, 1))
company = args[0]
team = args[1]
if popts['request']:
    req = strip_csv(popts['request'])
    request =  req.split(',')
else:
    request = None
(total, joblist) = jobs_managed(api, company, team, request=request,
                                                            save_xml=api.debug)
if total == 0:
    stderr("No jobs currently managed by {0:s}\n".format(company))
    api.clean_exit(0)
hdr = '----- Job {0:2d} of {1:d} ----\n'
for n in range(total):
예제 #29
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/
"""Test odapi.query.organization.company_reference_IDs()."""
import sys
from os import path
from odapi.main import app_main
from odapi.util import  stdout, stderr
from odapi.query.organization import company_reference_IDs
usage="""
  Usage: {0:s} [OPTIONS]
         {0:s} --help

    For all companies the authorized user has access to the company name and
    reference Id is returned in a list of dictionary objects.

    The dict object keys are 'name' and 'reference'.

"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)

cIds = company_reference_IDs(api)
if not cIds or len(cIds) == 0:
    stderr('failed to fetch company reference ids\n')
    api.clean_exit(1)
for n in range(len(cIds)):
    item = '{0:2d}: {1:40s} {2:s}\n'.format(
                              n+1, cIds[n]['company'], cIds[n]['ref'])
    stdout(item)
api.clean_exit(0)
예제 #30
0
        information returned and should be a subset of:

        "last_name, first_name, status, id, reference,
         is_provider, timezone, timezone_offset"

        For example: -r "id, last_name, first_name"
               or   -r "id"

         Default is to return all of the above.
"""
(pgm, ext) = path.splitext(path.basename(sys.argv[0]))
(api, argv) = app_main(pgm, sys.argv[1:], usage)
(popts, args) = parse_request(pgm, argv, usage)
if popts is None: api.clean_exit(1)
if len(args) != 1:
    stderr ("\n  ** Need team name **, quoted if necessary.\n")
    api.clean_exit(usage_tail(pgm, usage, 1))
team = args[0]
if popts['request']:
    req = strip_csv(popts['request'])
    request =  req.split(',')
else:
    request = None
userlist = team_users(api, team, request=request, eid=None, save_xml=api.debug)
if len(userlist) == 0:
    log.error('failed to get user list for team {0:s}'.format(team))
    api.clean_exit(1)

hdr = '---- contractor {0:2d} of {1:2d} ----\n'
total = len(userlist)
stdout('------ Team {0:s} ---------\n'.format(team))