示例#1
0
def _assign_new_asset_to_adgroups(client,
                                  googleads_client,
                                  account,
                                  asset,
                                  adgroups,
                                  text_type='descriptions'):
    """Assigns the new asset uploaded to the given ad groups, using the mutate
  module."""
    # common_typos_disable
    successeful_assign = []
    unsuccesseful_assign = []
    asset['adgroups'] = []

    if not adgroups:
        return {'asset': asset, 'status': -1}

    for ag in adgroups:
        # mutate_ad returns None if it finishes succesfully
        try:
            mutate.mutate_ad(client, account, ag, asset, 'ADD', text_type)
            successeful_assign.append({"id": ag})
        except Exception as e:
            unsuccesseful_assign.append({
                'adgroup': ag,
                'error_message': error_mapping(str(e)),
                'err': str(e)
            })
    # assignment status:
    #   0 - succesfull,
    #   1 - partialy succesfull,
    #   2 - unsuccesfull,
    #  -1 - no adgroups to assign
    status = 2

    # if successfully assigend only to some ad groups
    if successeful_assign and unsuccesseful_assign:
        status = 1

    # if successefully assigned to all ad groups
    elif successeful_assign:
        status = 0

    # if text assets aren't assigned to any adgroup they weren't uploaded
    if asset['type'] == 'TEXT' and status == 2:
        return {'status': 3, 'unsuccessfull': unsuccesseful_assign}

    if asset['type'] == 'TEXT' and successeful_assign:
        asset = _extract_text_asset_info(googleads_client, account, asset,
                                         successeful_assign[0])

    asset['adgroups'] = successeful_assign
    _update_asset_struct(asset)

    return {
        'asset': asset,
        'status': status,
        'successfull': successeful_assign,
        'unsuccessfull': unsuccesseful_assign
    }
示例#2
0
def _text_asset_mutate(data, asset_id, asset_struct):
    """Handles text asset mutations"""

    asset_handlers = []
    index = 0  # to re-write back to location
    for entry in asset_struct:
        if entry['id'] == asset_id:
            asset_handlers.append({'asset': entry, 'index': index})
        index += 1

    # if only one of headlines/descriptions entries
    # exists in asset_struct, create the second one.
    # if the asset isn't assigned to any adgroup, create both entries
    # create headline entry only if text's len <= 30
    if len(asset_handlers) < 2:
        new_asset = {
            'id': data[0]['asset']['id'],
            'type': 'TEXT',
            'asset_text': data[0]['asset']['asset_text'],
            'adgroups': []
        }
        append = False
        if len(data[0]['asset']['asset_text']) <= 30:
            headline_len = True
        else:
            headline_len = False

        if len(asset_handlers) == 1:
            existing_type = asset_handlers[0]['asset']['text_type']
            if existing_type == 'headlines':
                new_asset['text_type'] = 'descriptions'
                append = True
            elif headline_len:
                new_asset['text_type'] = 'headlines'
                append = True
            if append:
                asset_handlers.append({'asset': new_asset, 'index': None})

        elif len(asset_handlers) == 0:
            new_asset['text_type'] = 'descriptions'
            asset_handlers.append({'asset': new_asset, 'index': None})
            if headline_len:
                new_asset_second = copy.copy(new_asset)
                new_asset_second['adgroups'] = []
                new_asset_second['text_type'] = 'headlines'
                asset_handlers.append({
                    'asset': new_asset_second,
                    'index': None
                })

    successeful_assign = []
    failed_assign = []
    for item in data:
        account = item['account']
        adgroup = item['adgroup']
        action = item['action']
        asset = item['asset']
        text_type_to_assign = item['asset']['text_type_to_assign']

        try:
            mutation = mutate_ad(client, account, adgroup, asset, action,
                                 text_type_to_assign)

        except Exception as e:
            failed_assign.append({
                'adgroup': adgroup,
                'error_message': error_mapping(str(e)),
                'err': str(e)
            })
            mutation = 'failed'
            logging.error('could not execute mutation on adgroup: ' +
                          str(adgroup) + str(e))

        if mutation is None:
            for obj in asset_handlers:
                if obj['asset']['text_type'] == text_type_to_assign:
                    obj['asset'] = _asset_ag_update(obj['asset'], adgroup,
                                                    action)
                    successeful_assign.append(adgroup)

    Service_Class.reset_cid(client)

    for obj in asset_handlers:
        if obj['index']:
            asset_struct[obj['index']] = obj['asset']
        else:
            asset_struct.append(obj['asset'])

    with open(asset_to_ag_json_path, 'w') as f:
        json.dump(asset_struct, f, indent=2)

    if failed_assign and successeful_assign:
        status = 206
    elif successeful_assign:
        status = 200
    else:
        status = 500

    logging.info('mutate response: msg={} , status={}'.format(
        str(asset_handlers), index))
    # switch to this return and tell Mariam the changed return type.
    return _build_response(msg=json.dumps([{
        'asset': asset_handlers,
        'failures': failed_assign
    }]),
                           status=status)
示例#3
0
def mutate():
    """Assign or remove an asset from adgroups.

  gets a json file with a list of asset, account, adgourp and action.
  preforms all of the actions one by one.

  returns a list withthe new asset objects with the changed adgroups list.
  if its a text asset, returns a list with
  both 'headlines' and 'descriptions' entries.
  also changes the asset_to_ag.json file.
  """

    data = request.get_json(force=True)
    logging.info('Recived mutate request: ' + str(data))
    asset_id = data[0]['asset']['id']
    asset_type = data[0]['asset']['type']

    with open(asset_to_ag_json_path, 'r') as f:
        asset_struct = json.load(f)

    # special func for text assets, as they have 2 entries in asset_to_ag.json
    if asset_type == 'TEXT':
        return _text_asset_mutate(data, asset_id, asset_struct)

    asset_handler = {}
    index = 0  # to re-write back to location
    for entry in asset_struct:
        if entry['id'] == asset_id:
            asset_handler = entry
            break
        index += 1

    if not asset_handler:
        asset_handler = data[0]['asset']
        asset_handler['adgroups'] = []
        index = None

    failed_assign = []
    successeful_assign = []
    for item in data:
        account = item['account']
        adgroup = item['adgroup']
        action = item['action']
        asset = item['asset']

        try:
            mutation = mutate_ad(client, account, adgroup, asset, action)
        except Exception as e:
            failed_assign.append({
                'adgroup': adgroup,
                'error_message': error_mapping(str(e)),
                'err': str(e)
            })
            mutation = 'failed'
            logging.error('could not execute mutation on adgroup: ' +
                          str(adgroup))

        if mutation is None:
            successeful_assign.append(adgroup)
            asset_handler = _asset_ag_update(asset_handler, adgroup, action)

    Service_Class.reset_cid(client)

    if index:
        asset_struct[index] = asset_handler
    else:
        asset_struct.append(asset_handler)

    with open(asset_to_ag_json_path, 'w') as f:
        json.dump(asset_struct, f, indent=2)

    if failed_assign and successeful_assign:
        status = 206
    elif successeful_assign:
        status = 200
    else:
        status = 500

    logging.info('mutate response: msg={} , status={}'.format(
        asset_handler, index))

    return _build_response(msg=json.dumps([{
        'asset': asset_handler,
        'index': index,
        'failures': failed_assign
    }]),
                           status=status)