def update_items(): """ Update the DB table containing item info from Riot API. """ items = riot_api.static_get_item_list() Item.objects.all().delete() for k in items['data']: # plaintext and group are not present for every item if 'plaintext' in items['data'][k]: plain_text = items['data'][k]['plaintext'] else: plain_text = None if 'group' in items['data'][k]: group = items['data'][k]['group'] else: group = None item = Item(item_id=items['data'][k]['id'], description=items['data'][k]['description'], name=items['data'][k]['name'], plain_text=plain_text, group=group) item.save()
def addProduct(request: HttpRequest): code = request.POST['code'] name = request.POST['name'] price = request.POST['price'] warning_quantity = request.POST['warning_quantity'] is_chemical = request.POST.get('is_chemical', False) pack_size = request.POST['pack_size'] for_sale = request.POST.get('for_sale', False) valid = True #check to see for conflicts for itm in Item.objects.all(): if itm.code == code: valid = False if valid: item = Item() item.code = code item.name = name item.price = price item.quantity = 0 item.warning_quantity = warning_quantity item.is_chemical = is_chemical item.pack_size = int(pack_size) item.for_sale = for_sale item.save() messages.success(request, 'Product: '+name+' added successfully.') return HttpResponseRedirect('products') else: messages.error(request, 'Product Code: '+code+' already exists.') return HttpResponseRedirect('products')
def create_dummy_items(quantity=2): items = [] for x in range(2): b = Item(name=f'item_{x}', product_code=f'QQ-{x}-{x*3}') b.save() items.append(b) return items
def add_item(): ranking = request.json['ranking'] category_id = request.json['category_id'] same_rank_item = Item.query.filter_by(ranking=ranking, category_id=category_id).first() if same_rank_item is not None: readjust_ranking(int(ranking), None, int(category_id), is_firsttime=True) title = request.json['title'] des = request.json['description'] item_meta = request.json['item_meta'] new_item = Item(title, des, ranking, category_id, item_meta) try: new_item.save() except SQLAlchemyError as e: print(e.args[0]) errorMsg = SERVER_ERROR_MSG return jsonify(error=errorMsg),\ 500, {'Content-Type': 'application/json; charset=utf-8'} return (item_schema.jsonify(new_item), 201, { 'Content-Type': 'application/json; charset=utf-8' })
def add_item(self, order): keyword, amount = self.extract_parameters() if keyword: product = Product.objects.filter(keyword=keyword).first() if product: item = Item(order=order, product=product, amount=amount) item.save() return None return AnswerService.answer( AnswerService.product_not_found(keyword)) return AnswerService.answer(AnswerService.product_is_required())
def generate_mock_data(num_labels, num_items): fake = Faker() fake.add_provider(lorem) labels = [] for _ in range(num_labels): label = Label(name=fake.word()) label.save() labels.append(label) for _ in range(num_items): item = Item(title=fake.sentence(), description=fake.paragraph()) item.save() item.labels.add(*random_subset(labels))
def upload(request): item = Item( \ uid=request.POST["uid"], \ addtime=datetime.datetime.now().strftime("%Y%m%d%H%M%S"), \ status_remove=0, \ imgid=(request.POST["imgid"] if "imgid" in request.POST else "" ), \ iname=(request.POST["iname"] if "iname" in request.POST else "" ), \ imghdw=(request.POST["imghdw"] if "imghdw" in request.POST else 1 ), \ itext=(request.POST["itext"] if "itext" in request.POST else "" ), \ iam=(request.POST["iam"] if "iam" in request.POST else "" ), \ igps=(request.POST["igps"] if "igps" in request.POST else "" ), \ igpswhere=(request.POST["igpswhere"] if "igpswhere" in request.POST else "陕西省" ), \ iwhere=(request.POST["iwhere"] if "iwhere" in request.POST else "" ) \ ) item.save() return HttpResponse(serializers.serialize('json', [ item, ]))
class APIBaseTestCase(APITestCase, URLPatternsTestCase): """Test the Routable API Could be improved to be a generic test for all APIs """ urlpatterns = [ path('api/', include('api.urls')), ] def setUp(self) -> None: self.amount = 12000.0 self.item = Item(amount=self.amount) self.item.save() def new_transaction(self, status=Transaction.STATUS_PROCESSING, location=Transaction.LOCATION_ORIGIN): """ Create and save a new transaction with the class's item instance. :param status: The Desired status :param location: The Desired location :return: The new instance of Transaction """ trans = Transaction( item=self.item, status=status, location=location ) trans.save() return trans def get_latest_transaction(self): """ Retrieves the latest transaction for the item. :return: Transaction """ return Transaction.objects.select_related().filter( item__id=self.item.id).order_by('-updated_at')[0] def assertTransaction(self, transaction, status, location, msg=None): """ Helper assertion method to check a transaction's status and location :param transaction: The transaction :param status: Expected status :param location: Expected location :param msg: Any message you would like to add :return: None """ if transaction.status != status or transaction.location != location: msg = self._formatMessage(msg, 'Transaction in wrong status or location: {} {}, expected: {} {}'.format( transaction.status, transaction.location, status, location )) raise self.failureException(msg) def call_item_endpoint(self, name, response_code_expected=rest_status.HTTP_200_OK): """ Call an endpoint by it's name, then assert the expected response code. :param name: Name of the endpoint :param response_code_expected: The expected response code :return: The response data """ url = reverse(name, args=[self.item.id]) response = self.client.post(url, format='json') self.assertEqual(response.status_code, response_code_expected) return response.data def call_move_endpoint(self, expected_state=Item.STATE_PROCESSING): """ Calls the move endpoint and than asserts that the state is what was expected :param expected_state: The expected state of the Item :return: The response data """ data = self.call_item_endpoint('item-move') self.assertEqual(float(data['amount']), self.item.amount) self.assertEqual(data['state'], expected_state) return data def call_error_endpoint(self, expected_state=Item.STATE_ERROR): """ Calls the error endpoint and than asserts that the state is what was expected :param expected_state: The expected state of the Item :return: The response data """ data = self.call_item_endpoint('item-error') self.assertEqual(float(data['amount']), self.item.amount) self.assertEqual(data['state'], expected_state) return data def call_fix_endpoint(self, expected_state=Item.STATE_CORRECTING): """ Calls the fix endpoint and than asserts that the state is what was expected :param expected_state: The expected state of the Item :return: The response data """ data = self.call_item_endpoint('item-fix') self.assertEqual(float(data['amount']), self.item.amount) self.assertEqual(data['state'], expected_state) return data
ran = random.randint(0, 14) room = gen_room(ranInt=ran, roomId=idCount) idCount += 1 self.grid[x][y] = room room.positionx = x room.positiony = y room.save() w = World() width = 20 height = 20 w.generate_rooms(width, height) item = Item(1, "Torch", "This can light your path in the dark", "Prehistoric Cave", 1) item.save() item = Item(2, "Bag of Jerky", "You can smell the beef", "Prehistoric Cave", 2) item.save() item = Item(3, "Meat Club", "Part snack, part weapon", "Prehistoric Cave", 3) item.save() item = Item(4, "Animal Skin Cloak", "A small amount of protection", "Prehistoric Cave", 4) item.save() item = Item(5, "Dino-Tooth Saber", "Wickedly sharp", "Prehistoric Cave", 5) item.save() item = Item( 6, "Magic Wand", "A smooth stick with some strange engravings on the side. It feels like it has some kind of hidden power.", "Medieval Wizards Tower", 1) item.save() item = Item(
def test_cannot_save_empty_title_items(self): list_ = TodoList.objects.create() item = Item(todo_list=list_, title="") with self.assertRaises(ValidationError): item.save() item.full_clean()
def test_related_item_to_list(self): list_ = TodoList.objects.create() item = Item(title="test") item.todo_list = list_ item.save() self.assertIn(item, list_.items.all())
def post(self, request): data = json.dumps(request.data) data = json.loads(data) if not 'image' in data: return Response({'error': 'no image in request.'}, status=status.HTTP_400_BAD_REQUEST) if not 'mime' in data: return Response({'error': 'no mime in request.'}, status=status.HTTP_400_BAD_REQUEST) mime = data['mime'] if not mime in ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']: return Response({'error': 'mime not accepted'}, status=status.HTTP_400_BAD_REQUEST) ext = mime[6:] salt = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(16)) #data['image']=data['image'] image_string = data['image'] #image_string=image_string.replace('data:%s;base64,'% mime, '') # fh = open("public/static/admin/img/imageToSave.%s" % ext, "wb") # fh.write(base64.b64decode(image_string)) # fh.close() from firebase import Firebase config = { 'apiKey': "AIzaSyD7yT4lfcGx09w0WebnCMsGoNOW31dQm08", 'authDomain': "group-proj-c8dd5.firebaseapp.com", 'databaseURL': "https://group-proj-c8dd5.firebaseio.com", 'projectId': "group-proj-c8dd5", 'storageBucket': "group-proj-c8dd5.appspot.com", 'messagingSenderId': "424365456354", 'appId': "1:424365456354:web:27821c94665e5233" } firebase = Firebase(config) # storage=firebase.storage() # storage.child("storage/%s.%s"%(salt,ext)).put('public/static/admin/img/imageToSave.%s' % ext) asset_bundle = AssetBundle() asset_bundle.salt = salt asset_bundle.kind = 'image' #asset_bundle.base_url=storage.child("storage/%s.%s"%(salt,ext)).get_url(None) print(asset_bundle.base_url) asset_bundle.owner = request.user asset_bundle.save() for k in Asset.KIND_CHOICES: kind = k[0] asset = Asset() asset.asset_bundle = asset_bundle asset.kind = kind asset.extension = salt asset.processing = True asset.save() img = Image.open(BytesIO(base64.b64decode(image_string))) print(img) aspect = img.width / img.height width = 0 height = 0 resized_img = None if kind == 'original': print("ORIGINAL") width = img.width height = img.height resized_img = img.resize((width, height), PIL.Image.ANTIALIAS) elif kind == 'large': print("LARGE") width = 1024 height = aspect * 1024 resized_img = img.resize((int(width), int(height)), PIL.Image.ANTIALIAS) elif kind == 'small': print("SMALL") width = 128 height = aspect * 128 resized_img = img.resize((int(width), int(height)), PIL.Image.ANTIALIAS) else: print("ERROR - size not handled.") fh = open("public/static/admin/img/imageToSave.%s" % ext, "wb") fh.write(base64.b64decode(image_string)) fh.close() storage = firebase.storage() storage.child("storage/%s-%s.%s" % (salt, kind, ext)).put( "public/static/admin/img/imageToSave.%s" % ext) asset.base_url = storage.child("storage/%s-%s.%s" % (salt, kind, ext)).get_url(None) #asset = Asset.objects.get(pk=asset_id) asset.width = width asset.height = height asset.processing = False asset.save() item = Item() item.asset__bundle = asset_bundle item.owner = request.user item.save() serializer = ItemDetailSerializer(item) return Response(serializer.data, status=status.HTTP_200_OK)