예제 #1
0
def search(request):
    query_string = ''
    found_entries = None
    item_obj = Item()
    categories = Category.objects.all()
    is_search = 1
    first_item = []
    if ('category' in request.GET) and request.GET['category'].strip():
        category = request.GET['category'].strip().lower()
        category_inst = Category.objects.filter(name__icontains=category)
        if category_inst:
            if 'q' in request.GET and request.GET['q']:
                query_string = request.GET['q']
                entry_query = item_obj.get_query(query_string,
                    ['name', 'description', 'price', 'location', 'category__name'])
                found_entries = Item.objects.filter(entry_query, category=category_inst[0]).order_by('name')
            else:
                found_entries = Item.objects.filter(category=category_inst[0]).order_by('name')
        else:
            found_entries = []

    elif ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q'].strip()
        entry_query = item_obj.get_query(query_string, ['name', 'description', 'price', 'location', 'category__name'])

        found_entries = Item.objects.filter(entry_query).order_by('name')
    else:
        found_entries = Item.objects.filter()
    if found_entries:
        first_item = found_entries[0]
    return render_to_response('items/index.html',
            {'query_string': query_string, 'categories': categories, 'items': found_entries,'is_search':is_search,'first_item':first_item},
        context_instance=RequestContext(request))
예제 #2
0
def createInventory1(request, item_id):
    pharmacy = request.session['name']
    pharmacy_info = Pharmacy.objects.get(pharmacy_id=pharmacy)
    form1 = SellsForm()
    #form1.item_id=item_id
    s = Item.objects.get(item_id=item_id)
    if request.method == 'POST':
        form1 = SellsForm(request.POST, request.FILES)
        if form1.is_valid():
            info = form1.save(commit=False)
            print(item_id)
            temp = Item()
            temp.item_id = item_id
            info.item_id = temp
            print(info.item_id)
            temp1 = Pharmacy()
            temp1.pharmacy_id = request.session['name']
            print(temp1.pharmacy_id)
            info.pharmacy_id = temp1
            info.save()

            return HttpResponseRedirect('/pharmacy_name/inventory/show/')

        else:
            return render(request, 'inventory/create_inventory.html', {
                'form1': form1,
                'item': s,
                'pharmacy': pharmacy_info
            })
    else:
        return render(request, 'inventory/create_inventory.html', {
            'form1': form1,
            'item': s,
            'pharmacy': pharmacy_info
        })
예제 #3
0
def parseTweets(username, hashtag):
    try:
        from twython import Twython
        twitter = Twython()
        if (username is not None):
            tweets = twitter.getUserTimeline(screen_name=username)
            for t in tweets:
                it = Item(title=texto2Unicode(t["text"]),
                          desc=texto2Unicode(t["text"]),
                          author=texto2Unicode(t["user"]["screen_name"]),
                          category=texto2Unicode("twitter"),
                          link="",
                          img=texto2Unicode(
                              t["user"]["profile_image_url_https"]),
                          pub_date=texto2Unicode(t["created_at"]))
                checkAndSaveEntry(it)
        if (hashtag is not None):
            twhash = twitter.search(q=hashtag)
            for t in twhash["results"]:
                it = Item(title=texto2Unicode(t["text"]),
                          desc=texto2Unicode(t["text"]),
                          author=texto2Unicode(t["from_user"]),
                          category=texto2Unicode("twitter"),
                          link="",
                          img=texto2Unicode(t["profile_image_url_https"]),
                          pub_date=texto2Unicode(t["created_at"]))
                checkAndSaveEntry(it)
    except Exception, e:
        print("ExceptionTW: %s" % e)
        return 0
예제 #4
0
def parsePage(ilt,html, itemtype):
    global index_global
    try:

        plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
        tlt=re.findall(r'\"raw_title\"\:\".*?\"', html)
        purl=re.findall(r'\"pic_url\"\:\".*?\"', html)
        detail_url = re.findall(r'\"detail_url\"\:\".*?\"', html)
        sales = re.findall(r'\"view_sales\"\:\".*?\"', html)

        # item = Item(item_id=iid,
        #             title=tlt,
        #             price=float(plt),
        #             pic_url=purl,
        #             pic_file=f'data/{itemtype}/{itemtype}_{index_global}.jpg',
        #             sales=sales,
        #             type=itemtype)


        try:
            os.makedirs(f'../data/{itemtype}')
        except:
            pass

        for i in range(len(plt)):
            price=eval(plt[i].split(':')[1])
            title=eval(tlt[i].split(':')[1])
            pic_url = 'http:' + eval(purl[i].split(':')[1])
            sale = eval(sales[i].split(':')[1])
            sale = re.findall(r'\d+', sale)
            sale = int(''.join(sale))
            # ilt.append([price, title, pic_url, itemtype])
            try:
                iid = str(file_dict[itemtype]) + '_' + str(index_global)
                file = f'data/{itemtype}/{itemtype}_{index_global}.jpg'
                # sale = np.random.choice(10000, 1)[0]


                item = Item(item_id=iid,
	                        title=title,
	                        price=float(price),
	                        pic_url=pic_url,
	                        pic_file=file,
	                        sales=sale,
	                        type=itemtype)
                item.save()
                print([iid, price, title, pic_url, itemtype, sale, file])

                urllib.request.urlretrieve(pic_url,f'../data/{itemtype}/{itemtype}_{index_global}.jpg')
                img = Image.open(f'../data/{itemtype}/{itemtype}_{index_global}.jpg')
                out = img.resize((200, 200))
                out.save(f'../static/data/{itemtype}/{itemtype}_{index_global}.jpg', 'jpeg')
                ilt.append([index_global, price, title, pic_url, itemtype, sales])
                # print([index_global, price, title, pic_url, itemtype, sales])
                index_global += 1
                time.sleep(np.random.choice(5, 1))
            except:
                print(f'{title}数据保存失败')
    except:
        return ""
예제 #5
0
def add_item_service(request):
    """Our bookmarklet posts to here"""

    bookmarklet_key_id = request.POST['bookmarklet_key']
    try:
        bookmarklet_key = Contributor.objects.get(key=bookmarklet_key_id)
    except Contributor.DoesNotExist:
        return render_to_response('bookmarklet_denied.html')
    if not bookmarklet_key.is_active:
        return render_to_response('bookmarklet_denied.html')

    description = request.POST["description"]
    link = request.POST["link"]
    description = request.POST["description"]
    contributor = bookmarklet_key.display_name

    item = Item(
        contributor=bookmarklet_key,
        link=link,
        description=description,
    )

    item.save()

    return HttpResponse('success', status=200)
예제 #6
0
def add_items_from_file(file_path):
    xml_file = etree.ElementTree(file=file_path)
    xml_tag_list = xml_file.getroot()
    for xml_tag_item in xml_tag_list:
        for key in xml_tag_item.attrib:
            if key == 'id':
                atr_id = xml_tag_item.attrib[key]
            elif key == 'name':
                atr_name = xml_tag_item.attrib[key]
            elif key == 'type':
                atr_type = xml_tag_item.attrib[key]
            else:
                print('Item atribut : %s in tag : %s not parsed.' %
                      (key, xml_tag_item.tag))

        new_item = Item(id=atr_id, name=atr_name, type=atr_type)

        new_item.save()

        for i in xml_tag_item:
            if i.tag == 'set':
                new_param = ItemParam(item=new_item,
                                      name=i.attrib['name'],
                                      value=i.attrib['val'])

                new_param.save()

            elif i.tag == 'for':
                pass
            elif i.tag == 'cond':
                pass
            else:
                print(
                    'Item: %s with id: %s have non parsed tag: %s' %
                    (xml_tag_item.get('name'), xml_tag_item.get('id'), i.tag))
예제 #7
0
    def save(self, commit=True):
        for form in self.forms:
            print(form.cleaned_data)
            name = form.cleaned_data.get('name')
            description = form.cleaned_data.get('description', '')

            item = Item(name=name, description=description)
            item.save()
        return self.forms
예제 #8
0
 def create_item(self, seed, seller, price=12.00):
     """
     Creates an Item instance and returns it.
     """
     item = Item(title='Item{}'.format(seed),
                 notes='Some notes.',
                 seller=seller,
                 price=price)
     item.save()
     return item
예제 #9
0
def index_or_create(request):
    user = users.get_current_user()
    if not user:
        return HttpResponseForbidden(
            'You are not authorized to perform this action')

    if request.method == 'GET':
        return HttpResponse(flatten_array_to_json(Item.all()))
    if request.method == 'POST':
        item = Item(None, None)
        item_dict = simplejson.loads(request.raw_post_data)
        for key in item_dict.keys():
            setattr(item, key.encode('ascii'), item_dict[key])
        item.put()
        return HttpResponse(flatten_obj_to_json(item))
    if request.method == 'DELETE':
        request.method = 'POST'
        request.method = 'PUT'
        request.DELETE = request.POST
        del request._post
        items = Item.all()
        item_count = items.count()
        for item in Item.all():
            item.delete()
        return HttpResponse('deleted ' + str(item_count) + ' records')
예제 #10
0
    def delete(cls, collection_id):
        collection = cls.objects.get_or_404(id=collection_id)
        if collection.owner != g.user:
            raise Forbidden('Only collection owner can delete collection') if collection.public else NotFound()

        Comment.delete_from_collection(collection)
        Item.delete_from_collection(collection)

        logger.info('Deleting {} ...'.format(collection))
        super(cls, collection).delete()
        logger.info('Deleting {} done'.format(collection))
예제 #11
0
    def handle(self, *args, **kwargs):
        dummy_data = {
            'item_names': [
                'Do Androids Dream of Electric Sheep?',
                'The Hitchhiker\'s Guide to the Galaxy',
                'Something Wicked This Way Comes',
                'Pride and Prejudice and Zombies',
                'The Curious Incident of the Dog in the Night-Time',
                'I Was Told There\'d Be Cake', 'To Kill a Mockingbird',
                'The Unbearable Lightness of Being',
                'Eats, Shoots & Leaves: The Zero Tolerance Approach to Punctuation',
                'The Hollow Chocolate Bunnies of the Apocalypse',
                'A Clockwork Orange', 'Are You There, Vodka? It\'s Me, Chelsea'
            ],
            'item_descriptions': [
                'Brand new, never opened or used.',
                'Light usage, good condition',
                'Spilled some water on it, fair condition, but good enough',
                'Mint condition - collectors item'
            ],
            'item_ask_price': ['.1', '.23', '.51', '.233', '.47', '.09'],
            'new_items': []
        }

        for index, value in enumerate(range(kwargs['items'])):
            random_item = choice(dummy_data['item_names'])
            random_desc = choice(dummy_data['item_descriptions'])
            random_price = choice(dummy_data['item_ask_price'])
            random_user = choice(User.objects.all())

            item = Item(
                owner=random_user,
                name=random_item,
                description=random_desc,
                ask_price_xmr=random_price,
            )
            item.save()

            dummy_data['new_items'].append(item)
            self.stdout.write(
                self.style.SUCCESS(
                    f'Item "{item.name} ({item.id})" created successfully!'))

        for i in dummy_data['new_items']:
            all_users = User.objects.all().exclude(username=i.owner.username)
            for u in all_users:
                bid = ItemBid(item=i, bidder=u, bid_price_xmr=i.ask_price_xmr)
                bid.save()
                self.stdout.write(
                    self.style.SUCCESS(
                        f'Bid #{bid.id} for user "{bid.bidder}" created successfully!'
                    ))
예제 #12
0
def get_or_create_item(item_name):
    """
    Get or Create an Item instance

    :param item_name: string
    :return item: Item instance
    """
    try:
        item = Item.objects.get(name=item_name)
    except Item.DoesNotExist:
        item = Item()
        item.name = item_name
        item.save()
    return item
예제 #13
0
    def save(self, *args, **kwargs):
        f = io.TextIOWrapper(self.file.file.file, encoding='UTF-8')
        transactions = csv.reader(f)
        itemDict = refreshItemPrices()

        for line in transactions:
            input_data = Transaction()
            input_data.error_message = ""
            #input_data.time = datetime.strptime(line[4], "%Y/%m/%d %H:%M:%S")
            input_data.time = datetime.fromtimestamp(int(
                line[4])).strftime("%Y-%m-%d %H:%M:%S")
            char = Character.objects.filter(name=line[8].strip())
            if char.exists():
                input_data.character = char.first()
            else:
                character = Character(name=line[8].strip())
                character.save()
                input_data.character = character
                input_data.error_message += "No existing character. "
            input_data.type = line[7].strip()
            item = Item.objects.filter(itemId=line[10])
            if item.exists():
                input_data.item = item.first()
            else:
                new_item = Item(itemId=line[10], itemName=line[9].strip())
                itemId = int(line[10])
                if itemId in itemDict['items'].keys():
                    new_item.points = itemDict['items'][itemId].get(
                        'MarketValue')
                else:
                    input_data.error_message = "Item ID " + line[
                        10] + " not seen before, and not present in TSM response"
                new_item.save()
                input_data.item = new_item
            if input_data.item.itemId == 0:
                #Its gold. Divide by 10000 to switch from gold val to copper val
                #As per terra, round up.
                if int(line[11]) < 10000:
                    input_data.quantity = 1
                elif int(line[11]) % 10000 != 0:
                    input_data.quantity = (int(line[11]) / 10000) + 1
                else:
                    input_data.quantity = int(line[11]) / 10000
            else:
                input_data.quantity = int(line[11])
            input_data.save()
            input_data.process()

        super(TransactionFile, self).save(args, kwargs)
예제 #14
0
파일: views.py 프로젝트: zouzou05/dzlibs
def user_items(param, page=1):
    user = User.objects.get_or_404(user_id=param)
    items = Pagination(Item.objects(submitter=user), page, 12)

    return render_template('frontend/user_items.html',
                           items=items,
                           user=user)
예제 #15
0
def jot_index(request):
    item = Item.get_or_insert('jot')
    item.title = 'jot'
    if item.body:
        return HttpResponse(item.body)
    else:
        return HttpResponse('no jot content')
예제 #16
0
def borrow(request, info_id):
    if request.method == 'POST':
        item_id = request.POST['item_id']
        info_obj = Item.get_info_obj_by_id(info_id)
        test_item_obj = Item.objects.get(id=item_id)
        if not test_item_obj.item_abstract.track_1by1:
            amount = int(request.POST['amount'])
        else:
            amount = 1

        if amount > test_item_obj.quantity:
            messages.error(request, 'ไม่อนุญาตให้ยืมมากกว่าจำนวนอุปกรณ์ที่มี')
        elif amount < 1:
            messages.error(request, 'ไม่อนุญาตให้ระบุจำนวนน้อยกว่า 1')
        elif test_item_obj.status != 'available':
            messages.error(
                request,
                f"อุปกรณ์ชื่อ: {test_item_obj.item_abstract.title} รหัส: {test_item_obj.item_abstract.serial} หมายเลขติดตาม: {test_item_obj.tracking_number} ไม่ได้อยู่ในสถานะว่างแล้ว"
            )

        else:
            new_order = Order.objects.create(user=request.user)
            Order_Item.objects.create(item=test_item_obj,
                                      order=new_order,
                                      amount=amount)

            new_order.status = 'created'
            new_order.save()
            messages.success(request, 'สร้างรายการเบิกใช้อุปกรณ์เรียบร้อยแล้ว')

    return redirect('catalog:detail', info_id=info_id)
예제 #17
0
def cloud(model_or_obj, num=5):
    """ Get a tag cloud. If num==0 it will return all the tags."""
    tag_uses = get_tag_uses()
    if not (tag_uses):
        return []
    if num > 0:
        tag_uses = tag_uses[:num]

    max_uses = max(tag_uses[0][0], 5)
    min_uses = tag_uses[-1][0]

    # Use a logarithmic scaling between 1.0 to 170% of baseline font size
    # We could consider a logarithmic scale
    min_font, max_font = 3, 6
    slope = (max_font - min_font) / (max_uses - min_uses + 0.0)
    intercept = min_font - slope * min_uses

    out = []
    Item = namedtuple('Item', 'slug tag score')
    for score, pk in tag_uses:
        tag = Tag.objects.get(id=pk)
        out.append(
            Item(tag.slug, tag,
                 int(log(slope * score + intercept) * 100) - 9))

    out.sort()
    return out
예제 #18
0
파일: views.py 프로젝트: aarongut/fincom2
def edit(request, item_id):
    I = Item.objects.get(pk=item_id)

    if (not isAuthorised(request, I)
        and request.user != I.created_by):
        return authError()

    if request.method == 'POST':
        if (request.POST.get('desc', None)):
            I.desc = request.POST['desc']
        if (request.POST.get('event', None)):
            I.event = request.POST['event']
        if (request.POST.get('committee', None)):
            I.committee = Committee.objects.get(name=request.POST['committee'])
        if (request.POST.get('cost', None)):
            I.cost = request.POST['cost']
        if (request.POST.get('date', None)):
            I.date_purchased = Item.parseDate(request.POST['date']),
        if (request.POST.get('details', None)):
            I.details = request.POST['details']

        I.save()

        return HttpResponseRedirect('/items/' + str(item_id))
    else:
        template = loader.get_template('items/edit.html')
        
        context = {
            'I': I,
            'committees': Committee.objects.order_by('name'),
        }
        return HttpResponse(template.render(context, request))
예제 #19
0
def search(request):
    if request.method == 'GET' and request.GET:
        query = request.GET.get('query', None)
        if query:
            i = Item()
            ids = i.get_similar_item_ids(name=query)
            items = Item.objects.filter(id__in=ids, is_active=True).extra(
                select={'manual': 'FIELD(id, %s)' % ','.join(map(str, ids))},
                order_by=['manual'])
            results = []
            for item in items:
                results.append({'id': item.id, 'name': item.name})
            return HttpResponse(json.dumps(results))
        else:
            return HttpResponse(json.dumps(""))
    else:
        raise Http404
예제 #20
0
파일: views.py 프로젝트: aarongut/fincom2
def new_form(request):
    if request.method == 'POST':
        if request.FILES['image'].size > 10 * (1 << 20):
            template = loader.get_template('items/new.html')
            context = {
                'committees': Committee.objects.order_by('name'),
                'error': 'Your image file is too large. Maximum size is 20MB',
            }
            return HttpResponse(template.render(context, request))
        item = Item(
            desc = request.POST['desc'],
            event = request.POST['event'],
            committee = Committee.objects.get(name=request.POST['committee']),
            cost = request.POST['cost'],
            date_purchased = Item.parseDate(request.POST['date']),
            details = request.POST['details'],
            date_filed = timezone.now(),
            created_by = request.user,
            status = Item.NEW,
            image = request.FILES['image'],
        )

        item.save()

        item.mail_com_chair()

        return HttpResponseRedirect('/items')

    else:
        template = loader.get_template('items/new.html')
        context = {
            'committees': Committee.objects.order_by('name'),
        }

        return HttpResponse(template.render(context, request))
예제 #21
0
 def save_model(self, request, obj, form, change):
     """
     Guarda un nuevo item de la página de inicio con el orden por defecto
     al final de la lista
     """
     if not change:
         if form.cleaned_data["home_photo"]:
             obj.order = Item.get_default_order()
     obj.save()
예제 #22
0
파일: views.py 프로젝트: serkanh/Yupeat
def admin_items(request):
    item_array = []
    
    if request.method == 'POST':
        new_items = request.POST.get('new_items')
        item_array = new_items.split('\r\n')
        for i in item_array:
            #logging.debug(i)
            try:
                iarray = i.split(',')
                item = Item(name=iarray[0].strip(),quantity=iarray[1].strip(),price=Decimal(iarray[2].strip()))
                item.save()
            except IndexError:
                pass
    template = 'items/admin/admin_item.html'
    data = {}
    
    return render_to_response(template, data,context_instance=RequestContext(request))
예제 #23
0
    def create(self, request):

        loggedUser = self.session_service.getLoggedUser(request)
        if loggedUser is not None:
            item = Item()
            self.fromRequest(request, item, self.fields)
            item.user_id = loggedUser.id

            try:
                item.validate()
            except InvalidFieldsException as invalidFields:
                return HttpResponseForbidden(invalidFields)

            self.item_service.saveItem(item)

            return HttpResponse(item.as_json())
        else:
            return HttpResponseForbidden('<h1>not a user</h1>')
예제 #24
0
파일: views.py 프로젝트: acutexyz/cx
def search(request):
	if request.method == 'GET' and request.GET:
		query = request.GET.get('query', None)
		if query:
			i = Item()
			ids = i.get_similar_item_ids(name=query)
			items = Item.objects.filter(id__in=ids, is_active=True).extra(
				select={'manual': 'FIELD(id, %s)' % ','.join(map(str, ids))},
				order_by=['manual']
				)
			results = []
			for item in items:
				results.append({'id': item.id, 'name': item.name})
			return HttpResponse(json.dumps(results))
		else:
			return HttpResponse(json.dumps(""))
	else:
		raise Http404
예제 #25
0
 def save(self):
     items_csv = csv.reader(self.cleaned_data["file"])
     Item.objects.all().delete()
     for item_csv in items_csv:
         item = Item()
         item.item_id = item_csv[0]
         item.name = item_csv[1]
         item.category = item_csv[2]
         item.price_cash = item_csv[3]
         item.price_credit = item_csv[4]
         item.save()
예제 #26
0
def populate_items():
    items = populate_instance(Item, API_ITEMS_URL, 'items')

    for item in items:
        try:
            Item.objects.get(pk=item['id'])
            continue
        except Item.DoesNotExist:
            new_instance = Item()
            new_instance.id = item['id']
            new_instance.name = item['name']
            new_instance.localized_name = item['localized_name']
            new_instance.is_recipe = item['recipe']
            new_instance.cost = item['cost']
            new_instance.save()
예제 #27
0
파일: views.py 프로젝트: zouzou05/dzlibs
def category(param, page=1):
    categories = Category.objects.all()
    category = categories.get_or_404(name_en__iexact=param)

    items = Pagination(Item.objects(category=category), page, 12)

    return render_template('frontend/category_listing.html',
                           items=items,
                           current_category=category,
                           categories=categories)
예제 #28
0
 def test_update_inventory(self):
     nickname = "Bob"
     cnt = 42
     new_cnt = 47
     name = "Banapple"
     description = "Is it a Banana? An Apple? No one cares!"
     # Create player and existing item
     Player(nickname=nickname).save()
     item = Item(name=name, description=description)
     item.save()
     test_player = Player.objects.get(nickname=nickname)
     test_item = Item.objects.get(name=name)
     inventory = Inventory(item_owner=test_player, item_type=test_item, count=cnt)
     inventory.save()
     # Update inventory.
     inv = test_player.inventory[0]
     inv.count = new_cnt
     inv.save()
     inv = test_player.inventory[0]
     # Check if the count of the item is correct.
     self.assertTrue(inv.count == new_cnt)
예제 #29
0
 def test_add_inventory(self):
     """
     Tests adding two items to the player's inventory.
     """
     nickname = "Bob"
     cnt_a = 42
     cnt_b = 47
     item_a = Item(name="Banapple", description="Is it a Banana? An Apple? No one cares!")
     item_b = Item(name="Apprange", description="Turns out you can compare Apples and Oranges.")
     # Create player and existing items
     Player(nickname=nickname).save()
     item_a.save()
     item_b.save()
     # Save the items.
     test_player = Player.objects.get(nickname=nickname)
     test_item_a = Item.objects.get(name=item_a.name)
     test_item_b = Item.objects.get(name=item_b.name)
     inventory_a = Inventory(item_owner=test_player, item_type=test_item_a, count=cnt_a)
     inventory_a.save()
     inventory_b = Inventory(item_owner=test_player, item_type=test_item_b, count=cnt_b)
     inventory_b.save()
     # Get the items.
     inv = test_player.inventory
     # Check the results.
     self.assertEqual(inv[0], inventory_a)
     self.assertEqual(inv[1], inventory_b)
예제 #30
0
파일: views.py 프로젝트: Brioal/dnw
def item_create(request):
    if request.method == 'PUT':
        data = JSONParser().parse(request)
        # create item
        item = Item()
        item_data = {}
        item_data['item_name'] = data['item_name']
        item_data['item_price'] = data['item_price']
        item_data['frequency'] = data['frequency']
        item_data['classify'] = data['classify']
        serializer = ItemSerializer(item, data=item_data)
        if serializer.is_valid():
            serializer.save()
            item_id = item.id
            # create step
            step_list = data['steps']
            for step_val in step_list:
                step = Step()
                step_data = step_val
                step_data['belong_item'] = item_id
                serializer = StepSerializer(step, step_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            product_list = data['product']
            for product_val in product_list:
                item_product = Item_Product()
                product_data = product_val
                product_data['item'] = item_id
                product_data['product'] = Product.objects.get(
                    name=product_data['name']).id
                serializer = ItemProductSerializer(item_product, product_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            instrument_list = data['instrument']
            for instrument_val in instrument_list:
                item_instrument = Item_Instrument()
                instrument_data = instrument_val
                instrument_data['item'] = item_id
                instrument_data['instrument'] = Instrument.objects.get(
                    name=instrument_data['name']).id
                serializer = ItemInstrumentSerializer(item_instrument,
                                                      instrument_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            return JsonResponse({"text": "success"})
        return JsonResponse(serializer.errors, status=400)
예제 #31
0
    def receive_(self):

        if not Item.is_registered(self.item.item_abstract, self.dst_branch):
            new_item = Item.register(self.item.item_abstract, self.dst_branch)

        if self.item.item_abstract.track_1by1:
            if self.ref_order:
                self.item.status = 'reserved'
            else:
                self.item.status = 'available'
            self.item.currently_at = self.dst_branch
            self.item.save()
        else:
            shipping_obj = Item.objects.filter(item_abstract=self.item.item_abstract,
                                               currently_at=self.item.currently_at,
                                               status='shipping').first()
            shipping_obj.quantity -= self.amount
            shipping_obj.save()



            if self.ref_order:
                reserved_item = Item.objects.filter(
                    item_abstract=self.item.item_abstract,
                    currently_at=self.dst_branch,
                    status='reserved'
                ).first()
                reserved_item.quantity += self.amount
                reserved_item.save()
            else:
                dst_item = Item.objects.filter(
                    Q(item_abstract__serial=self.item.item_abstract.serial, currently_at=self.dst_branch,
                      status='available', tracking_number=self.item.tracking_number) |
                    Q(item_abstract__serial=self.item.item_abstract.serial, currently_at=self.dst_branch,
                      status='unavailable', tracking_number=self.item.tracking_number)
                ).distinct().first()

                dst_item.quantity += self.amount
                dst_item.save()
예제 #32
0
def category_search(request, pk, format=None):
    """Retrieve, update or delete a code category."""
    try:
        category = Category.objects.get(name=pk)
    except Category.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        items = Item.get_active(category=category)
        print("items")
        serializer = ItemSerializer(items, many=True)
        # serializer = ItemsCategorySerializer(items, many=True)
        return Response(serializer.data)
예제 #33
0
def item_list(request, format=None):
    """List all code items, or create a new item."""
    if request.method == 'GET':
        items = Item.get_active()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ItemSerializer(data=request.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)
예제 #34
0
def add(request):
#    user, item = get_user_profile(request.user.id)
    form = ItemForm()
    if request.method == "POST":
        form = ItemForm(request.POST, request.FILES)
        if form.is_valid():
            form.cleaned_data['seller'] = request.user
            data = form.cleaned_data
            image1 = data['image1']
            image2 = data['image2']
            image3 = data['image3']
            if not (is_image(image1) and is_image(image2) and is_image(image3)):
                request.flash['message'] = "Sorry please upload a picture in an acceptable format"
                return HttpResponseRedirect(reverse('add_item'))
            item = Item(
                name=data['name'],
                description=data['description'],
                condition=data['condition']or 0,
                price=round(float(data['price']),2),
                longitude=data['longitude'] or 0,
                latitude=data['latitude'] or 0,
                seller=request.user,
                category=data['category'],
                location=data['location'],
                is_published = True,
                is_service = data['is_service']
            )

            item_obj = item.save()
            upload_item_images(image1, image2, image3, item)
            request.flash['message'] = "Item saved successfully"

            #            else:
            #                request.flash['message'] = "Sorry can't save item"
            return HttpResponseRedirect(reverse('my_listing'))
        else:
            request.flash['message'] = "Invalid data"

    return render_to_response("items/add.html", {'form': form}, context_instance=RequestContext(request))
예제 #35
0
def add_item_service(request):
    """Our bookmarklet posts to here"""
    
    bookmarklet_key_id = request.POST['bookmarklet_key']
    try:
        bookmarklet_key = Contributor.objects.get(key=bookmarklet_key_id)
    except Contributor.DoesNotExist:
        return render_to_response('bookmarklet_denied.html')
    if not bookmarklet_key.is_active:
        return render_to_response('bookmarklet_denied.html')
        
    description = request.POST["description"]
    link = request.POST["link"]
    description = request.POST["description"]
    contributor = bookmarklet_key.display_name
    
    item = Item(contributor=bookmarklet_key,
                link=link,
                description=description,)
    
    item.save()
    
    return HttpResponse('success', status=200)
예제 #36
0
파일: views.py 프로젝트: acutexyz/cx
def add(request):
	if request.method == 'POST':
		form = ItemAddForm(request.POST)
		if form.is_valid():
			# i = Item(**form.cleaned_data)
			i = Item(
				name=form.cleaned_data['name'],
				date_created=timezone.now(),
				created_by=CustomUser(id=request.user.id),
				category=form.cleaned_data['category']
			)
			duplicates_list = i.get_similar_item_ids()
			if len(duplicates_list) > 0:
				possible_duplicates = ItemPossibleDuplicates(str_list=str(duplicates_list), number=len(duplicates_list))
				possible_duplicates.save()
				i.possible_duplicates = possible_duplicates
			i.save()
			return HttpResponseRedirect(reverse('items.views.view', kwargs={'item_id': i.id}))
	else:
		form = ItemAddForm() # An unbound form

	return render(request, 'items/add.html', {
		'form': form,
	})
예제 #37
0
    def create_items_from_feed(self, items, feed):
        '''
        This method receives a list of items and a feed,
        and try to create items based on a md5 hash.
        '''
        new_items = []
        for item in items:
            item_object = self._create_item_payload(item, feed)
            md5 = self._create_md5(item_object)

            if not Item.objects.filter(md5=md5).exists():
                item_object.update(md5=md5)
                new_items.append(Item(**item_object))

        return Item.objects.bulk_create(new_items)
예제 #38
0
def borrow_multiple(request):
    if request.method == 'POST':

        info_id = request.POST['info_id']

        info_obj = Item.get_info_obj_by_id(info_id)

        amount = int(request.POST['amount'])
        available_q = info_obj.get_q_this_branch().get('available')

        if amount > available_q:
            messages.error(request, 'ไม่อนุญาตให้ยืมมากกว่าจำนวนอุปกรณ์ที่มี')
        elif amount < 1:
            messages.error(request, 'ไม่อนุญาตให้ระบุจำนวนน้อยกว่า 1')

        else:
            new_order = Order.objects.create(user=request.user)

            if info_obj.item_abstract.track_1by1:
                selected_ids = Item.objects.filter(
                    item_abstract=info_obj.item_abstract,
                    currently_at=info_obj.currently_at,
                    status='available').order_by(
                        '-tracking_number')[:amount].values_list("id",
                                                                 flat=True)
                selected_items_obj = Item.objects.filter(
                    id__in=list(selected_ids)).all()

                to_create_order_items = []
                for item in selected_items_obj:
                    new_order_item = Order_Item(item=item, order=new_order)
                    to_create_order_items.append(new_order_item)
                Order_Item.objects.bulk_create(to_create_order_items)

            else:
                track1_item = Item.objects.get(
                    item_abstract=info_obj.item_abstract,
                    currently_at=info_obj.currently_at,
                    status='available')
                Order_Item.objects.create(item=track1_item,
                                          order=new_order,
                                          amount=amount)

            new_order.status = 'created'
            new_order.save()
            messages.success(request, 'สร้างรายการเบิกใช้อุปกรณ์เรียบร้อยแล้ว')

        return redirect('catalog:list')
예제 #39
0
def add_item_image(request, item_id):
    if request.method == 'POST':
        form = ItemImageUploadForm(request.POST, request.FILES)
        if form.is_valid() and form.clean_image_size():
            item_image = ItemImage(item=Item(id=item_id),
                                   image=request.FILES['image'],
                                   uploaded_by=request.user,
                                   date_uploaded=timezone.now())
            item_image.save()
            return HttpResponseRedirect('/items/' + item_id + '/gallery/')
    else:
        form = ItemImageUploadForm()

    return render(request, 'items/item_images/add.html', {
        'form': form,
        'item_id': item_id,
    })
예제 #40
0
def parsePOPMail(server, username, passw, from_filter):
    try:
        import poplib
        from email.parser import Parser

        pop_conn = poplib.POP3_SSL(server)
        pop_conn.user(username)
        pop_conn.pass_(passw)

        messages = [
            pop_conn.retr(i) for i in range(1,
                                            len(pop_conn.list()[1]) + 1)
        ]
        messages = ["\n".join(mssg[1]) for mssg in messages]
        messages = [Parser().parsestr(mssg) for mssg in messages]

        for message in messages:

            if from_filter in message['from']:
                body = ""
                flag = 1
                for part in message.get_payload():
                    if flag:
                        #print part.as_string()
                        part.__delitem__('Content-Type')
                        #print part['Content-Type']
                        body = body + part.as_string()
                        flag = 0
                #print body

                it = Item(title=message['subject'],
                          desc=body[:2000],
                          author=message['from'],
                          category='mail',
                          link="",
                          img="",
                          pub_date=message['date'])
                checkAndSaveEntry(it)

        pop_conn.quit()
        return 1
    except Exception, e:
        print("Exception: %s" % e)
        return 0
예제 #41
0
    def handle(self, *args, **kwargs):
        """Loop thru Enum object ItemType and create sample data

        Eg. For total = 10 will create 10 sample Item data into db
        """
        current_time = timezone.now()
        for x in ItemType:
            prefix = x.name[:1]
            for i in range(0, kwargs['total']):
                item = Item()
                item.sku = prefix + str(randint(1000000, 9999999))
                item.name = x.name[:3] + str(randint(1, 99909990))
                item.item_type = x.value
                item.active_timestamp = current_time
                item.expiry_timestamp = current_time + timedelta(days=5)

                item.save()

                price = Price()
                price.item = item
                price.price = uniform(10.00, 200.00)
                price.effective_timestamp = current_time - timedelta(days=10)

                price.save()
예제 #42
0
파일: views.py 프로젝트: vikev/SLIP
def add( request ):
  name = request.GET.get( 'name', '' )
  mass = request.GET.get( 'mass', '' )

  if name and mass:
    item = Item()
    item.name = name
    item.mass = mass
    item.item_id = len( Item.objects.all() )
    item.save()
    return HttpResponseRedirect( '/items/' )

  item = Item.objects.all()
  return render( request, 'items/add.html' )
예제 #43
0
파일: views.py 프로젝트: pfeilbr/qik
def index_or_create(request):
    if not is_authenticated(request):
        return HttpResponseForbidden('You are not authorized to perform this action')
    
    if request.method == 'GET':
        return HttpResponse( flatten_array_to_json( Item.all() ) )
    if request.method == 'POST':
        item = Item(None, None)
        item_dict = simplejson.loads( request.raw_post_data )
        for key in item_dict.keys():
            setattr(item, key.encode('ascii'), item_dict[key])
        item.put()
        return HttpResponse( flatten_obj_to_json(item) )
    if request.method == 'DELETE':
        request.method = 'POST'
        request.method = 'PUT'
        request.DELETE = request.POST
        del request._post
        items = Item.all()
        item_count = items.count() 
        for item in Item.all():
            item.delete()
        return HttpResponse('deleted ' + str(item_count) + ' records')
예제 #44
0
def jot(request):
    item = Item.get_or_insert('jot')
    item.title = 'jot'
    
    data = {}
    if request.raw_post_data:
        data = simplejson.loads( request.raw_post_data )
    
    if request.method == 'GET':
        if item.body:
            return json_response( flatten_obj_to_json(item) )   
        else:
            return json_response( '{}' )
    
    if request.method == 'POST':
        item.body = data['body']
        item.put()
        return json_response( flatten_obj_to_json(item) )          
    
    if request.method == 'PUT':
        request.method = 'POST'
        request.method = 'PUT'
        request.PUT = request.POST
        del request._post
        if item.body:
            item.body = data['body'] + '\n' + item.body
        else:
            item.body = data['body']
        item.put()
        return json_response( flatten_obj_to_json(item) ) 
        
    if request.method == 'DELETE':
        request.method = 'POST'
        request.method = 'PUT'
        request.DELETE = request.POST
        del request._post
        if item.is_saved():
            item.delete()
        return json_response( '{}' )
예제 #45
0
def jot(request):
    item = Item.get_or_insert('jot')
    item.title = 'jot'

    data = {}
    if request.raw_post_data:
        data = simplejson.loads(request.raw_post_data)

    if request.method == 'GET':
        if item.body:
            return json_response(flatten_obj_to_json(item))
        else:
            return json_response('{}')

    if request.method == 'POST':
        item.body = data['body']
        item.put()
        return json_response(flatten_obj_to_json(item))

    if request.method == 'PUT':
        request.method = 'POST'
        request.method = 'PUT'
        request.PUT = request.POST
        del request._post
        if item.body:
            item.body = data['body'] + '\n' + item.body
        else:
            item.body = data['body']
        item.put()
        return json_response(flatten_obj_to_json(item))

    if request.method == 'DELETE':
        request.method = 'POST'
        request.method = 'PUT'
        request.DELETE = request.POST
        del request._post
        if item.is_saved():
            item.delete()
        return json_response('{}')
 def add_item(request, item_id, amount, proposal):
     """
     1. if item_list containts item, update amount
     2. else, add item id and amount plus name and image to item_list
     """
     item_list = request.session['item_list'] # check if list exists
     for count, i in enumerate(item_list):
         if i['id'] == item_id and i['proposal'] == proposal:
             new_amount = amount + i['amount']
             item_list[count]['amount'] = new_amount
             break
     else:
         id, name, image_url = Item.get_item(item_id)
         if id:
             new_item = {
                 'id': id,
                 'name': name,
                 'image_url': image_url,
                 'amount': amount,
                 'proposal': proposal,
             }
             item_list.append(new_item)
     request.session['item_list'] = item_list
예제 #47
0
def jot_index(request):
    item = Item.get_or_insert('jot')
    item.title = 'jot'
    if item.body:
        return HttpResponse(item.body)
    else:
        return HttpResponse('no jot content')


        #i = simplejson.loads( request.raw_post_data )
        
        # convert unicode string keys to ascii string keys.
        # this is neccessary in order to use the ** operator in the following Item constructor
        #i2 = {}
        #for k in i.keys():
        #    i2[k.encode('ascii')] = i[k]
            
        #item = Item(None, None, **i2)
        
        #item.title = i['title']
        #item.body = i['body']
        #item.tags = i['tags']

        #data = serializers.serialize("json",items)
        #return HttpResponse( data )
        #item_list = []
        #for item in items:
        #    item_list.append({'id': item.key().id(), 'title': item.title, 'body': item.body, 'tags': item.tags})
        #return HttpResponse( simplejson.dumps(item_list) )
        #item.title = item_input['title']
        #item.body = item_input['body']
        #item.encoding = item_input['encoding']
        #item.tags = item_input['tags']
        #for key in item_input.keys():
        #    item.__dict__['_' + key] = item_input[key]        
        # save new item
예제 #48
0
 def items_count(self):
     return Item.objects(collection=self.id).count() if self.id else 0
예제 #49
0
파일: views.py 프로젝트: 01walid/dzlibs
def user_profile(id):
    user = User.objects.get_or_404(user_id=id)
    items_count = Item.objects(submitter=user).count()
    return render_template('users/user_profile.html',
                           user=user,
                           items_count=items_count)
예제 #50
0
def add_item(uuid, created_at):
    time.sleep(3)
    item = Item(uuid=uuid, created_at=created_at)
    item.save()
예제 #51
0
    def get_item(self, item_id):
        try:
            item_resp = fetch('https://api.mercadolibre.com/items/%s' % item_id)
            item = anyjson.deserialize(item_resp.content)
            
            if item.has_key('site_id') and item.has_key('title'):
                i = Item()
                
                i.item_id = item_id
                
                i.site_id = item['site_id']
                i.title = item['title']
                i.subtitle = item['subtitle'] if item.has_key('subtitle') else ''
                if item.has_key('price'):
                    i.currency_id = item['currency_id']
                    i.price = item['price']
                    i.base_price = item['price'] * Currency.objects.get(currency_id=item['currency_id']).usd_exchange_rate
                
                if item.has_key('thumbnail'):
                    i.thumbnail = item['thumbnail'].replace('_I_', '_E_')

                if item.has_key('permalink'):
                    i.permalink = item['permalink']
        
                i.condition = item['condition'] if item.has_key('condition') else 'not_especified'
                i.buying_mode = item['buying_mode'] if item.has_key('buying_mode') else 'not_especified'
                i.sold_quantity = item['sold_quantity'] if item.has_key('sold_quantity') else 0
                return i
            else:
                return None
        except Exception, e:
            print e
            return None
예제 #52
0
파일: views.py 프로젝트: 01walid/dzlibs
    def post(self):

        form = AddItemForm()
        item = Item()

        categories = Category.objects.all()
        licenses = License.objects.all()
        form.set_categories(categories, g.lang)
        form.set_licenses(licenses)

        if form.validate_on_submit():
            # first, the user has to share something !
            if not form.github.data and not form.files.data:
                flash('Neither a repo URL nor files has been shared, come on!',
                      category='alert')
                return render_template('items/add_item.html', form=form)

            # give that something at least one title
            if not form.ar_title.data and not form.fr_title.data and \
               not form.en_title.data:

                flash('You need to give this item at least one title, \
                       just pick one language and name it!',
                      category='alert')
                return render_template('items/add_item.html', form=form)

            # now we can proceed
            ar_title = Title()
            fr_title = Title()
            en_title = Title()

            ar_title.title = form.ar_title.data.strip()
            ar_title.lang = 'ar'

            fr_title.title = form.fr_title.data.strip()
            fr_title.lang = 'fr'

            en_title.title = form.en_title.data.strip()
            en_title.lang = 'en'

            item.titles.append(ar_title)
            item.titles.append(fr_title)
            item.titles.append(en_title)

            item.description = form.description.data
            item.tags = form.tags.data.strip().split(',')
            item.category = Category.objects.get(category_id=
                                                 int(form.category.data))

            item.submitter = User.objects.get(id=current_user.id)

            thumbnail = request.files['thumbnail']
            thumbnail_name = secure_filename(thumbnail.filename)

            if thumbnail and allowed_thumbnails(thumbnail_name):
                ext = thumbnail.mimetype.split('/')[-1]
                # use the 'thumbnail' name for all thumbnails
                filename = '.'.join(["thumbnail", ext])
                item.thumbnail.put(thumbnail.stream,
                                   content_type=thumbnail.mimetype,
                                   filename=filename)

            if form.github.data:
                item.github = form.github.data
                item.save()
                # no need to process any uploaded files
                flash('Item submitted successfully', category='success')
                return redirect(url_for('items.detail', item_id=item.item_id))
            else:
                item.license = License.objects.get(license_id=
                                                   int(form.license.data))

        else:
            flash('upload unsuccessful', category='error')
            return render_template('items/add_item.html', form=form)

        uploaded_files = request.files.getlist("files")
        for file in uploaded_files:
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(filename):
                # put the file in the ListField.
                # see https://gist.github.com/tfausak/1299339
                file_ = GridFSProxy()
                file_.put(file.stream,
                          content_type=file.mimetype,
                          filename=filename)
                item.files.append(file_)
        # Save the thing
        item.save()
        flash('Item uploaded successfully', category='success')
        return redirect(url_for('items.detail', item_id=item.item_id))
예제 #53
0
파일: views.py 프로젝트: 01walid/dzlibs
def search(param, page=1):
    items = Pagination(Item.objects(titles__title__icontains=param),
                       1, 12)
    return render_template('frontend/search_result.html', items=items)
예제 #54
0
파일: testdata.py 프로젝트: pfeilbr/qik
import os
import sys
import logging

from google.appengine.ext import db
from django.core import serializers
from django.utils import simplejson

from items.models import Item

item = Item(title='favorite books', body='my favorite books are ...')
item.put()
items = Item.all()
data = serializers.serialize("json", items)
objs = simplejson.loads(data)

def flatten_obj(obj):
  new_obj = obj.copy()
  new_obj.update(new_obj['fields']) # add the key/value pairs that are in the fields value
  del new_obj['fields'] # remove the embeded 'fields' values since we copied them up a level
  return new_obj
  
def flatten_objs(objs):
  new_objs = []
  for obj in objs:
    new_objs.append( flatten_obj(obj) )
  return new_objs
  
def flatten_to_json(objs):
  s = serializers.serialize("json", objs)
  array = simplejson.loads(s)
예제 #55
0
파일: views.py 프로젝트: 01walid/dzlibs
def tag(param, page=1):
    items = Pagination(Item.objects(tags=param), page, 12)
    if len(items.items) == 0:
        return abort(404)
    return render_template('frontend/tag.html', tag=param, items=items)
예제 #56
0
파일: views.py 프로젝트: 01walid/dzlibs
def index():
    items_count = Item.objects(submitter=current_user.id).count()
    return render_template('users/user_profile.html', user=current_user,
                           items_count=items_count)