def task_save_event_log(user, event_type, detail, address, useragent): event = LoginLog() event.user = user event.event_type = event_type event.detail = detail event.address = address event.useragent = useragent event.save()
def event_log(user, event_type, detail, address, useragent): try: username = user.username except Exception: username = user if platform.system().lower() in ['linux', 'unix']: task_save_event_log.delay(username, event_type, detail, address, useragent) else: event = LoginLog() event.user = username event.event_type = event_type event.detail = detail event.address = address event.useragent = useragent event.save()
def UserRegister(request): # 获取POST参数 username = request.POST.get('username') password = request.POST.get('password') nickname = request.POST.get('nickname') tel = request.POST.get('tel') img_code = request.POST.get('img_code') # 调用Form验证 form_user = UserRegisterForm({ 'username': username, 'password': password, 'nickname': nickname, 'tel': tel, }) if form_user.is_valid(): if User.objects.filter(username=username).only('username').first(): return JsonResponse(USERNAME_EXIST) # 创建用户 user = User() user.username = username user.password = to_md5_hex(password) user.nickname = nickname user.tel = tel now_time = timezone.now().strftime('%Y-%m-%d %H:%M:%S') user.lastvisit = now_time user.save() # 记录用户登录信息 new_login_log = LoginLog() new_login_log.user = user new_login_log.ipaddr = get_ip_address(request) new_login_log.logdate = now_time new_login_log.save() REGISTER_SUCCESS['token'] = uuid1().hex redis_client = get_redis_connection() redis_client.set(LOGIN_SUCCESS['token'], pickle.dumps(user), 3600) return JsonResponse(REGISTER_SUCCESS) else: FORM_ERRORS['msg'] = form_user.errors return JsonResponse(FORM_ERRORS)
def UserLogin(request): # 获取POST参数 username = request.POST.get('username') password = request.POST.get('password') # 获取用户信息 user = User.objects.filter(username=username, password=to_md5_hex(password)).first() if not user: return JsonResponse(LOGIN_ERROR) # 事务环境 或者在视图函数中加上@atomic装饰器, 导入地方跟下面一样 with transaction.atomic(): # 登录成功,进行后续操作 now_time = timezone.now().strftime('%Y-%m-%d %H:%M:%S') user.lastvisit = now_time user.save() new_login_log = LoginLog() new_login_log.user = user new_login_log.ipaddr = get_ip_address(request) new_login_log.logdate = now_time new_login_log.save() LOGIN_SUCCESS['token'] = uuid1().hex redis_client = get_redis_connection() redis_client.set(LOGIN_SUCCESS['token'], pickle.dumps(user), 3600) return JsonResponse(LOGIN_SUCCESS)