示例#1
0
def profile(request, username):
    user = get_object_or_404(User, username=username)

    if request.method == 'POST':
        old_name = user.profile.name
        old_description = user.profile.description
        form = ProfileForm(request.POST, instance=user.profile)
        if form.is_valid():
            print(form.cleaned_data)
            if user.profile.name != old_name:
                BadgeCache.instance().possibly_award_badge(
                    'on_user_profil_name', user=user)
            if user.profile.description != old_description:
                BadgeCache.instance().possibly_award_badge(
                    'on_user_profil_bio', user=user)
            form.save()
            return redirect('profile', username=username)
    else:
        form = ProfileForm(instance=user.profile)

    last_badges = user.badges_earned.order_by('-awarded_at')[:10]
    last_contents = Content.objects.filter(
        author=user.profile).order_by('-posted_at')[:5]

    return render(
        request, 'profile.html', {
            'profile': user.profile,
            'last_badges': last_badges,
            'last_contents': last_contents,
            'form': form
        })
示例#2
0
    def test_lazy_user(self):
        u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
        PlayerStat.objects.create(user=u, points=5001)
        BadgeCache.instance().possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)

        self.assert_num_queries(1, lambda: u.badges_earned.get().badge)
示例#3
0
def download_dataset(request, dataset_id):
    dataset = get_object_or_404(ProxyDataset,
                                id=dataset_id,
                                exports__has_key='xls')
    dataset.nb_downloads_local += 1
    dataset.save()
    BadgeCache.instance().possibly_award_badge('on_dataset_download',
                                               user=request.user)
    return redirect(dataset.exports['xls'])
示例#4
0
def questions_page(request, dataset_id):
    dataset = get_object_or_404(ProxyDataset, id=dataset_id)
    BadgeCache.instance().possibly_award_badge('on_comment_read',
                                               user=request.user)
    return render(request,
                  "tags/questions_list.html",
                  context={
                      "questions": dataset.questions,
                      "is_registered": request.user.profile.is_registered
                  })
示例#5
0
def add_answer(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    content = Content.objects.create(author=request.user.profile,
                                     text=request.POST["content"])
    source = request.POST["source"] if "source" in request.POST else None
    Answer.objects.create(question=question, content=content, source=source)
    BadgeCache.instance().possibly_award_badge('on_question_answer',
                                               user=request.user)
    return render(request,
                  "question/answers.html",
                  context={"question": question})
示例#6
0
def toggle_like(request, dataset_id):
    dataset = get_object_or_404(ProxyDataset, id=dataset_id)
    liked = dataset not in request.user.profile.liked_datasets.all()
    if liked:
        request.user.profile.liked_datasets.add(dataset)
    else:
        request.user.profile.liked_datasets.remove(dataset)

    BadgeCache.instance().possibly_award_badge('on_dataset_like',
                                               user=request.user)

    return JsonResponse({
        'liked': liked,
        'n_likes': dataset.liking_users.count(),
    })
示例#7
0
def toggle_subscription(request, theme_id):
    theme = get_object_or_404(Theme, id=theme_id)
    subscribed = theme not in request.user.profile.theme_subscriptions.all()
    if subscribed:
        request.user.profile.theme_subscriptions.add(theme)
    else:
        request.user.profile.theme_subscriptions.remove(theme)

    BadgeCache.instance().possibly_award_badge('on_theme_subscription',
                                               user=request.user)

    return JsonResponse({
        'subscribed': subscribed,
        'n_subscriptions': theme.subscribed_users.count(),
    })
示例#8
0
def quiz(request, quiz_id):
    submitted_answers = tuple(
        itertools.chain.from_iterable(
            value for key, value in dict(request.POST).items()
            if key.startswith("question")))

    quiz = get_object_or_404(Quiz, pk=quiz_id)
    choices = check(quiz, submitted_answers)
    submission = QuizSubmission(user=request.user, quiz=quiz, choices=choices)
    submission.save()
    BadgeCache.instance().possibly_award_badge("on_quiz_result",
                                               user=request.user)
    form = QuizForm(quiz, choices)

    return render(request, 'quiz/quiz.html', {'quiz': quiz, 'form': form})
示例#9
0
def add_question(request):
    dataset = None
    if "dataset_id" in request.GET:
        dataset = get_object_or_404(ProxyDataset, id=request.GET["dataset_id"])
    content = Content.objects.create(author=request.user.profile,
                                     text=request.POST["content"])
    Question.objects.create(dataset=dataset, content=content)
    BadgeCache.instance().possibly_award_badge('on_question_ask',
                                               user=request.user,
                                               dataset=dataset)
    if "dataset_id" in request.GET:
        return redirect('questions', dataset_id=dataset.id)
    else:
        return render(request,
                      "tags/questions_list.html",
                      context={
                          "questions":
                          Question.objects.order_by('-content__posted_at')[:5],
                          "is_registered":
                          request.user.profile.is_registered
                      })
示例#10
0
文件: apps.py 项目: balfroim/OpenData
    def ready(self):
        from badge.base import Badge

        # This function needs to be define here because it requires to import the Badge class
        # which requires the app to be loaded before being imported.
        # Else it would throw an AppRegistryNotReady exception.
        def is_badge(cls):
            """Check recursively if the class is a suptype of Badge."""
            if Badge in cls.__bases__:
                return True
            if object in cls.__bases__:
                return False

            for base_cls in cls.__bases__:
                if is_badge(base_cls):
                    return True
            return False

        from badge.registry import BadgeCache

        # Import dynamically all the Badge subclasses in the installed apps.
        for module_name in CUSTOM_APPS:
            try:
                module = importlib.import_module(f"{module_name}.badges",
                                                 package=None)
            except ModuleNotFoundError:
                pass
            else:
                classes = [
                    cls for name, cls in inspect.getmembers(
                        module, inspect.isclass)
                    if is_badge(cls) and not is_abstract(cls)
                ]
                for cls in classes:
                    BadgeCache.instance().register(cls)

        badge_awarded = getattr(importlib.import_module("badge.signals"),
                                "badge_awarded")
示例#11
0
def badge_detail(request, slug, level):
    badge = BadgeCache.instance().get_badge(slug).levels[int(level)]
    badge_awards = BadgeAward.objects.filter(
        slug=slug, level=level).order_by("-awarded_at")

    badge_count = badge_awards.count()
    latest_awards = badge_awards[:50]

    return render(
        request, "badge_detail.html", {
            "badge": badge,
            "badge_count": badge_count,
            "latest_awards": latest_awards,
        })
示例#12
0
def dataset_page(request, dataset_id):
    dataset = get_object_or_404(ProxyDataset, id=dataset_id)
    most_relevant_keywords = sorted([(ship.keyword, ship.relevancy)
                                     for ship in dataset.datasetships.all()],
                                    key=lambda value: value[1],
                                    reverse=True)
    already_matched_ids = {dataset.id}
    already_matched_ids.update(
        (link.to_dataset.all() for link in dataset.to_links.all()))
    init_nb_linked_datasets = len(already_matched_ids)
    datasets_by_keyword = dict()
    for keyword, relevancy in most_relevant_keywords:
        datasets = [
            d for d in keyword.datasets.all()
            if d.id not in already_matched_ids
        ]
        if len(datasets) == 0:
            continue
        datasets_by_keyword[keyword] = datasets
        already_matched_ids.update([d.id for d in datasets])
        if len(datasets_by_keyword) >= 2:
            break
    user = request.user
    user.profile.visited_datasets.add(dataset)
    if request.GET.get('origin', '') == 'quiz':
        BadgeCache.instance().possibly_award_badge('on_linked_quiz_inspect',
                                                   user=user)
    BadgeCache.instance().possibly_award_badge('on_dataset_explore', user=user)
    return render(request,
                  'dataset.html',
                  context={
                      'dataset': dataset,
                      'nb_other_linked_datasets':
                      len(already_matched_ids) - init_nb_linked_datasets,
                      'nb_linked_datasets': len(already_matched_ids) - 1,
                      'datasets_by_keyword': datasets_by_keyword
                  })
示例#13
0
def badge_list(request, username):
    user = get_object_or_404(User, username=username)
    cache = BadgeCache.instance()

    # Make a list of every available badge
    badges = {}
    for badge in cache.badges:
        for level in range(len(badge.levels)):
            name = f'{badge.slug}:{level}'
            badges[name] = {
                'slug': badge.slug,
                'level': level,
                'name': badge.levels[level].name,
                'description': badge.levels[level].description,
                'image': badge.levels[level].image,
                'score': badge.levels[level].score,
                'x': badge.positions[level][0],
                'y': badge.positions[level][1],
                'visible': False,
                'earned': False,
            }

    # Annotate earned badges
    visible_positions = set()
    if user.is_authenticated:
        for badge_obj in user.badges_earned.all():
            name = f'{badge_obj.slug}:{badge_obj.level}'
            badge = badges[name]

            badge['earned'] = True

            x, y = badge['x'], badge['y']
            visible_positions.add((x, y))
            visible_positions.add((x, y - 1))
            visible_positions.add((x + 1, y))
            visible_positions.add((x, y + 1))
            visible_positions.add((x - 1, y))

    # Annotate visible badges
    for badge in badges.values():
        if (badge['x'], badge['y']) in visible_positions:
            badge['visible'] = True

    return render(request, 'badges.html', {
        'badges': badges,
        "profile": user.profile
    })
示例#14
0
    def test_award(self):
        u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
        PlayerStat.objects.create(user=u)
        BadgeCache.instance().possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 0)

        u.stats.points += 5001
        u.stats.save()
        BadgeCache.instance().possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)
        self.assertEqual(u.badges_earned.all()[0].badge.name, "Bronze")

        BadgeCache.instance().possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)

        u.stats.points += 2500
        BadgeCache.instance().possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 2)
示例#15
0
def scores_page(request):
    users = User.objects.filter(profile__is_registered=True)
    users = sorted(users, key=lambda user: user.profile.score, reverse=True)
    BadgeCache.instance().possibly_award_badge("top_1", user=users[0])
    return render(request, 'scores.html', {'users': users})
示例#16
0
 def setUp(self):
     self.user = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
     PlayerStat.objects.create(user=self.user)
     self.user.stats.points += 5001
     self.user.stats.save()
     BadgeCache.instance().possibly_award_badge("points_awarded", user=self.user)
示例#17
0
        "points_awarded",
    ]
    multiple = False

    def award(self, **state):
        user = state["user"]
        points = user.stats.points
        if points > 10000:
            return BadgeAwarded(3)
        elif points > 7500:
            return BadgeAwarded(2)
        elif points > 5000:
            return BadgeAwarded(1)


BadgeCache.instance().register(PointsBadge)


class BaseTestCase(TestCase):
    def assert_num_queries(self, n, func):
        current_debug = settings.DEBUG
        settings.DEBUG = True
        current = len(connection.queries)
        func()
        self.assertEqual(current + n, len(connection.queries), connection.queries[current:])
        settings.DEBUG = current_debug


class BadgesTests(BaseTestCase):
    def test_award(self):
        u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
示例#18
0
 def _badge(self):
     from badge.registry import BadgeCache
     return BadgeCache.instance().get_badge(self.slug)