def docs_in_add_item(request, document_id): document = get_object_or_404(Document, pk=document_id, doc_type=0) if request.method == "POST": form = ItemForm(request.POST) if form.is_valid(): # найдем такой же груз items = Item.objects.filter( factory_number=form.cleaned_data["factory_number"]) if items.exists(): # пока берем первый, но вообще единица должна быть уникальной item = items.first() else: item = Item( name=form.cleaned_data["name"], factory_number=form.cleaned_data["factory_number"], passport_number=form.cleaned_data["passport_number"], weight=form.cleaned_data["weight"], ) item.save() entry = ItemEntry(description=form.cleaned_data["description"], item=item, operation=document.operation) entry.save() return HttpResponseRedirect( reverse('main:docs_in_edit', args=(document.pk, )))
def get_items_booked_by_user(code, n_latest): items = Booking.objects \ .filter(hh_user__pk=code) \ .values('item', 'item__name', 'item__uri', 'item__image_uri') \ .annotate(max_dt=Max('dt')) \ .order_by('-max_dt')[:n_latest] return [ Item(code=item["item"], name=item["item__name"], uri=item["item__uri"], image_uri=item["item__image_uri"]).as_dict() for item in items ]
def test_item_json_cast(self, mock_default_item: Item): """ Tests item .json() method """ expected_dict = { "item_name": mock_default_item.item_name, "summary": mock_default_item.summary, "content": mock_default_item.content, "date_published": mock_default_item.date_published, "item_slug": mock_default_item.item_slug, "category_name": mock_default_item.category_name, } assert mock_default_item.to_json() == expected_dict
def test_send_notification_is_called_on_first_save( self, monkeypatch, mock_default_item: Item, mock_email_host_user: str): """ Tests the send_email_notification_to_users function is called when saving an item Tests that the email notification is only sent when the item is first saved. Modifying an existing item and calling .save() should not trigger the email_notification function. """ mock_send_email_notification = Mock() monkeypatch.setattr( Item, "send_email_notification_to_users", mock_send_email_notification, ) mock_default_item.save() mock_send_email_notification.assert_called_once() mock_default_item.item_name = "updated name" mock_default_item.save() mock_send_email_notification.assert_called_once()
def default_item(parent_category: Category, item_id: int = DEFAULT_ID, **kwargs) -> Item: """ Generates a default mock Item object when calling MockItem.default_item(). In a similar way as the Category class, distincts Item objects can be created: - By providing unique `_id` values. - And/or by providing a number of custom kwargs. One thing to note is the `parent_category` argument, which is the Category object the Item "belong to". If the given category object does not exist in the database, then the item creation fails with an error message. """ if parent_category.category_name not in [ cat.category_name for cat in Category.objects.all() ]: print( f"""Parent category {parent_category} does not exist in the databse.\n Please creating it prior to running this function.""") sys.exit() _id = f"{parent_category.id}-{item_id}" item_data = { "item_name": kwargs.get("item_name", f"{MockItem.DEFAULT_ITEM_NAME}{_id}"), "summary": kwargs.get("summary", f"{MockItem.DEFAULT_SUMMARY}{_id}"), "content": kwargs.get("content", f"{MockItem.DEFAULT_CONTENT}{_id}"), "date_published": kwargs.get( "date_published", f"{MockItem.DEFAULT_DATE}", ), "item_slug": kwargs.get("item_slug", f"{MockItem.DEFAULT_ITEM_SLUG}{_id}"), "category_name": parent_category, } dummy_item = Item.create(item_data) return dummy_item
def check_can_delete_post(user, item): if not user.has_post(item=item): if Item.is_post_with_id_a_community_post(item.pk): if not user.is_moderator_of_community_with_name( item.community.name) and not user.is_administrator_of_community_with_name(item.community.name): raise ValidationError( 'Только модераторы/администраторы могут удалять записи.', ) else: item.community.create_remove_post_log(source_user=user, target_user=item.creator) else: raise ValidationError( 'Вы не можете удалить запись, которое вам не принадлежит' )
def register(user_id): login_user_check(user_id) if request.method == "POST": user_id = user_id item_name = request.form.get('item_name') url = request.form.get('url') price = get_price(url) if price is None: flash("商品価格の取得に失敗しました。もう一度お試しください。", "info") return redirect(url_for("item.register", user_id=user_id)) latest_price = price lowest_price = price if item_name: item = Item(user_id, item_name, url, latest_price, lowest_price) db.session.add(item) db.session.commit() p = Price(item.id, price) db.session.add(p) db.session.commit() draw_graph(item.id) return redirect(url_for('user.mypage', user_id=user_id)) else: return redirect(url_for("item.register", user_id=user_id)) return render_template("item_register.html", user_id=user_id)
def test_item_list_class_property(self, load_default_items: List[Item]): """ Tests __item_list contains a list of saved items """ assert Item.get_item_list() == load_default_items
def createItemFromData(soup, restaurant): name = soup.find('dd').text name = name.replace('®', '') name = name.replace('©', '') type_of_item = 'meal' for dd in soup.find_all('dd'): if 'fl oz' in dd.text: floz = int(dd.text.split(' ')[-3]) type_of_item = 'drink' for metric in dd.find_all('li'): if "Calories " in metric.text: calories = int(metric.text.split(' ')[-1]) elif "Total Fat" in metric.text: total_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Saturated Fat" in metric.text: sat_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Trans Fat" in metric.text: trans_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Cholesterol" in metric.text: cholesterol = Decimal(metric.text.split(' ')[-1].strip('mg')) elif "Sodium" in metric.text: sodium = Decimal(metric.text.split(' ')[-1].strip('mg')) elif "Carbohydrates" in metric.text: carbs = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Fiber" in metric.text: fiber = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Sugar" in metric.text: sugar = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Protein" in metric.text: protein = Decimal(metric.text.split(' ')[-1].strip('g')) item = Item(name=name, restaurant=restaurant, type_of_item=type_of_item, calories=calories, protein=protein, carbs=carbs, total_fat=total_fat, sat_fat=sat_fat, trans_fat=trans_fat, cholesterol=cholesterol, sodium=sodium, sugar=sugar, fiber=fiber, floz=floz if type_of_item == 'drink' else 0) print(f"Name: {item.name}") print(f"Restaurant: {item.restaurant}") print(f"Type Of Item: {item.type_of_item}") print(f"Calories: {item.calories}") print(f"Protein: {item.protein}") print(f"Carbs: {item.carbs}") print(f"Total Fat: {item.total_fat}") print(f"Saturated Fat: {item.sat_fat}") print(f"Trans Fat: {item.trans_fat}") print(f"Cholesterol: {item.cholesterol}") print(f"Sodium: {item.sodium}") print(f"Sugar: {item.sugar}") print(f"Fiber: {item.fiber}") print(f"Fl Oz: {item.floz}") print('-' * 40) item.save() print("O" * 50) print("Saved Item to Database") print("O" * 50) return item
def load_default_item(mock_default_item: Item) -> Item: """Save a default item object, and return the object""" if mock_default_item not in Item.objects.all(): mock_default_item.save() return mock_default_item
def test_item_model_has_required_fields(self): item = Item() self.assertRaises(IntegrityError, item.save)
def item(request): """ * get itn:item_num每次取得贴子条数 st:start_pos:开始条数 cat:catalog :分类 tag:拼音缩写 JY ZH PC XK XR TC todo 管理员自定义 # todo :缓存 #todo 用户id查询 #todo 用户id ps :删除在post的基础上op=DELETE *post """ res = "" op = request.POST.get("op", None) if request.method == "GET": item_num = request.GET.get('itn', 10) start_pos = request.GET.get("st", None) catalog = request.GET.get("tag", "all") # TODO page = request.GET.get("pg", 1) # 上拉刷新 if start_pos is None: select_obj = Item.objects.all() start_pos = Item.objects.order_by('-pk').first().id # 下拉刷新,前端自动返回启刷的id else: # 只搜索id值小于起始点的 select_obj = Item.objects.filter(pk__lte=start_pos) # 图片请求令启一个api,减轻服务器压力 select_obj = select_obj.order_by('-pk').values() paginator = Paginator(select_obj, item_num) try: content = paginator.page(page) except PageNotAnInteger as e: content = paginator.page(1) print(e) # todo 改log except EmptyPage as e: # 是invalid的子类要放在前面 #todo 前端要判断最后一页到了没,到了就不能在页面加载最后一页了 content = paginator.page(paginator.num_pages) print(e) except InvalidPage as e: content = paginator.page(1) print(e) # todo 改log # for per_item in content: # if() # content=serializers.serialize("json", content, ensure_ascii=False) content = list(content) data = { 'mag': 'ok', 'status': 200, 'per_page': int(paginator.per_page), 'num_page': int(paginator.num_pages), 'start_pos': start_pos, "page_now": page, 'content': content } return JsonResponse(data) # end if ########### # 发帖 elif request.method == "POST" and op is None: i_title = request.POST.get('ttl', False) i_content = request.POST.get('cnt', False) # 内容 i_tag = request.POST.get('tag', False) # 标签 i_p_id = request.POST.get('p_id', False) # 发帖人id #todo 身份验证 i_id = request.POST.get('i_id', False) if i_title and i_tag and i_content and i_p_id: dict_to_add = { 'i_title': i_title, 'i_content': i_content, 'i_tag': i_tag, 'i_p_id': i_p_id } try: if not i_id: it = Item(**dict_to_add) it.save() msg = 'add_success' else: it = Item.objects.filter(pk=i_id) it.update(**dict_to_add) # 创建并写入数据库 msg = 'update_success' # 先储存否则外码设置有问题 # todo 图片修改? if request.FILES: image_list = request.FILES.getlist("img") for image in image_list: img = Image(file=image, item=it) img.save() return JsonResponse({"msg": msg, 'status': 200}) except Exception as e: res = str(e) else: res = "missing argument" elif request.method == "POST" and op == "DELETE": i_p_id = request.POST.get('p_id', False) # 发帖人id #todo 身份验证 i_id = request.POST.get('i_id', False) # todo 无法访问 if not Item.objects.filter(pk=i_id).exists(): res = "not found" else: the_item = Item.objects.filter(pk=i_id).first() print(the_item) print(i_p_id) print(i_id) print(the_item.i_p_id) if not i_p_id or the_item.i_p_id != i_p_id: res = "no access to delete" else: the_item.delete() return JsonResponse({"msg": 'delete_success', 'status': 200}) return JsonResponse({"msg": 'illegal operation::' + res, "status": 400})
def daemon_add_item(self, url, title, snippet, published_time, channel_id): """ return 0(int) if succeed; otherwise return error message Add channel_id if existing item doesn't have one; or append a channel_id if existing item has some Add channel_id for new item """ try: url = url.strip() title = title.strip() snippet = snippet.strip() if not url or not title: return 'Error: url or title is null' maxlength = 5242880 #5 * 1024 * 1024bytes = 5MB # redirect_return_value = process_redirect(url, maxlength) # if 'url' in redirect_return_value: # url = redirect_return_value['url'] # else: # return redirect_return_value['error'] url = url_normalize(url, charset='utf-8') parsed = urlparse.urlparse(url) #can be used to judge the source of item if url.find('www.') == -1: url_alias = 'http://' + 'www.' + url.replace('http://', '') else: url_alias = 'http://' + url.replace('http://www.', '') url_set = Item.objects.filter(url=url) url_alias_set = Item.objects.filter(url=url_alias) if len(url_set) > 0 or len(url_alias_set) > 0: if channel_id: #we need to update the channels for the existing news if len(url_set) > 0: item = url_set[0] else: item = url_alias_set[0] if item.channels: id_list = item.channels.split(',') if not str(channel_id) in id_list: id_list.append(str(channel_id)) item.channels = ','.join(id_list) item.save() else: item.channels = str(channel_id) item.save() return 'Error: The item already exists.' headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', #Accept-Language: en-us,en;q=0.5 #Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 'Keep-Alive': '115' , 'Connection': 'keep-alive' , 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.797.0 Safari/535.1' } req = urllib2.Request(url, headers=headers) response = urllib2.urlopen(req, timeout=20) url = response.url url = url_normalize(url, charset='utf-8') #ensure url is normalized after redirect webpage = response.read(maxlength + 1) if len(webpage) == maxlength + 1: return "Error: The webpage is more than max length" if response.info().get('Content-Encoding') == 'gzip': buf = StringIO(webpage) f = gzip.GzipFile(fileobj=buf) webpage = f.read() webpage_name = generate_random_file_name(32) + '.html' f = open(settings.MEDIA_ROOT + 'webpage/' + webpage_name, 'w+') f.write(webpage) #Do not use unicode(soup) here, it will produce error on Linux server f.close() item = Item(name=title[:200], url=url[:255], snippet=snippet[:600], share_count=0, file='webpage/' + webpage_name) item.creator_id = None item.create_date = published_time if channel_id: item.channels = str(channel_id) item.save() return 0 except: return 'Error in getting webpage'
def handle(self, *args, **options): restaurant_count = options["count"] # keep track of used names, streets etc. in the variables below, # so we can prevent duplicates names = [] streets = [] cities = [] # XXX factorize into smaller functions for item in range(restaurant_count): print "generate restaurant %d" % (item + 1) r = Restaurant() r.name = gen_unique_name(names, restaurant_names) r.save() print "generate address" a = Address(country=random.choice(_countries)) a.street = gen_unique_name(streets, street_names) a.street_no = random.randint(1, 100) a.zip = random.randint(1000, 100000) a.city = gen_unique_name(cities, city_names) a.restaurant = r a.save() count = random.randint(5, 25) print "generate %d tables" % count for i in range(1, 1 + count): t = Table() t.restaurant = r t.no = i t.save() print "add supported payment methods" for _ in range(2, len(_payment_methods)): method = random.choice(_payment_methods) if method not in r.payment_method.all(): r.payment_method.add(method) r.save() print "generate menu" m = Menu() m.currency = random.choice(_currencies) m.language = _languages[2] m.restaurant = r m.save() m.translations.add(_languages[0]) m.translations.add(_languages[1]) m.save() items = [] _cat_names = [] count = random.randint(3, 12) itemid = 1 print "generate %d categories" % count for j in range(1, 1 + count): c = Category() c.menu = m c.ordering = j c.view = random.choice(_views) c.save() count = random.randint(4, 20) # i18n stuff name = gen_unique_name(_cat_names, category_names) for lang in _languages: c18n = CategoryI18n() c18n.category = c c18n.language = lang c18n.name = name if lang.abbr != "en": c18n.name += "(%s)" % lang.abbr c18n.save() print "generate %d items" % count for _ in range(1, count): item = Item() item.no = itemid itemid += 1 item.category = c item.price = "%.2f" % random.uniform( 1, 110) # 2 decimal points item.save() item.image.save("item%d.jpg" % item.id, random.choice(_pictures), save=True) count = random.randint(0, 8) # "assign %d allergens" % count for k in range(count): a = random.choice(_allergens).allergen if a in ItemAllergen.objects.filter(item=item, allergen=a): continue traces = bool(random.randint(0, 1)) ItemAllergen.objects.get_or_create( item=item, allergen=a, traces=traces)[0].save() item.save() # i18n stuff name = gen_unique_name(items, food_names) for lang in _languages: i18n = ItemI18n() i18n.item = item i18n.language = lang i18n.name = name if lang.abbr != "en": i18n.name += "(%s)" % lang.abbr i18n.description = "Very delicious %s. It is made with love and all the care it is needed to make a great %s." % ( name, name) i18n.save() print self.stdout.write('Successfully added %d restaurants' % restaurant_count)
from main.models import User, Item base_name = "你好世界" for i in range(10): tt = User(u_name=base_name + str(i), u_pwd="123445") tt.save() Item(i_title=base_name + str(i), i_content=base_name + str(i), i_p_id=tt).save()