Beispiel #1
0
 def user_login(self, request, *args, **kwargs):
     username = request.data.get('username')
     password = request.data.get("password")
     user = User.objects.filter(username=username, password=password)
     if user:
         return MyResponse(data_message="登入成功")
     return MyResponse(data_message="登入失败")
Beispiel #2
0
 def my_destroy(self, request, *args, **kwargs):
     book_obj = self.get_object()
     print("book_obj", book_obj, type(book_obj))
     if not book_obj:
         return MyResponse(500, "删除失败")
     book_obj.is_delete = True
     book_obj.save()
     return MyResponse(200, "删除成功")
Beispiel #3
0
 def login(self, request, *args, **kwargs):
     username = request.query_params.get('username')
     password = request.query_params.get('password')
     user = User.objects.filter(username=username, password=password)
     # print(user)
     if user:
         return MyResponse(data_message="1", results={"username": username})
     return MyResponse(data_status=status.HTTP_422_UNPROCESSABLE_ENTITY,
                       data_message="0")
Beispiel #4
0
def check_user(username: str) -> Union[MyResponse, int]:
    try:
        user = User.get_id(username=username)
        return user.id
    except AttributeError:
        return MyResponse(message=f"{username} does not exist",
                          status_code=Config.NOT_FOUND)
    except Exception as exc:
        return MyResponse(message=f"Error occurred: {exc}",
                          status_code=Config.INTERNAL_ERROR)
Beispiel #5
0
def delete_profile(username: str) -> MyResponse:
    try:
        MapData.delete_from_map_db(username=username)
        User.delete_from_user_db(username=username)
        return MyResponse(f"Profile for {username} was deleted",
                          Config.DELETED)
    except AttributeError:
        return MyResponse(f"User '{username}' does not exist",
                          Config.NOT_FOUND)
    except Exception as exc:
        return MyResponse(f"Error occurred: {exc}", Config.INTERNAL_ERROR)
Beispiel #6
0
 def user_history(username: str):
     user = User.get_id(username=username)
     if user is not None:
         user_id = user.id
         return MyResponse(message=[
             result.results
             for result in MapData.query.filter_by(user_id=user_id).all()
         ],
                           status_code=Config.OK)
     else:
         return MyResponse(message=f"User '{username}' does not exist",
                           status_code=Config.NOT_FOUND)
Beispiel #7
0
def create_profile(user_data: request, username: str) -> MyResponse:
    try:
        new_user = User.init_new(user_data=user_data, username=username)
        DBOperations.persist_to_db(new_user)
        User.set_password(username=username,
                          password=user_data.json.get("password"))
        content = f"Profile for {username} was created"
        email = user_data.json.get('email')
        send_email(content=content, subject="Profile Created", reciever=email)
        return MyResponse(content, Config.CREATED)

    except IntegrityError:
        return MyResponse(f"Username or email already in use", Config.CONFLICT)
    except Exception as exc:
        return MyResponse(f"Error occurred: {exc}", Config.INTERNAL_ERROR)
Beispiel #8
0
def get_reverse_geocode_data(
        username: str, location: Optional[Tuple[float, float]]) -> MyResponse:
    try:
        user_id = check_user(username=username)
        if isinstance(user_id, MyResponse):
            return user_id
        coordinate_location = map_utils.check_param_location(location)
        address = get_an_address(location=coordinate_location)
        new_map_data = MapData.init_new(user_id=user_id,
                                        coordinates=coordinate_location,
                                        results=json.dumps(address))
        DBOperations.persist_to_db(new_map_data)
        return MyResponse(message=f"Successfully got geocode data",
                          status_code=Config.OK)
    except Exception as exc:
        return MyResponse(message=f"An error occurred: {exc}",
                          status_code=Config.INTERNAL_ERROR)
Beispiel #9
0
 def get(self, request, *args, **kwargs):
     # return MyResponse(data_status=status.HTTP_200_OK, data_message="查询成功")
     if 'id' in kwargs:
         employees = self.retrieve(request, *args, **kwargs)
     else:
         employees = self.list(request, *args, **kwargs)
     return MyResponse(data_status=status.HTTP_200_OK,
                       data_message="查询成功",
                       results={"employees": employees.data})
Beispiel #10
0
 def register(self, request, *args, **kwargs):
     user_data = request.data
     if user_data.get('password') and (user_data.get('password') !=
                                       user_data.get('con_password')):
         raise exceptions.ValidationError("两次密码不同")
     user_ser = UserModelSerializer(data=user_data)
     user_ser.is_valid(raise_exception=True)
     with transaction.atomic():
         user_ser.save()
         return MyResponse(data_message="1")
Beispiel #11
0
def exception_handler(exc, context):
    error = "%s--%s--%s" % (context['view'], context['request'].method, exc)
    print(error)

    response = drf_exception_handler(exc, context)
    if response is None:
        return MyResponse(data_status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                          data_message="程序内部错误,请稍等一会儿~",
                          exception=None)
    return response
Beispiel #12
0
    def post(self, request):
        form = forms.RegisterForm(request.data)
        response = MyResponse()
        if form.is_valid():
            clean_data = form.cleaned_data
            username = clean_data.get("username")
            password = clean_data.get("password")
            phone = clean_data.get("phone")
            email = clean_data.get("email")

            with transaction.atomic():
                user = User.objects.create(username=username,
                                           password=password,
                                           phone=phone,
                                           email=email)
            response.data = UserSerializer(user).data
            return Response(response.to_dict())

        else:
            msg = form.errors[list(form.errors.keys())[0]][0]
            return Response(response.error_response(msg=msg))
Beispiel #13
0
def get_nearby_data(
        username: str,
        location: Optional[Tuple[float, float]] = None) -> MyResponse:
    try:
        user_id = check_user(username=username)
        if isinstance(user_id, MyResponse):
            return user_id
        nearby_coordinates = map_utils.check_param_location(location)
        nearby_locations = get_places_nearby(location=nearby_coordinates)
        print(f"Nearby location: {nearby_locations}")
        new_map_data = MapData.init_new(
            user_id=user_id,
            coordinates=nearby_coordinates,
            location_data=map_utils.check_if_next_page_token_exist(
                nearby_locations))
        DBOperations.persist_to_db(new_map_data)
        return MyResponse(message=f"Successfully got location data",
                          status_code=Config.OK)
    except Exception as exc:
        return MyResponse(message=f"An error occurred: {exc}",
                          status_code=Config.INTERNAL_ERROR)
Beispiel #14
0
    def get(self, request, uid=None):
        print(uid)
        response = MyResponse()
        if not uid:
            user_queryset = self.get_queryset()
            if user_queryset.exists():
                response.data = self.get_serializer(user_queryset,
                                                    many=True).data
                return Response(response.to_dict())
            return Response(response.error_response("nothing"))

        else:
            user_obj = self.get_object()
            if user_obj:
                response.data = self.get_serializer(user_obj).data
                return Response(response.to_dict())
            return Response(response.error_response("no one"))
Beispiel #15
0
    def get(self, request, *args, **kwargs):
        # user = User.objects.first()
        # print(user)
        # print(user.groups.first(), type(user.groups.first()))
        # print(user.groups.first().name, type(user.groups.first().name))
        # print(user.user_permissions.all().first().name)

        # group = Group.objects.first()
        # print(group)
        # print(group.permissions.first().name)
        # print(group.user_set.first().username)
        # print(group.user_set.all().values('username'))

        # permission = Permission.objects.filter(pk=4).first()
        # print(permission.user_set.first().username)
        # per = Permission.objects.filter(pk=8).first()
        # print(per.group_set.first().name)
        return MyResponse(data_message="查询成功")
Beispiel #16
0
 def get(self, request, *args, **kwargs):
     try:
         book_id = kwargs.get('id')
         if book_id:
             book_obj = Book.objects.filter(pk=book_id, is_delete=False)
             if book_obj:
                 book_ser = BookModelSerializerV2(book_obj)
                 book_info = book_ser.data
                 message = "单个图书查询成功了"
             else:
                 raise
         else:
             book_list = Book.objects.filter(is_delete=False)
             book_list_ser = BookModelSerializerV2(book_list, many=True)
             book_info = book_list_ser.data
             message = "查询所有图书成功"
         # return Response({
         #     "status": status.HTTP_200_OK,
         #     "message": message,
         #     "results": book_info
         # })
         return MyResponse(status.HTTP_200_OK, message, results=book_info)
     except:
         raise exceptions.NotFound("查询图书失败")
Beispiel #17
0
 def post(self, request):
     response = MyResponse()
     form = forms.LoginForm(request.data)
     if form.is_valid():
         username = form.cleaned_data.get("username")
         password = form.cleaned_data.get("password")
         image_code_id = form.cleaned_data.get("image_code_id")
         image_code = form.cleaned_data.get("image_code")
         try:
             user_obj = self.get_user(username)
             self.checke_captcha(image_code_id, image_code)
             self.check_password(user_obj, password)
         except MyException as e:
             return Response(response.error_response(e.msg))
         response.data = self.login_success(user_obj)
         return Response(response.to_dict())
     else:
         msg = form.errors[list(form.errors.keys())[0]][0]
         return Response(response.error_response(msg=msg))
Beispiel #18
0
 def patch(self, request, *args, **kwargs):
     response = self.partial_update(request, *args, **kwargs)
     return MyResponse(results=response.data)
Beispiel #19
0
 def put(self, request, *args, **kwargs):
     response = self.update(request, *args, **kwargs)
     return MyResponse(results=response.data)
Beispiel #20
0
 def get(self, request, *args, **kwargs):
     if "pk" in kwargs:
         response = self.retrieve(request, *args, **kwargs)
     else:
         response = self.list(request, *args, **kwargs)
     return MyResponse(results=response.data, data_message="查询成功")
Beispiel #21
0
 def get(self, request, *args, **kwargs):
     book_list = Book.objects.filter(is_delete=False).all()
     book_ser = serializers.BookModelSerializer(book_list, many=True)
     book_data = book_ser.data
     return MyResponse(results=book_data)
Beispiel #22
0
 def post(self, request, *args, **kwargs):
     return MyResponse("写操作")
Beispiel #23
0
 def get(self, request, *args, **kwargs):
     return MyResponse("读操作访问成功")
Beispiel #24
0
 def post(self, request, *args, **kwargs):
     return MyResponse(data_message="修改成功")
Beispiel #25
0
def get_all_users() -> MyResponse:
    try:
        return User.get_users()
    except Exception as exc:
        return MyResponse(f"Error occurred: {exc}", Config.INTERNAL_ERROR)
Beispiel #26
0
 def my_create(self, request, *args, **kwargs):
     request_data = request.data
     print(request_data)
     return MyResponse(results="OK")
Beispiel #27
0
def home():
    return create_response(MyResponse("Welcome!", 200))
Beispiel #28
0
 def delete(self, request, *args, **kwargs):
     a = self.destroy(request, *args, **kwargs)
     print(a)
     return MyResponse(http_status=status.HTTP_204_NO_CONTENT)
Beispiel #29
0
 def post(self, request, *args, **kwargs):
     data_ser = BookModelSerializer(data=request.data,
                                    context={'request': request})
     data_ser.is_valid(raise_exception=True)
     data = data_ser.save()
     return MyResponse(results=BookModelSerializer(data).data)
Beispiel #30
0
 def get(self, request, *args, **kwargs):
     return MyResponse(data_message="浏览页面打开成功")