def setup_data(self, count): """ :param count: Number received from command line. default 100 """ json_file = open(self.setup_path + 'sample_data.json') users = json.load(json_file) for user in users[:count]: new_user = User( first_name=user['first_name'], last_name=user['last_name'], username=user['first_name'] + '_' + user['last_name'], email=user['email'], job_title=user['job_title'], ssn=user['ssn'], profile_picture=user['profile_pic'], phone_number=user['phone_number'], company=user['company'], tz=self.random_timezone(), ) new_user.save() new_user.set_password(new_user.username[:5] + new_user.ssn[-4:]) new_user.save() for _ in range(random.randint(1, 10)): from_time = self.generate_from_time() to_time = self.generate_to_time(from_time) activity = Activity( user=new_user, start_time=from_time, end_time=to_time ) activity.save()
def handle(self, *args, **kwargs): total = kwargs['total'] try: for i in range(total): user = User(username=get_random_string(), email='', password='******') user.save() timezone = Timezones(user=user,timezone=random.choice(all_timezones)) timezone.save() activity = Activity(user=user,start_time=gen_datetime(),end_date=gen_datetime()) activity.save() print("user created",i) except Exception as e: print(str(e))
def rejudge(self, request, pk=None, *args, **kwargs): queryset = self.get_queryset() submission = get_object_or_404(queryset, pk=pk) # 如果已经保存了 last rejudge time 的话,与 last rejudge time 比较 # 如果没有保存 last rejudge time 的话, 和 create time 比较 if (submission.last_rejudge_time is not None and timezone.now() < submission.last_rejudge_time + timedelta(minutes=1)) or ( submission.last_rejudge_time is None and timezone.now() < submission.create_time + timedelta(minutes=1)): return Response(msg(err=_('Can\'t Rejudge Within 1 minutes.'))) submission.last_rejudge_time = timezone.now() submission.verdict = Verdict.PENDING submission.additional_info = None submission.save() run_submission_task.apply_async(args=[ submission.id, submission.problem.id, submission.problem.manifest, submission.code, submission.lang, submission.problem.time_limit, submission.problem.memory_limit ], queue='judge') Activity(user=request.user, category=Activity.SUBMISSION, info=f'用户请求Rejudge,提交编号是{submission.id}').save() return Response(msg(SubmissionShortSerializer(submission).data))
def save_event(request): data = json.loads(request.POST["data-for-db"]) if check_for_overlapping_hours(data) == 0: messages.error(request, "Overlapping time interval!") return JsonResponse({"overlapping_error": True}, status=200) if "data-for-db" in request.POST: new_activity = Activity() new_activity.groups = str(data['groups']) new_activity.time_interval = data['timeInterval'] new_activity.course_name = data['courseName'] new_activity.activity_type = data['activityType'] new_activity.teacher_name = data['teacherName'] new_activity.day = data['day'] new_activity.save() return JsonResponse({"created_id": new_activity.id}, status=200) return redirect("home_page")
def handle(self, *args, **options): cursor = connection.cursor() cursor.execute("PRAGMA foreign_keys = OFF;") cursor.execute("delete from users") cursor.execute("delete from user_activity") cursor.execute("PRAGMA foreign_keys = ON;") current_time = now() user_data = [{ "first_name": "Egon", "last_name": "Spengler", "email": "*****@*****.**", "username": "******", "password": "******" }, { "first_name": "Glinda", "last_name": "Southgood", "email": "*****@*****.**", "username": "******", "password": "******" }] for data in user_data: self.stdout.write( self.style.WARNING(f"Creating New User {data['first_name']}")) new_user = CustomUser.objects.create_user( username=data["username"], email=data["email"], password=data["password"], first_name=data["first_name"], last_name=data["last_name"]) user_activity_data = [] for i in range(0, 2): user_activity_data.append( Activity(user=new_user, start_time=current_time - timedelta(hours=i * 2 + 2), end_time=current_time - timedelta(hours=i * 2))) Activity.objects.bulk_create(user_activity_data) api_key = CustomUser.objects.generate_api_key(user_id=new_user.pk) self.stdout.write( self.style.SUCCESS( f"Successfully Created User with ID: {new_user.pk} and API_Key: " f"{api_key}"))
def create(self, request: Request): last_submit_time = request.user.last_submit_time if last_submit_time is not None and timezone.now( ) < last_submit_time + timedelta(seconds=10): return Response( msg(err=_('Can\'t submit twice within 10 seconds.'))) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) submission = serializer.save(user=request.user) run_submission_task.apply_async(args=[ submission.id, submission.problem.id, submission.problem.manifest, submission.code, submission.lang, submission.problem.time_limit, submission.problem.memory_limit ], queue='judge') Activity(user=request.user, category=Activity.SUBMISSION, info=f'用户提交了题目{submission.problem.id},提交编号是{submission.id}' ).save() return Response(msg(SubmissionShortSerializer(submission).data))
def fake_activity(): begin = datetime.date(2019,4,9) end = datetime.datetime.today() for i in range(365): date = begin + datetime.timedelta(days=i) user = User.objects.get(id=1) try: a = Activity.objects.get(activity_date=date,user=user) except: a = Activity() a.user = user a.activity_date = date # c = Article.objects.filter(user=a.user).filter(creat_time=a.activity_date).count() # if c > 3: # c = 4 a.activity_level = random.choice(LEVEL) a.save() print(i)
def get(self, request): '''显示首页''' # 如果是认证用户则显示自己的文章,否则显示管理员的文章 # context = cache.get('index_page') if True: if request.user.is_authenticated: articles = Article.objects.filter( user_id=request.user.id).filter( is_delete=False).order_by('-create_time') # 用户文章数量不够则用管理员的文章补齐4个 if len(articles) < 4: x = 4 - len(articles) articles1 = Article.objects.filter(user_id=1).filter( is_delete=False).order_by('-create_time')[:x] new_articles = chain(articles, articles1) else: new_articles = articles[:4] else: articles = Article.objects.filter(user_id=1).filter( is_delete=False).order_by('-create_time') new_articles = articles[:4] types = ArticleType.objects.all() today = datetime.datetime.today() # 获取最近一年的活动 user = request.user if request.user.is_authenticated else 1 activitys = cache.get('activitys') if not activitys: last_year = today - datetime.timedelta(days=359) #365-6 last_year = get_last_monday(last_year) try: a = Activity.objects.get(user=user, activity_date=today) except: Activity.fake_activity(days=1) finally: tomorrow = today + datetime.timedelta(days=1) activitys = Activity.objects.filter( user=user, activity_date__range=( last_year, tomorrow)).order_by('activity_date') cache.set('activitys', activitys, 60 * 60 * 24) # 获取每日一句 quote = cache.get('quote') if not quote: try: quote = Quote.objects.get(date=today) except: date = today.strftime('%Y-%m-%d') content, translation, author = get_quote(date=date) quote = Quote.objects.create(date=today, quote=content, translation=translation, source=author) quote.save() cache.set('quote', quote, 60 * 60 * 24) for a in articles: a.content = markdown.markdown( a.content, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' ]) # 分页器,若是首页则激活动态这个panel, # 要是有 page 参数则是文章选项卡 paginator = Paginator(articles, 12) page = request.GET.get('page') if page is None: isindex = True page = 1 else: isindex = False articles = paginator.page(page) page = int(page) # 显示前后5页 a = paginator.num_pages if a <= 5: start = 1 end = a else: if page < 5: start = 1 end = 5 elif page > a - 5: start = a - 4 end = a else: start = page - 2 end = page + 2 page_list = list(range(start, end + 1)) # 统计新增文章数量 article_counter = Article.objects.filter( create_time__gt=today).count() articletype_counter = ArticleType.objects.filter( create_time__gt=today).count() if request.user.is_authenticated: notes = Note.objects.filter(owner_id=request.user.id)[:5] else: notes = Note.objects.filter(owner_id=1)[:5] context = { 'quote': quote, 'new_articles': new_articles, 'articles': articles, 'isindex': isindex, 'types': types, 'activitys': activitys, 'article_counter': article_counter, 'articletype_counter': articletype_counter, 'page_list': page_list, 'notes': notes, } # cache.set('index_page',context,60) return render(request, 'index.html', context)
def generate_user_activity(): from user.models import Activity Activity.fake_activity(days=1)