Best Python code snippet using django-test-plus_python
user.py
Source:user.py
...19 data = [{"name": k, "city": v} for k, v in CITY.items()]20 data.sort(key=lambda x: x['name'])21 else:22 data = CITY.get(province, [])23 return response_200({'cities': data})24class UserGradeView(generics.GenericAPIView):25 permission_classes = (AllowAny,)26 def get(self, request):27 """28 è·å年级é项29 """30 data = [{'label': g[1], 'value': g[0]} for g in CustomUser.GRADE_CHOICES]31 return response_200({'grades': data})32class UserWorkspaceOfTeacherView(generics.GenericAPIView):33 permission_classes = (IsAuthenticated,)34 def get(self, request):35 """36 è·åèå¸ä»¬çå·¥ä½å°å37 """38 users = CustomUser.objects.filter(role=CustomUser.ROLE_CHOICES[0][0]).values('work_place').distinct()39 return response_200({'work_places': [u['work_place'] for u in users]})40class UserAllWorkspaceOfTeacherView(generics.GenericAPIView):41 permission_classes = (IsAuthenticated,)42 def get(self, request):43 """44 è·åèå¸ä»¬çå·¥ä½å°å45 """46 users = CustomUser.objects.filter(role=CustomUser.ROLE_CHOICES[0][0]).values('work_place').distinct()47 return response_200({'work_places': [u['work_place'] for u in users]})48class UserTeacherOfWorkspaceView(generics.GenericAPIView):49 permission_classes = (IsAuthenticated,)50 def get(self, request):51 """52 GETåæ°`work_space`ï¼è·å该å¦æ ¡ï¼åä½ï¼èå¸ä»¬53 """54 work_space = request.GET.get('work_space', None)55 if work_space:56 users = CustomUser.objects.filter(work_place=work_space)57 return response_200({'teachers': [u.to_dict() for u in users]})58 else:59 return response_404()60class UserInfoView(generics.GenericAPIView):61 """62 ç¨æ·ä¿¡æ¯63 """64 serializer_class = UserInfoSerializer65 permission_classes = (AllowAny,)66 def get(self, request):67 """68 è·åç¨æ·ä¿¡æ¯, é»è®¤ä¸ºæ¬äººçç¨æ·ä¿¡æ¯ï¼ä¼ å
¥getåæ°idåè·å对åºidçç¨æ·ä¿¡æ¯69 å¦ï¼/api/user/info/?id=170 """71 user_id = request.GET.get('id', None)72 if user_id:73 user = get_object_or_404(CustomUser, pk=user_id)74 else:75 if request.user.is_anonymous:76 return response_403()77 user = request.user78 return response_200(user.to_dict(guest=request.user))79 def patch(self, request):80 """æ´æ°ç¨æ·ä¿¡æ¯"""81 serializer = UserInfoSerializer(instance=request.user, data=request.data)82 if not serializer.is_valid():83 return response_400(serializer.errors)84 user = serializer.save()85 return response_200(user.to_dict())86class UserFollowView(generics.GenericAPIView):87 """88 ç¨æ·å
³æ³¨ä¿¡æ¯89 """90 serializer_class = UserFollowSerializer91 permission_classes = (IsAuthenticated,)92 def get(self, request):93 """94 è·åå
³æ³¨å被å
³æ³¨çç¨æ·ï¼é»è®¤è¿å为æ¬äººçç¨æ·å
³æ³¨ä¿¡æ¯ï¼ä¼ å
¥getåæ°idåè·å对åºidçç¨æ·å
³æ³¨ä¿¡æ¯95 å¦ï¼/api/user/follow/?id=196 """97 user_id = request.GET.get('id', None)98 if user_id:99 user = get_object_or_404(CustomUser, pk=user_id)100 else:101 user = request.user102 data = {103 'my_follow': [u.to_dict() for u in user.follow.all()],104 'follow_me': [u.to_dict() for u in user.customuser_set.all()]105 }106 return response_200(data)107 def post(self, request):108 """109 å
³æ³¨110 """111 serializer = UserFollowSerializer(data=request.data)112 if not serializer.is_valid():113 return response_400(serializer.errors)114 request.user.follow.add(serializer.data['user_id'])115 send_push_j(serializer.data['user_id'], '%så
³æ³¨äºä½ ' % (request.user.full_name or request.user.phone, ),116 class_name=Message.CLASS_NAME_CHOICES[2][0], class_id=request.user.id)117 return response_200(request.user.to_dict())118 def delete(self, request):119 """120 åæ¶å
³æ³¨121 """122 serializer = UserFollowSerializer(data=request.data)123 if not serializer.is_valid():124 return response_400(serializer.errors)125 request.user.follow.remove(serializer.data['user_id'])126 return response_200(request.data)127class UserWorksView(generics.GenericAPIView):128 """129 ç¨æ·ä½å130 å¯éGETåæ°`storage_type`ï¼131 * image: å¾ç132 * video: è§é¢133 """134 serializer_class = serializers.Serializer135 permission_classes = (AllowAny,)136 def get(self, request, _id):137 storage_type = request.GET.get('storage_type', None)138 works_s = Works.objects.filter(is_delete=False, user_id=_id)139 if storage_type:140 works_s = works_s.filter(storage__type__startswith=storage_type)141 return response_200({'works': [w.details() for w in works_s]})142class UserFollowTeacherView(generics.GenericAPIView):143 """144 ç¨æ·å
³æ³¨çèå¸145 """146 permission_classes = (IsAuthenticated,)147 def get(self, request):148 teachers = request.user.follow.filter(role=CustomUser.ROLE_CHOICES[0][0])149 recommends = CustomUser.objects.filter(role=CustomUser.ROLE_CHOICES[0][0]).exclude(150 pk__in=teachers).exclude(pk=request.user.id).order_by('?')[:5]151 return response_200({'users': [u.to_dict() for u in teachers], 'recommends': [u.to_dict() for u in recommends]})152class UserFollowStudentView(generics.GenericAPIView):153 """154 ç¨æ·å
³æ³¨çå¦ç155 """156 permission_classes = (IsAuthenticated,)157 def get(self, request):158 students = request.user.follow.filter(role=CustomUser.ROLE_CHOICES[1][0])159 recommends = CustomUser.objects.filter(role=CustomUser.ROLE_CHOICES[1][0]).exclude(160 pk__in=students).exclude(pk=request.user.id).order_by('?')[:5]161 return response_200({'users': [u.to_dict() for u in students], 'recommends': [u.to_dict() for u in recommends]})162class UserFollowWorksView(generics.GenericAPIView):163 """164 ç¨æ·å
³æ³¨ç人çææ°å¨æ165 """166 permission_classes = (IsAuthenticated,)167 def get(self, request):168 follows = request.user.follow.all()169 works_s = Works.objects.filter(user__in=follows, is_delete=False).order_by('-create_time')170 return response_200({'works': [works.details(user=request.user) for works in works_s]})171class UserMessageView(generics.GenericAPIView):172 """173 ç¨æ·æ¶æ¯174 """175 permission_classes = (IsAuthenticated,)176 def get(self, request):177 messages = Message.objects.filter(user=request.user).order_by('-push_time')178 return response_200({'messages': [message.details() for message in messages]})179class UserMessageReadView(generics.GenericAPIView):180 """181 æ è®°æ¶æ¯å·²è¯»182 """183 serializer_class = serializers.Serializer184 permission_classes = (IsAuthenticated,)185 def put(self, request, _id):186 Message.objects.filter(pk=_id).update(is_read=True)187 return response_200({})188class UserMessageChartDetailView(generics.GenericAPIView):189 """190 æ¶æ¯è¯¦æ
191 """192 serializer_class = serializers.Serializer193 permission_classes = (IsAuthenticated,)194 def get(self, request, _id):195 import db.models196 message = get_object_or_404(Message, pk=_id, user=request.user)197 _class = getattr(db.models, message.class_name, )198 if not _class:199 return response_404()200 class_instance = _class.objects.get(pk=message.class_id)201 if isinstance(class_instance, CustomUser):202 return response_200({'user': class_instance.to_dict()})203 works = class_instance if isinstance(class_instance, Works) else class_instance.works204 if request.user.role == CustomUser.ROLE_CHOICES[0][0]:205 teacher = request.user206 else:207 if isinstance(class_instance, Works):208 return response_403()209 teacher = class_instance.user if isinstance(class_instance, WorksComment) else class_instance.to210 chat_list = []211 for c in WorksComment.objects.filter(works=works, user=teacher):212 chat_list.append(c)213 for q in WorksQuestion.objects.filter(works=works, to=teacher):214 chat_list.append(q)215 chat_list.extend(list(WorksQuestionReply.objects.filter(works_question=q)))216 return response_200({217 'works': works.details(), 'teacher_id': teacher.id,218 'chat_list': [{**i.details(), 'class': i.__class__.__name__}219 for i in sorted(chat_list, key=lambda x: x.create_time)]})220class UserQuestionView(generics.ListAPIView):221 """222 ç¨æ·çæé®223 """224 permission_classes = (IsAuthenticated,)225 def get(self, request):226 questions = WorksQuestion.objects.filter(works__user=request.user)227 return response_200({'questions': [{**q.details(), 'works': q.works.details()} for q in questions]})228class UserQuestionDetailsView(generics.ListAPIView):229 """230 ç¨æ·çæé®231 """232 permission_classes = (IsAuthenticated,)233 def get(self, request, _id):234 question = get_object_or_404(WorksQuestion, pk=_id, works__user=request.user)235 data = question.details()236 data['works'] = question.works.details()237 data['reply_list'] = [r.details() for r in question.worksquestionreply_set.all()]238 return response_200(data)239class UserCommentView(generics.ListAPIView):240 """241 ç¨æ·çè¯è®º242 """243 permission_classes = (IsAuthenticated,)244 def get(self, request):245 comments = WorksComment.objects.filter(user=request.user)246 return response_200({'comments': [{**c.details(), 'works': c.works.details()} for c in comments]})247class UserCommentDetailsView(generics.ListAPIView):248 """249 ç¨æ·çè¯è®ºè¯¦æ
ï¼ä½åï¼250 """251 permission_classes = (IsAuthenticated,)252 def get(self, request, _id):253 comment = get_object_or_404(WorksComment, pk=_id, user=request.user)254 data = {}255 data['works'] = comment.works.details()256 data['comments'] = [r.details() for r in WorksComment.objects.filter(works=comment.works, user=request.user)]257 return response_200(data)258class UserReplyView(generics.ListAPIView):259 """260 ç¨æ·çåå¤261 """262 permission_classes = (IsAuthenticated,)263 def get(self, request):264 questions = WorksQuestion.objects.filter(to=request.user)265 return response_200({'reply': [{**r.details(), 'question': q.details(), 'works': q.works.details()} for q in questions for r in q.worksquestionreply_set.all()]})266class UserReplyDetailsView(generics.ListAPIView):267 """268 ç¨æ·çåå¤ï¼æé®ï¼269 """270 permission_classes = (IsAuthenticated,)271 def get(self, request, _id):272 reply = get_object_or_404(WorksQuestionReply, pk=_id, works_question__to=request.user)273 data = {}274 data['question'] = reply.works_question.details()275 data['replies'] = [r.details() for r in reply.works_question.worksquestionreply_set.all()]...
views.py
Source:views.py
...5from .models import Product, ShelfBox, Shelf, Transport6from .api.serializers import ProductSerializer, ShelfSerializer, TransportSerializer7from .const import *8class Responses:9 def response_200(self, data, label=False, success=True):10 response = dict()11 12 if label:13 response[self.label] = data14 else:15 response = data16 17 if success:18 response['success'] = True19 return Response(response, status=status.HTTP_200_OK)20 21 def response_201(self, data):22 response = {23 'success': True,24 self.label: data25 }26 27 return Response(response, status=status.HTTP_201_CREATED)28 29 def response_400(self, data={}):30 return Response(data, status=status.HTTP_400_BAD_REQUEST)31 32 def response_404(self):33 return Response({}, status=status.HTTP_404_NOT_FOUND)34class APIRoot(generics.GenericAPIView):35 name = 'api-root'36 37 def get(self, request):38 return Response({39 'products': reverse('products', request=request),40 'shelfs': reverse('shelfs', request=request),41 'transports': reverse('transports', request=request),42 })43class Products(APIView, Responses):44 label = Product._meta.verbose_name45 46 def get(self, request):47 products = Product.objects.all()48 serializer = ProductSerializer(products, many=True)49 50 return self.response_200(51 serializer.data,52 success=False53 )54 55 def post(self, request):56 serializer = ProductSerializer(data=request.data)57 58 if serializer.is_valid():59 serializer.save()60 61 return self.response_201(62 serializer.data63 )64 65 if serializer.errors.get('name'):66 return self.response_400(ERROR_NAME_TAKEN)67 68 return self.response_400(serializer.errors)69class ProductItem(APIView, Responses):70 label = Product._meta.verbose_name71 72 def get(self, request, id):73 try:74 product = Product.objects.get(id=id)75 serializer = ProductSerializer(product)76 77 return self.response_200(78 serializer.data,79 success=False80 )81 except Product.DoesNotExist:82 return self.response_404()83 84 return self.response_400()85 86 def patch(self, request, id):87 try:88 product = Product.objects.get(id=id)89 90 product.name = request.data.get('name', product.name)91 product.quantity = request.data.get('quantity', product.quantity)92 product.save()93 94 serializer = ProductSerializer(product)95 96 return self.response_200(97 serializer.data,98 label=True99 )100 except Product.DoesNotExist:101 return self.response_404()102 103 def delete(self, request, id):104 try:105 product = Product.objects.get(id=id)106 product.delete()107 108 return self.response_200({})109 except Product.DoesNotExist:110 return self.response_404()111 112class Shelfs(APIView, Responses):113 label = Shelf._meta.verbose_name114 115 def get(self, request):116 shelfs = Shelf.objects.all()117 serializer = ShelfSerializer(shelfs, many=True)118 119 return self.response_200(120 serializer.data,121 success=False122 )123 124 def post(self, request):125 def create_box(box_id):126 if box_id and box_id != 'None':127 return ShelfBox.objects.get(id=box_id)128 else:129 return ShelfBox.create_empty_box()130 131 shelfs = Shelf.objects.all()132 133 if shelfs.count() < SHELF_OBJECTS_MAX_COUNT:134 box1 = create_box(request.data.get('box1'))135 box2 = create_box(request.data.get('box2'))136 box3 = create_box(request.data.get('box3'))137 138 139 shelf = Shelf.objects.create(box1=box1, box2=box2, box3=box3)140 141 serializer = ShelfSerializer(shelf)142 143 return self.response_201(144 serializer.data145 )146 147 return self.response_400(ERROR_MAX_OBJECTS)148class ShelfItem(APIView, Responses):149 label = Shelf._meta.verbose_name150 151 def get(self, request, id):152 try:153 shelf = Shelf.objects.get(id=id)154 serializer = ShelfSerializer(shelf)155 156 return self.response_200(157 serializer.data,158 success=False159 )160 except Shelf.DoesNotExist:161 return self.response_404()162 163 return self.response_400()164 165 def patch(self, request, id):166 try:167 shelf = Shelf.objects.get(id=id)168 169 for box_name in request.data:170 box = getattr(shelf, box_name)171 product_id = request.data[box_name].get('product')172 quantity = request.data[box_name].get('quantity')173 174 if box.product.name == 'EMPTY' and box.product.id == product_id and quantity:175 return self.response_400(ERROR_EMPTY_ARTICLE)176 else:177 try:178 product = Product.objects.get(id=product_id)179 box.product = product180 box.quantity = quantity or 0181 box.save()182 except Product.DoesNotExist:183 pass184 185 serializer = ShelfSerializer(shelf)186 187 return self.response_200(188 serializer.data,189 label=True190 )191 except Shelf.DoesNotExist:192 return self.response_404()193 194 def delete(self, request, id):195 try:196 shelf = Shelf.objects.get(id=id)197 shelf.delete()198 199 return self.response_200({})200 except Shelf.DoesNotExist:201 return self.response_404()202class Transports(APIView, Responses):203 label = Transport._meta.verbose_name204 205 def get(self, request):206 transports = Transport.objects.all()207 serializer = TransportSerializer(transports, many=True)208 209 return self.response_200(210 serializer.data,211 success=False212 )213 214 def post(self, request):215 serializer = TransportSerializer(data=request.data)216 217 if serializer.is_valid():218 serializer.save()219 220 return self.response_201(221 serializer.data222 )223 224 if serializer.errors.get('name'):225 return self.response_400(ERROR_NAME_TAKEN)226 227 return self.response_400(serializer.errors)228class TransportItem(APIView, Responses):229 label = Transport._meta.verbose_name230 231 def get(self, request, id):232 try:233 transport = Transport.objects.get(id=id)234 serializer = TransportSerializer(transport)235 236 return self.response_200(237 serializer.data,238 success=False239 )240 except Transport.DoesNotExist:241 return self.response_404()242 243 return self.response_400()244 245 def patch(self, request, id):246 try:247 transport = Transport.objects.get(id=id)248 249 transport.product_request = request.data.get(250 'product_request', transport.product_request)251 transport.status = request.data.get(252 'status', transport.status)253 transport.save()254 255 serializer = TransportSerializer(transport)256 257 return self.response_200(258 serializer.data,259 label=True260 )261 except Transport.DoesNotExist:262 return self.response_404()263 264 def delete(self, request, id):265 try:266 transport = Transport.objects.get(id=id)267 transport.delete()268 269 return self.response_200({})270 except Transport.DoesNotExist:271 return self.response_404()272 273class Prepare(APIView, Responses):274 def _save(self, *objects):275 for obj in objects:276 obj.save()277 278 def get(self, request):279 products = Product.objects.all().exclude(name='EMPTY')280 shelfs = Shelf.objects.all().iterator()281 transports = Transport.objects.all().filter(status='incoming')282 283 shelf = next(shelfs)284 box = shelf.get_free_box()285 286 for transport in transports:287 product = products.get(name=transport.product_request)288 product_available = product.get_storage()289 290 if product_available:291 free_shelf_space = shelf.get_free_space()292 293 # can't add two products to one box294 if box.product != product:295 box = shelf.get_free_box()296 297 # shelf is full298 if not free_shelf_space or not box:299 shelf = next(shelfs)300 free_shelf_space = shelf.get_free_space()301 box = shelf.get_free_box()302 303 if product_available >= CARGO_MAX_VALUE:304 product.quantity -= CARGO_MAX_VALUE305 306 if box.product.name == 'EMPTY':307 box.product = product308 309 if free_shelf_space >= CARGO_MAX_VALUE:310 box.quantity += CARGO_MAX_VALUE311 else:312 temp = free_shelf_space313 box.quantity += free_shelf_space314 315 self._save(box, shelf)316 317 shelf = next(shelfs)318 free_shelf_space = shelf.get_free_space()319 box = shelf.get_free_box()320 321 box.product = product322 box.quantity += CARGO_MAX_VALUE - temp323 else:324 product.quantity -= product_available325 326 if box.product.name == 'EMPTY':327 box.product = product328 329 if free_shelf_space >= product_available:330 box.quantity += product_available331 else:332 temp = free_shelf_space333 box.quantity += free_shelf_space334 335 self._save(box, shelf)336 337 shelf = next(shelfs)338 free_shelf_space = shelf.get_free_space()339 box = shelf.get_free_box()340 341 box.product = product342 box.quantity += product_available - temp343 344 345 self._save(product, box, shelf)346 347 return self.response_200({})348 ...
model.py
Source:model.py
...19 else:20 results = [json.loads(place.to_json()) for place in places]21 response = {'uuid': str(uuid.uuid4()), 'places': results}22 print(response)23 return self.response_200(response)24 else:25 place = PlaceTable.query.get(data)26 if place is None:27 return self.response_error(400, "ID not found!")28 else:29 return self.response_200({'uuid': str(uuid.uuid4()), 'places': [json.loads(place.to_json())]})30 def post(self):31 status, data = self.get_data()32 if not status:33 places = PlaceTable.query.all()34 if places is None:35 return self.response_error(400, "ID not found!")36 else:37 results = [json.loads(place.to_json()) for place in places]38 response = {'uuid': str(uuid.uuid4()), 'places': results}39 print(response)40 return self.response_200(response)41 id = data.get("id", '')42 if id is None or id is '':43 # No id given... then display all details..44 places = PlaceTable.query.all()45 if places is None:46 return self.response_error(400, "ID not found!")47 else:48 results = [json.loads(place.to_json()) for place in places]49 response = {'uuid': str(uuid.uuid4()), 'places': results}50 print(response)51 return self.response_200(response)52 else:53 place = PlaceTable.query.get(id)54 if place is None:55 return self.response_error(400, "ID not found!")56 else:57 return self.response_200({'uuid': str(uuid.uuid4()), 'places': [json.loads(place.to_json())]})58class CrudHandler(BaseListHandler):59 def __init__(self):60 self.pk_param_name = 'uuid'61 self.collection = 'places'62 def get(self):63 status, data = self.get_url_data()64 data = data.get("id", '')65 if data is None or len(data) == 0:66 # No id given... then display all details..67 places = PlaceTable.query.all()68 if places is None:69 return self.response_error(400, "ID not found!")70 else:71 results = [json.loads(place.to_json()) for place in places]72 response = {'uuid': str(uuid.uuid4()), 'places': results}73 print(response)74 return self.response_200(response)75 else:76 place = PlaceTable.query.get(data)77 if place is None:78 return self.response_error(400, "ID not found!")79 else:80 return self.response_200({'uuid': str(uuid.uuid4()), 'places': [json.loads(place.to_json())]})81 def post(self):82 # Post method to add a place into the table place_table83 status, data = self.get_data()84 if not status:85 return self.response_error(400, "Invalid Post Data")86 name = data.get("name", '')87 if name is None or name is '':88 # No name is given... then show invalid post data..89 return self.response_error(400, "No name element added")90 else:91 place = PlaceTable(data)92 try:93 place.save()94 except SQLAlchemyError as e:95 error = str(e.__dict__['orig'])96 return self.response_error(400, error)97 return self.response_200({'uuid': str(uuid.uuid4()), 'message': "Successfully inserted the place to db."})98 def put(self):99 # Update field..100 status, data = self.get_data()101 if not status:102 return self.response_error(400, "Invalid request")103 data = placetable_schema.load(data, partial=True)104 try:105 place = PlaceTable.get_one_places(data.get("id"))106 except KeyError as e:107 return self.response_error(400, "Invalid id")108 if place is None:109 return self.response_error(400, "ID not found!")110 try:111 place.update(data)112 except SQLAlchemyError as error2:113 return self.response_error(400, str(error2.__dict__['orig']))114 return self.response_200({'uuid': str(uuid.uuid4()), 'message': "Successfully updated Details!"})115 def delete(self):116 # Delete field..117 status, data = self.get_data()118 if not status:119 return self.response_error(400, "Invalid request")120 data = placetable_schema.load(data, partial=True)121 try:122 place = PlaceTable.get_one_places(data.get("id"))123 except KeyError as e:124 return self.response_error(400, "Invalid id")125 if place is None:126 return self.response_error(400, "ID not found!")127 try:128 place.delete()129 except SQLAlchemyError as error2:130 return self.response_error(400, str(error2.__dict__['orig']))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!