当前位置: 首页>>代码示例>>Python>>正文


Python models.AbstractNode类代码示例

本文整理汇总了Python中osf.models.AbstractNode的典型用法代码示例。如果您正苦于以下问题:Python AbstractNode类的具体用法?Python AbstractNode怎么用?Python AbstractNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AbstractNode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main(dry_run=True):
    init_app(routes=False)
    from osf.models import AbstractNode
    from website.project.utils import activity

    popular_activity = activity()

    popular_nodes = popular_activity['popular_public_projects']
    popular_links_node = AbstractNode.find_one(Q('_id', 'eq', POPULAR_LINKS_NODE))
    popular_registrations = popular_activity['popular_public_registrations']
    popular_links_registrations = AbstractNode.find_one(Q('_id', 'eq', POPULAR_LINKS_REGISTRATIONS))

    update_node_links(popular_links_node, popular_nodes, 'popular')
    update_node_links(popular_links_registrations, popular_registrations, 'popular registrations')
    try:
        popular_links_node.save()
        logger.info('Node links on {} updated.'.format(popular_links_node._id))
    except (KeyError, RuntimeError) as error:
        logger.error('Could not migrate popular nodes due to error')
        logger.exception(error)

    try:
        popular_links_registrations.save()
        logger.info('Node links for registrations on {} updated.'.format(popular_links_registrations._id))
    except (KeyError, RuntimeError) as error:
        logger.error('Could not migrate popular nodes for registrations due to error')
        logger.exception(error)

    if dry_run:
        raise RuntimeError('Dry run -- transaction rolled back.')
开发者ID:adlius,项目名称:osf.io,代码行数:30,代码来源:populate_popular_projects_and_registrations.py

示例2: activity

def activity():
    """Reads node activity from pre-generated popular projects and registrations.
    New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py`
    Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py`
    """
    # Prevent circular import
    from osf.models import AbstractNode as Node

    # New and Noreworthy Projects
    try:
        new_and_noteworthy_projects = Node.load(settings.NEW_AND_NOTEWORTHY_LINKS_NODE).nodes_pointer
    except AttributeError:
        new_and_noteworthy_projects = []

    # Popular Projects
    try:
        popular_public_projects = Node.load(settings.POPULAR_LINKS_NODE).nodes_pointer
    except AttributeError:
        popular_public_projects = []

    # Popular Registrations
    try:
        popular_public_registrations = Node.load(settings.POPULAR_LINKS_REGISTRATIONS).nodes_pointer
    except AttributeError:
        popular_public_registrations = []

    return {
        'new_and_noteworthy_projects': new_and_noteworthy_projects,
        'recent_public_registrations': utils.recent_public_registrations(),
        'popular_public_projects': popular_public_projects,
        'popular_public_registrations': popular_public_registrations,
    }
开发者ID:adlius,项目名称:osf.io,代码行数:32,代码来源:views.py

示例3: update_node_async

def update_node_async(self, node_id, index=None, bulk=False):
    AbstractNode = apps.get_model('osf.AbstractNode')
    node = AbstractNode.load(node_id)
    try:
        update_node(node=node, index=index, bulk=bulk, async=True)
    except Exception as exc:
        self.retry(exc=exc)
开发者ID:erinspace,项目名称:osf.io,代码行数:7,代码来源:elastic_search.py

示例4: has_object_permission

 def has_object_permission(self, request, view, obj):
     if not isinstance(obj, AbstractNode):
         obj = AbstractNode.load(request.parser_context['kwargs'][view.node_lookup_url_kwarg])
     assert isinstance(obj, AbstractNode), 'obj must be an Node'
     if obj.is_registration:
         return request.method in permissions.SAFE_METHODS
     return True
开发者ID:erinspace,项目名称:osf.io,代码行数:7,代码来源:permissions.py

示例5: _send_global_and_node_emails

def _send_global_and_node_emails(send_type):
    """
    Called by `send_users_email`. Send all global and node-related notification emails.
    """
    grouped_emails = get_users_emails(send_type)
    for group in grouped_emails:
        user = OSFUser.load(group['user_id'])
        if not user:
            log_exception()
            continue
        info = group['info']
        notification_ids = [message['_id'] for message in info]
        sorted_messages = group_by_node(info)
        if sorted_messages:
            if not user.is_disabled:
                # If there's only one node in digest we can show it's preferences link in the template.
                notification_nodes = sorted_messages['children'].keys()
                node = AbstractNode.load(notification_nodes[0]) if len(
                    notification_nodes) == 1 else None
                mails.send_mail(
                    to_addr=user.username,
                    mimetype='html',
                    can_change_node_preferences=bool(node),
                    node=node,
                    mail=mails.DIGEST,
                    name=user.fullname,
                    message=sorted_messages,
                )
            remove_notifications(email_notification_ids=notification_ids)
开发者ID:icereval,项目名称:osf.io,代码行数:29,代码来源:tasks.py

示例6: test_bulk_creates_children_and_sanitizes_html_logged_in_owner

    def test_bulk_creates_children_and_sanitizes_html_logged_in_owner(
            self, app, user, project, url):
        title = '<em>Reasoning</em> <strong>Aboot Projects</strong>'
        description = 'A <script>alert("super reasonable")</script> child'

        res = app.post_json_api(url, {
            'data': [{
                'type': 'nodes',
                'attributes': {
                    'title': title,
                    'description': description,
                    'category': 'project',
                    'public': True
                }
            }]
        }, auth=user.auth, bulk=True)
        child_id = res.json['data'][0]['id']
        assert res.status_code == 201
        url = '/{}nodes/{}/'.format(API_BASE, child_id)

        res = app.get(url, auth=user.auth)
        assert res.json['data']['attributes']['title'] == strip_html(title)
        assert res.json['data']['attributes']['description'] == strip_html(
            description)
        assert res.json['data']['attributes']['category'] == 'project'

        project.reload()
        child_id = res.json['data']['id']
        assert child_id == project.nodes[0]._id
        assert AbstractNode.load(child_id).logs.latest(
        ).action == NodeLog.PROJECT_CREATED
开发者ID:erinspace,项目名称:osf.io,代码行数:31,代码来源:test_node_children_list.py

示例7: test_bulk_creates_children_child_logged_in_write_contributor

    def test_bulk_creates_children_child_logged_in_write_contributor(
            self, app, user, project, child_one, child_two, url):
        write_contrib = AuthUserFactory()
        project.add_contributor(
            write_contrib,
            permissions=[
                permissions.READ,
                permissions.WRITE],
            auth=Auth(user),
            save=True)

        res = app.post_json_api(
            url,
            {'data': [child_one, child_two]},
            auth=write_contrib.auth, bulk=True)
        assert res.status_code == 201
        assert res.json['data'][0]['attributes']['title'] == child_one['attributes']['title']
        assert res.json['data'][0]['attributes']['description'] == child_one['attributes']['description']
        assert res.json['data'][0]['attributes']['category'] == child_one['attributes']['category']
        assert res.json['data'][1]['attributes']['title'] == child_two['attributes']['title']
        assert res.json['data'][1]['attributes']['description'] == child_two['attributes']['description']
        assert res.json['data'][1]['attributes']['category'] == child_two['attributes']['category']

        project.reload()
        child_id = res.json['data'][0]['id']
        child_two_id = res.json['data'][1]['id']
        nodes = project.nodes
        assert child_id == nodes[0]._id
        assert child_two_id == nodes[1]._id

        assert AbstractNode.load(child_id).logs.latest(
        ).action == NodeLog.PROJECT_CREATED
        assert nodes[1].logs.latest().action == NodeLog.PROJECT_CREATED
开发者ID:erinspace,项目名称:osf.io,代码行数:33,代码来源:test_node_children_list.py

示例8: get_settings_url

def get_settings_url(uid, user):
    if uid == user._id:
        return web_url_for('user_notifications', _absolute=True)

    node = AbstractNode.load(uid)
    assert node, 'get_settings_url recieved an invalid Node id'
    return node.web_url_for('node_setting', _guid=True, _absolute=True)
开发者ID:CenterForOpenScience,项目名称:osf.io,代码行数:7,代码来源:emails.py

示例9: handle

    def handle(self, *args, **options):
        guids = options.get('guids', [])
        flag = options.get('flag', False)

        for guid in guids:
            logger.info('Checking Node {}...'.format(guid))
            check_spam(AbstractNode.load(guid), flag=flag)
开发者ID:leb2dg,项目名称:osf.io,代码行数:7,代码来源:check_spam.py

示例10: compile_subscriptions

def compile_subscriptions(node, event_type, event=None, level=0):
    """Recurse through node and parents for subscriptions.

    :param node: current node
    :param event_type: Generally node_subscriptions_available
    :param event: Particular event such a file_updated that has specific file subs
    :param level: How deep the recursion is
    :return: a dict of notification types with lists of users.
    """
    subscriptions = check_node(node, event_type)
    if event:
        subscriptions = check_node(node, event)  # Gets particular event subscriptions
        parent_subscriptions = compile_subscriptions(node, event_type, level=level + 1)  # get node and parent subs
    elif getattr(node, 'parent_id', False):
        parent_subscriptions = \
            compile_subscriptions(AbstractNode.load(node.parent_id), event_type, level=level + 1)
    else:
        parent_subscriptions = check_node(None, event_type)
    for notification_type in parent_subscriptions:
        p_sub_n = parent_subscriptions[notification_type]
        p_sub_n.extend(subscriptions[notification_type])
        for nt in subscriptions:
            if notification_type != nt:
                p_sub_n = list(set(p_sub_n).difference(set(subscriptions[nt])))
        if level == 0:
            p_sub_n, removed = utils.separate_users(node, p_sub_n)
        parent_subscriptions[notification_type] = p_sub_n
    return parent_subscriptions
开发者ID:CenterForOpenScience,项目名称:osf.io,代码行数:28,代码来源:emails.py

示例11: fork_pointer

def fork_pointer(auth, node, **kwargs):
    """Fork a pointer. Raises BAD_REQUEST if pointer not provided, not found,
    or not present in `nodes`.

    :param Auth auth: Consolidated authorization
    :param Node node: root from which pointer is child
    :return: Fork of node to which nodelink(pointer) points
    """
    NodeRelation = apps.get_model('osf.NodeRelation')

    linked_node_id = request.json.get('nodeId')
    linked_node = AbstractNode.load(linked_node_id)
    pointer = NodeRelation.objects.filter(child=linked_node, is_node_link=True, parent=node).first()

    if pointer is None:
        # TODO: Change this to 404?
        raise HTTPError(http.BAD_REQUEST)

    try:
        fork = node.fork_pointer(pointer, auth=auth, save=True)
    except ValueError:
        raise HTTPError(http.BAD_REQUEST)

    return {
        'data': {
            'node': serialize_node_summary(node=fork, auth=auth, show_path=False)
        }
    }, http.CREATED
开发者ID:aaxelb,项目名称:osf.io,代码行数:28,代码来源:node.py

示例12: get_enabled_authorized_linked

def get_enabled_authorized_linked(user_settings_list, has_external_account, short_name):
    """ Gather the number of users who have at least one node in each of the stages for an addon

    :param user_settings_list: list of user_settings for a particualr addon
    :param has_external_account: where addon is derrived from, determines method to load node settings
    :param short_name: short name of addon to get correct node_settings
    :return:  dict with number of users that have at least one project at each stage
    """
    from addons.forward.models import NodeSettings as ForwardNodeSettings

    num_enabled = 0  # of users w/ 1+ addon account connected
    num_authorized = 0  # of users w/ 1+ addon account connected to 1+ node
    num_linked = 0  # of users w/ 1+ addon account connected to 1+ node and configured

    # osfstorage and wiki don't have user_settings, so always assume they're enabled, authorized, linked
    if short_name == 'osfstorage' or short_name == 'wiki':
        num_enabled = num_authorized = num_linked = OSFUser.objects.filter(
            is_registered=True,
            password__isnull=False,
            merged_by__isnull=True,
            date_disabled__isnull=True,
            date_confirmed__isnull=False
        ).count()

    elif short_name == 'forward':
        num_enabled = num_authorized = ForwardNodeSettings.objects.count()
        num_linked = ForwardNodeSettings.objects.filter(url__isnull=False).count()

    else:
        for user_settings in paginated(user_settings_list):
            node_settings_list = []
            if has_external_account:
                if user_settings.has_auth:
                    num_enabled += 1
                    node_settings_list = [AbstractNode.load(guid).get_addon(short_name) for guid in user_settings.oauth_grants.keys()]
            else:
                num_enabled += 1
                node_settings_list = [AbstractNode.load(guid).get_addon(short_name) for guid in user_settings.nodes_authorized]
            if any([ns.has_auth for ns in node_settings_list if ns]):
                num_authorized += 1
                if any([(ns.complete and ns.configured) for ns in node_settings_list if ns]):
                    num_linked += 1
    return {
        'enabled': num_enabled,
        'authorized': num_authorized,
        'linked': num_linked
    }
开发者ID:erinspace,项目名称:osf.io,代码行数:47,代码来源:addon_snapshot.py

示例13: migrate_nodes

def migrate_nodes(index, query=None):
    logger.info('Migrating nodes to index: {}'.format(index))
    node_query = Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False)
    if query:
        node_query = query & node_query
    total = Node.find(node_query).count()
    increment = 200
    total_pages = (total // increment) + 1
    pages = paginated(Node, query=node_query, increment=increment, each=False, include=['contributor__user__guids'])

    for page_number, page in enumerate(pages):
        logger.info('Updating page {} / {}'.format(page_number + 1, total_pages))
        Node.bulk_update_search(page, index=index)

    logger.info('Nodes migrated: {}'.format(total))
开发者ID:adlius,项目名称:osf.io,代码行数:15,代码来源:migrate.py

示例14: setUp

 def setUp(self, *args, **kwargs):
     OsfTestCase.setUp(self, *args, **kwargs)
     if not self.kind:
         return
     self.sanction = self.Factory()
     self.reg = Node.find_one(Q(self.Model.SHORT_NAME, 'eq', self.sanction))
     self.user = self.reg.creator
开发者ID:adlius,项目名称:osf.io,代码行数:7,代码来源:test_tokens.py

示例15: conference_submissions

def conference_submissions(**kwargs):
    """Return data for all OSF4M submissions.

    The total number of submissions for each meeting is calculated and cached
    in the Conference.num_submissions field.
    """
    conferences = Conference.find(Q('is_meeting', 'ne', False))
    #  TODO: Revisit this loop, there has to be a way to optimize it
    for conf in conferences:
        # For efficiency, we filter by tag first, then node
        # instead of doing a single Node query
        projects = set()

        tags = Tag.find(Q('system', 'eq', False) & Q('name', 'iexact', conf.endpoint.lower())).values_list('pk', flat=True)
        nodes = Node.find(
            Q('tags', 'in', tags) &
            Q('is_public', 'eq', True) &
            Q('is_deleted', 'ne', True)
        ).include('guids')
        projects.update(list(nodes))
        num_submissions = len(projects)
        # Cache the number of submissions
        conf.num_submissions = num_submissions
    bulk_update(conferences, update_fields=['num_submissions'])
    return {'success': True}
开发者ID:adlius,项目名称:osf.io,代码行数:25,代码来源:views.py


注:本文中的osf.models.AbstractNode类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。