def test_create_asset(self): """Asset data is saved correctly.""" asset_uuid = uuid.uuid4() data = { "id": str(asset_uuid), "name": "Asset Name", "asset_class": self.asset_class.name, "easy_to_borrow": True, "exchange": self.exchange.name, "marginable": True, "shortable": True, "status": Asset.ACTIVE, "symbol": "SYMBOL", "tradable": True, } serializer = AssetSerializer(data=data, context={"request": self.request}) self.assertTrue(serializer.is_valid()) asset = serializer.save() self.assertEqual(Asset.objects.count(), 1) self.assertEqual(str(asset.id), data["id"]) self.assertEqual(asset.asset_class.name, data["asset_class"]) self.assertTrue(asset.easy_to_borrow) self.assertEqual(asset.exchange.name, data["exchange"]) self.assertTrue(asset.marginable) self.assertTrue(asset.shortable) self.assertEqual(asset.status, data["status"]) self.assertEqual(asset.symbol, data["symbol"]) self.assertTrue(asset.tradable)
def create_asset_from_dict(self, asset_dict): """Return an assets.models.Asset object from a dictionary of the form accepted by the POST endpoint. The object has also been save()-ed to the database so the pk attribute will be valid. The dictionary is assert-ed to be valid via the is_valid() method on the AssetSerializer. """ asset_serializer = AssetSerializer(data=asset_dict) self.assertTrue(asset_serializer.is_valid()) return Asset.objects.create(**asset_serializer.validated_data)
def test_update_asset(self): """Asset data is updated correctly.""" asset = AssetFactory(name="Old Asset Name", asset_class=self.asset_class, exchange=self.exchange) serializer = AssetSerializer( asset, data={"name": "New Asset Name"}, partial=True, context={"request": self.request}, ) self.assertTrue(serializer.is_valid()) serializer.save() asset.refresh_from_db() self.assertEqual(asset.name, "New Asset Name")
def asset_list(request): """ List all assets, or create a new one :param request: HTTP request object :return: JSON response """ if request.method == 'GET': assets = Asset.objects.all() serializer = AssetSerializer(assets, many=True) return Response(serializer.data) elif request.method == 'POST': # Check that admin user is creating objects user = request.META.get('HTTP_X_USER', 'anon') if user != 'admin': print([user for user in sorted(request.META.keys())]) return Response('Only admin user can create assets', status=status.HTTP_401_UNAUTHORIZED) data = JSONParser().parse(request) serializer = AssetSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def retrieve(self, request, *args, **kwargs): group_obj = self.get_object() queryset = group_obj.asset_set.all() serializer = AssetSerializer(queryset, many=True) data = { "count": len(serializer.data), "results": serializer.data } return response.Response(data)
def asset_typefilter(request, type_name): """ List assets filtered by the provided type string :param request: Django HTTP :param type_name: The name of the type to perform filtering :return: Response with appropriate assets """ if request.method == 'GET': assets = Asset.objects.filter(asset_type=type_name) if not assets: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = AssetSerializer(assets, many=True) return Response(serializer.data)
def AssetList(request): if request.method == 'GET': asset_list = models.Asset.objects.all() serializer = AssetSerializer(asset_list,many=True) return Response(serializer.data) elif request.method == 'POST': serializer = AssetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_view_asset(self): """Asset data is serialized correctly.""" asset = AssetFactory(asset_class=self.asset_class, exchange=self.exchange) data = AssetSerializer(asset, context={"request": self.request}).data self.assertEqual(Asset.objects.count(), 1) self.assertEqual(data["id"], str(asset.id)) self.assertEqual(data["asset_class"], asset.asset_class.name) self.assertTrue(data["easy_to_borrow"]) self.assertEqual(data["exchange"], asset.exchange.name) self.assertTrue(data["marginable"]) self.assertTrue(data["shortable"]) self.assertEqual(data["status"], asset.status) self.assertEqual(data["symbol"], asset.symbol) self.assertTrue(data["tradable"])
def asset_detail(request, pk): """ Retrieve an asset with its corresponding details Updating and deleting assets is not allowed in this API :param request: HTTP request object :param pk: Asset's primary key, which is its unique name :return: JSON response """ try: asset = Asset.objects.get(pk=pk) except Asset.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AssetSerializer(asset) return Response(serializer.data) else: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def AssetList(request): ''' django调用restframework的serializer和response定制自己的视图方法 ''' if request.method == 'GET': asset_list = models.Asset.objects.all() #many表示传入的是一个结果集,得到的结果是一个可序列化的OrderedDict serializer = AssetSerializer(asset_list, many=True) print(serializer.data) #使用restframework封装的Response return Response(serializer.data) elif request.method == 'POST': serializer = AssetSerializer(data=request.POST) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, pk, format=None): assets = self.get_objects(pk) serializer = AssetSerializer(assets, many=True) return Response(serializer.data)