def tag_documents(request, label): """ Bulk add documents to a tag, by document pk specified in a multiple 'doc' fields in the request body. """ tag = models.Tag.objects.get_or_create( owner = request.user, label = label.lower(), tag_class = models.Tag.USER) [0] if 'doc' not in request.POST: logging.debug("raise KeyError('at least one document is requried')") else: doc_pk_list = request.POST.getlist('doc') documents = request.user.documents.filter( pk__in = [ int(pk) for pk in doc_pk_list ] ) if len(documents) != len(doc_pk_list): raise ObjectDoesNotExist( 'One or more of the document pks given is invalid') tag.documents.add(documents) return tag_as_json_dict(tag)
def generate_existence(symbol, book): try: assert isinstance(symbol, Symbol) and isinstance(book, Book) except AssertionError: try: assert isinstance(symbol, int) and isinstance(book, int) symbol_ = Symbol.objects.get(id=symbol) book_ = Book.objects.get(id=book) except AssertionError: raise TypeError( "'symbol' and 'book' must be a instances of models or its integer identifiers." ) from None except ObjectDoesNotExist: raise ObjectDoesNotExist( "Can't find objects by identifiers that you passed.") from None else: symbol, book = symbol_, book_ text = get_text(book.file) new_locations_added = 0 if _symbol_exists(symbol.name, text): staff_user = get_user_model().objects.get_or_create( username='******')[0] new_ex = Existence.objects.create(symbol=symbol, book=book, inserter=staff_user) locations, container = _get_locations(symbol.name, text), {} Location.objects.bulk_create([ Location(**_pack_location_params(loc, new_ex, container)) for loc in locations ]) new_locations_added = len(locations) return new_locations_added
def login_authentication(request): if request.method != "POST": return HttpResponse() login_state = {} cookies_id = valid_login_cookies(request) if cookies_id != 0: login_state['authState'] = AuthEnum.LoginSuccess login_state['userID'] = cookies_id print('信息:' + bytes.decode(request.body)) else: try: user_info = json.loads(bytes.decode(request.body)) db_info = UserInfo.objects.get(user_name=user_info["userName"]) if db_info.pass_word == user_info["userPassWD"]: login_state['authState'] = AuthEnum.LoginSuccess login_state['userID'] = db_info.user_id else: raise ObjectDoesNotExist() except ObjectDoesNotExist: login_state['authState'] = AuthEnum.PasswordNotMatch except KeyError: login_state['authState'] = AuthEnum.BrokenJson http_response = HttpResponse(json.dumps(login_state)) if login_state['authState'] == AuthEnum.LoginSuccess and cookies_id == 0: if is_cookies_expired(db_info) != 0: db_info.user_token = get_random_str(64) db_info.save() http_response.set_cookie('userToken', db_info.user_token, max_age=SESSION_EXPIRED, expires=SESSION_EXPIRED) return http_response
def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ try: model = get_model(*request.POST["content_type"].split(".", 1)) obj = model.objects.get(id=request.POST["object_pk"]) if request.method != "POST": raise ObjectDoesNotExist() except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") form = ThreadedCommentForm(request, obj, request.POST or None) if form.is_valid(): comment = form.get_comment_object() if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = request.POST.get("replied_to") comment.save() response = HttpResponseRedirect(comment.get_absolute_url()) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = request.POST.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response else: # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} return render(request, template, context)
def activate_acount(self, user_email): # Getting user by email try: user = User.objects.get(email=user_email) if user: if not user.is_active: user.is_active = True user.save() return user # End if except ObjectDoesNotExist: print("Error finding user by email") raise ObjectDoesNotExist() return None
def run(self, serialized_instance, *args, **kwargs): """ Deserialize input data and start backend operation execution """ try: instance = utils.deserialize_instance(serialized_instance) except ObjectDoesNotExist: raise ObjectDoesNotExist( 'Cannot restore instance from serialized object %s. Probably it was deleted.' % serialized_instance) self.args = args self.kwargs = kwargs self.pre_execute(instance) result = self.execute(instance, *self.args, **self.kwargs) self.post_execute(instance) if result and isinstance(result, django_models.Model): result = utils.serialize_instance(result) return result
def test_failed_db_lookup(): factory = APIRequestFactory() request = factory.post("/foo", {"someFk": "https://example.com/api/v1/bar"}, format="json") with patch("vng_api_common.permissions.BaseAuthRequired._get_obj") as m: m.side_effect = ObjectDoesNotExist("not found in DB") response = View.as_view()(request) assert response.status_code == 400 invalid_params = response.data["invalid_params"][0] assert invalid_params == { "name": "someFk", "code": "object-does-not-exist", "reason": _("The object does not exist in the database"), }
def generate_symbol(symbol_name, book): try: assert isinstance(symbol_name, str) except AssertionError: raise TypeError from None symbol = Symbol.objects.create(name=symbol_name) try: assert isinstance(book, Book) except AssertionError: try: assert isinstance(book, int) and book > 0 book_ = Book.objects.get(id=book) except AssertionError: raise TypeError( "You should pass book model instance or pk of some book." ) from None except ObjectDoesNotExist: raise ObjectDoesNotExist("Can't find book by passed id.") from None else: book = book_ return generate_existence(symbol, book)
def raise_exception(*args, **kwargs): from django.db.models import ObjectDoesNotExist raise ObjectDoesNotExist()