我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用models.User.DoesNotExist()。
def load_user_from_request(request): """ User login validation logic. If the user exists with the given username and with the correct password then returns the user, otherwise None. Args: request (Request): The flask request object used in endpoint handlers Returns: models.User: The logged user, None if login fails """ if not request.authorization: return None try: user = User.get(User.email == request.authorization['username']) except User.DoesNotExist: return None if user.verify_password(request.authorization['password']): return user return None
def post(self): request_data = request.get_json(force=True) if 'email' not in request_data or 'password' not in request_data: abort(client.BAD_REQUEST) email = request_data['email'] password = request_data['password'] try: user = User.get(User.email == email) except User.DoesNotExist: abort(client.BAD_REQUEST) if not user.verify_password(password): abort(client.UNAUTHORIZED) login_user(user) return generate_response({}, client.OK)
def sign_in(request): if request.method == "POST": account = request.POST.get('account', None) password = request.POST.get('password', None) if not account or not password: return JsonResponse(resultMsg['NeedParameter']) try: user = User.objects(account=account).get() except User.DoesNotExist: return JsonResponse(resultMsg['NotExistUser']) if user.password == password: request.session['currentUser'] = {"_id": str(user.id)} kw = { '_id': str(user.id), 'nickname': user.nickname, 'avatar': user.avatar, 'token': user.token } process_token(**kw) user.reload() return HttpResponse(user.to_json()) return JsonResponse(resultMsg['ErrorPassword']) raise Http404
def authenticated(f): @wraps(f) def decorator(*args, **kwargs): token = (request.json or {}).get('auth') or \ request.values.get('auth') or \ request.cookies.get('auth') request.user = None request.auth = None if token is not None: user_id = get_cache(token) if user_id: try: user = User.get(pk=user_id) except User.DoesNotExist: pass else: request.user = user request.auth = token return f(*args, **kwargs) return decorator
def accept(game_id): try: pool = GamePool.get(GamePool.pk == game_id) except GamePool.DoesNotExist: return send_error('Game not found') except Exception as e: return send_error('Wrong format') if pool.user1 and pool.user1 == request.user: return send_error('You cannot start game with yourself') with config.DB.atomic(): pool.player2 = generate_token(True) pool.user2 = request.user pool.is_started = True pool.save() game = Game.new_game( pool.player1, pool.player2, pool.type_game, pool.time_limit, white_user=pool.user1, black_user=pool.user2 ) delete_cache('wait_{}'.format(pool.player1)) result = {'game': pool.player2} result.update(game.get_info(consts.BLACK)) return send_data(result)
def invited(token): try: enemy_token, game_type, game_limit = get_cache('invite_{}'.format(token)) except: return send_error('game not found') enemy_user = None user_id = get_cache('user_{}'.format(enemy_token)) if user_id: try: enemy_user = User.get(pk=user_id) except User.DoesNotExist: # TODO: if user not found game will be created with None as white player pass user_token = generate_token(True) game = Game.new_game( enemy_token, user_token, game_type, game_limit, white_user=enemy_user, black_user=request.user ) delete_cache('wait_{}'.format(enemy_token)) result = {'game': user_token} result.update(game.get_info(consts.BLACK)) return send_data(result)
def post(self, game_id): try: pool = GamePool.get(GamePool.pk == game_id) except GamePool.DoesNotExist: raise errors.APINotFound('game') except Exception as e: raise errors.APIException('wrong format') if pool.user1 and pool.user1 == request.user: raise errors.APIException('you cannot start game with yourself') pool.player2 = generate_token(True) pool.user2 = request.user pool.is_started = True pool.save() game = Game.new_game( pool.player1, pool.player2, pool.type_game, pool.time_limit, white_user=pool.user1, black_user=pool.user2 ) delete_cache('wait_{}'.format(pool.player1)) result = {'game': pool.player2} result.update(game.get_info(consts.BLACK)) return result
def get(self, token): try: enemy_token, game_type, game_limit = get_cache('invite_{}'.format(token)) except: raise errors.APINotFound('game') enemy_user = None user_id = get_cache('user_{}'.format(enemy_token)) if user_id: try: enemy_user = User.get(pk=user_id) except User.DoesNotExist: # TODO: if user not found game will be created with None as white player pass user_token = generate_token(True) game = Game.new_game( enemy_token, user_token, game_type, game_limit, white_user=enemy_user, black_user=request.user ) delete_cache('wait_{}'.format(enemy_token)) result = {'game': user_token} result.update(game.get_info(consts.BLACK)) return result
def modifyPassword(request): if request.method == "POST": old_password = request.POST.get('old_password',None) new_password = request.POST.get('new_password',None) if not old_password or not new_password: return JsonResponse({'is_success':0}) try: user = User.objects(id = request.session['currentUser']['_id'],password = old_password).get() except User.DoesNotExist: return JsonResponse({'is_success':0}) user.update(password = new_password) user.reload() results = user.to_json() results['is_success'] = 1 return HttpResponse(results) raise Http404
def add_page(request, category_name_slug): try: cat = Category.objects.get(slug=category_name_slug) except Category.DoesNotExist: cat = None if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): if cat: page = form.save(commit=False) page.category = cat page.views = 0 page.save() return category(request, category_name_slug) else: print form.errors else: form = PageForm() context_dict = {'form': form, 'category': cat} return render(request, 'rango/add_page.html', context_dict)
def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/rango/') else: return HttpResponse('Your Rango account is disabled.') try: User.objects.get(username=username) except User.DoesNotExist: print "Invalid login details:{0}, {1}".format(username, password) return HttpResponse("this name does not exist!") print "Invalid login details:{0}, {1}".format(username, password) return HttpResponse("your password is wrong!") else: return render(request, 'rango/login.html', {})
def identity(payload): user_id = payload['identity'] try: g.user = User.get(user_id, None) return g.user except User.DoesNotExist: return None
def load_user(user_id): """ Current user loading logic. If the user exists return it, otherwise None. Args: user_id (int): Peewee user id Returns: models.User: The requested user """ try: return User.get(User.id == user_id) except User.DoesNotExist: return None
def get(self, order_uuid): """ Get a specific order, including all the related Item(s).""" try: order = Order.get(Order.uuid == order_uuid) except Order.DoesNotExist: return None, NOT_FOUND return generate_response(order.json(), OK)
def get_users (): """ TODO: write description """ try: users = User.objects.all() return users except User.DoesNotExist: return []
def get_user_by_id(fbid): """ TODO: get description """ try: user = User.objects.get(user_id=fbid) except User.DoesNotExist: user = None return user
def modify_password(request): if request.method == "POST": old_password = request.POST.get('oldPassword', None) new_password = request.POST.get('newPassword', None) if not old_password or not new_password: return JsonResponse(resultMsg['NeedParameter']) try: update_user = User.objects(id=request.session['currentUser']['_id'], password=old_password).get() except User.DoesNotExist: return JsonResponse(resultMsg['ErrorPassword']) update_user.update(password=new_password) update_user.reload() return HttpResponse(update_user.to_json()) raise Http404
def reset(data): try: user = User.get(User.email == data['email']) except User.DoesNotExist: return send_error('email not found') else: token = user.get_reset() data = { 'username': user.username, 'url': urljoin(config.SITE_URL, config.RECOVER_URL), 'token': token, } send_mail_template('reset', [user.email], data=data) return send_success()
def post(self): try: user = User.get(User.email == self.data['email']) except User.DoesNotExist: raise APINotFound('hey email') token = user.get_reset() data = { 'username': user.username, 'url': urljoin(config.SITE_URL, config.RECOVER_URL), 'token': token, } send_mail_template('reset', [user.email], data=data) return 'send recover email'
def login(self, request): try: user = User.objects.get(phone=request.data.get('account')) password = make_password(request.data.get('password'), "a", 'pbkdf2_sha256') if user.password == password[22:54]: request.session['user'] = user.id return Response({'error': 0, 'user_id': user.id}, status=status.HTTP_200_OK) else: return Response({'error': 'password insistent'}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response({'error': "account does not exists"}, status=status.HTTP_400_BAD_REQUEST)
def logout(self, request): try: user = User.objects.get(phone=request.data.get('account')) del request.session['user'] return Response({'error': 0, 'data': 'logout success'}, status=status.HTTP_200_OK) except User.DoesNotExist: return Response({'error': "account does not exists"}, status=status.HTTP_400_BAD_REQUEST) except KeyError: return Response({'error': 'not logged in'})
def category(request, category_name_slug): context_dict = {} context_dict['result_list'] = None #context_dict['query'] = None if request.method == 'POST': query = request.POST['query'].strip() if query: result_list = run_query(query) context_dict['result_list'] = result_list #context_dict['query'] = query try: category = Category.objects.get(slug=category_name_slug) context_dict['category_name'] = category.name pages = Page.objects.filter(category=category).order_by('-views') context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: pass #if not context_dict['query']: #context_dict['query'] = category.name return render(request, 'rango/category.html', context_dict)
def page(request, page_name_slug): context_dict = {} try: page = Page.objects.get(slug=page_name_slug) context_dict['page'] = page except Page.DoesNotExist: pass return render(request, 'rango/page.html', context_dict)
def patch(self, order_uuid): """ Modify a specific order. """ res = request.get_json(force=True) errors = Order.validate_input(res, partial=True) if errors: return errors, BAD_REQUEST data = res['data']['relationships'] req_items = data.get('items', {}) req_address = data.get('delivery_address') with database.atomic(): try: order = Order.get(uuid=str(order_uuid)) except Order.DoesNotExist: abort(NOT_FOUND) address = None if req_address: try: address = Address.get(Address.uuid == req_address['data']['id']) except Address.DoesNotExist: abort(BAD_REQUEST) order.delivery_address = address # get the user from the flask.g global object registered inside the # auth.py::verify() function, called by @auth.login_required decorator # and match it against the found user. # This is to prevent uses from modify other users' order. if auth.current_user != order.user and auth.current_user.admin is False: return ({'message': "You can't delete another user's order"}, UNAUTHORIZED) # Generate the dict of {<Item>: <int:quantity>} to call Order.update_items items_uuids = [e['id'] for e in req_items.get('data', [])] items = list(Item.select().where(Item.uuid << items_uuids)) if len(items) != len(items_uuids): abort(BAD_REQUEST) items_to_add = { item: req_item['quantity'] for item in items for req_item in req_items.get('data', []) if str(item.uuid) == req_item['id'] } try: order.update_items(items_to_add, new_address=address) except InsufficientAvailabilityException: abort(BAD_REQUEST) return generate_response(order.json(), OK)