<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def remove_template_from_network(network_id, template_id, remove_attrs, **kwargs):
 """ Remove all resource types in a network relating to the specified template. remove_attrs Flag to indicate whether the attributes associated with the template types should be removed from the resources in the network. These will only be removed if they are not shared with another template on the network """


    try:
        network = db.DBSession.query(Network).filter(Network.id==network_id).one()
    except NoResultFound:
        raise HydraError("Network %s not found"%network_id)

    try:
        template = db.DBSession.query(Template).filter(Template.id==template_id).one()
    except NoResultFound:
        raise HydraError("Template %s not found"%template_id)

    type_ids = [tmpltype.id for tmpltype in template.templatetypes]

    node_ids = [n.id for n in network.nodes]
    link_ids = [l.id for l in network.links]
    group_ids = [g.id for g in network.resourcegroups]

    if remove_attrs == 'Y':
        #find the attributes to remove
        resource_attrs_to_remove = _get_resources_to_remove(network, template)
        for n in network.nodes:
            resource_attrs_to_remove.extend(_get_resources_to_remove(n, template))
        for l in network.links:
            resource_attrs_to_remove.extend(_get_resources_to_remove(l, template))
        for g in network.resourcegroups:
            resource_attrs_to_remove.extend(_get_resources_to_remove(g, template))

        for ra in resource_attrs_to_remove:
            db.DBSession.delete(ra)

    resource_types = db.DBSession.query(ResourceType).filter(
        and_(or_(
            ResourceType.network_id==network_id,
            ResourceType.node_id.in_(node_ids),
            ResourceType.link_id.in_(link_ids),
            ResourceType.group_id.in_(group_ids),
        ), ResourceType.type_id.in_(type_ids))).all()

    for resource_type in resource_types:
        db.DBSession.delete(resource_type)

    db.DBSession.flush()