def parse(self, response): for item in response.xpath('//body//div[@class="mw-content-ltr"]//li/a/@href'): yield response.follow('http://dota.wikia.com' + str(item.extract()), self.parse) # yield {'heroe': 'http://dota.wikia.com' + str(hero.extract())} item_name = response.url.split('/')[-1] item_desc = response.xpath('//body//table[@class="infobox"]//td[@colspan="2"]//i/text()').extract()[0] item_effect = response.xpath('//body//table[@class="infobox"]//tr[4]//td[last()]/text()').extract()[0] item_cost = response.xpath('//body//table[@class="infobox"]//tr[6]//td[last()]/text()').extract()[0] item = Item() item.name = item_name item.description = re.sub('<.*?>', '', item_desc).replace('\n', '') item.effects = re.sub('<.*?>', '', item_effect).replace('\n', '') item.cost = int(re.sub('<.*?>', '', item_cost).replace('\n', '')) mongo_item = { 'name': item_name, 'description': re.sub('<.*?>', '', item_desc).replace('\n', ''), 'effects': re.sub('<.*?>', '', item_effect).replace('\n', ''), 'cost': int(re.sub('<.*?>', '', item_cost).replace('\n', '')), } items.insert_one(mongo_item) session.add(item) session.commit() self.log(item_effect) session.close()
def add_new_item_view(request): if request.user.is_seller is False: messages.add_message( request, messages.INFO, "toastr.error('You must be a seller to post items', 'Error');") return HttpResponseRedirect('/index') if request.method == 'POST': item = Item() try: item.description = request.POST['desl'] except: pass try: item.keywords = request.POST['key'] except: pass item.amount = request.POST['amount'] item.name = request.POST['name'] item.category = Category.objects.get(pk=request.POST['cate']) item.description_short = request.POST['dess'] item.provider = request.user item.listed_price = request.POST['price'] try: item.save() except: messages.add_message( request, messages.INFO, "toastr.error('You provided wrong data.', 'Error');") return render(request, 'ecommerce/newitem.html')
def post(self): form = AddItemForm() item = Item() if form.validate_on_submit(): ar_title = Titles() fr_title = Titles() en_title = Titles() 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.submitter = User.objects.get(id=current_user.id) else: flash('upload unsuccessful', 'error') return render_template('items/add_item.html', form=form) uploaded_files = request.files.getlist("files") 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) 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('upload successful') return render_template('items/add_item.html', form=form)
def post(self): user = json.loads(self.session["user_info"]) urlsafe_entity_key = self.request.get('item-entity-key') if len(urlsafe_entity_key) > 0: # Edit item_key = ndb.Key(urlsafe=urlsafe_entity_key) item = item_key.get() logging.info(item) else: #Add item = Item(parent=PARENT_KEY) item.seller_key = ndb_utils.get_parent_key(user) if self.get_uploads() and len(self.get_uploads()) == 1: logging.info( "Received an image blob with this text message event.") media_blob = self.get_uploads()[0] item.media_blob_key = media_blob.key() item.name = self.request.get('item_name') item.image_url = self.request.get('image_url') item.price = float(self.request.get('item_price')) item.description = self.request.get('item_description') logging.info(item) item.put() self.redirect('/')
def add_item(): if request.method == 'GET': catagories = session.query(Catagory).all() return render_template('newitem.html', catagories=catagories) elif request.method == 'POST': title_ = request.form['title'] catagory = request.form['catagory'] description = request.form['description'] exists = session.query(Item).filter_by(title=title_).first() if exists: flash('This item already exists') return redirect(request.url, 302) item = Item(title=title_) item.description = description catagory_object = session.query(Catagory).\ filter_by(name=catagory).one() item.catagory_id = catagory_object.id item.author = login_session['username'] if 'file' not in request.files: # print 'file not in request.files', request.files item.image = 'picture.png' else: file = request.files['file'] if allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) item.image = filename else: flash("Uploaded file format must be .png .jpg .jpeg or gif") return redirect(request.url, 302) session.add(item) session.commit() return redirect('/', 302)
def create_item(category): '''handles creation of a new Item''' if request.method == 'GET' and 'username' in login_session: # user is logged in, so render the createItem page categories = session.query(Category).all() return render_template('createItem.html', categories=categories, selected_category=category) elif request.method == 'GET': # user is NOT logged in, so render the loginpage flash('You need to login first to create a new item.') return render_template('login.html') elif request.method == 'POST': new_item = Item() if request.form['name']: new_item.name = request.form['name'] if request.form['description']: new_item.description = request.form['description'] category_selected = (session.query(Category).filter_by( name=request.form['category']).one()) new_item.category_id = category_selected.id new_item.creator_id = login_session['user_id'] new_item.edited_time = int(time.time()) session.add(new_item) session.commit() flash('{} created'.format(new_item.name)) return redirect( url_for('category_display', category=category_selected.name))
def new_item(request): if request.method == 'POST': item_json_obj = json.loads(request.POST['map-json']) item_obj = Item() item_obj.owner = request.user item_obj.name = item_json_obj['name'] item_obj.title = item_json_obj['title'] item_obj.url = item_json_obj['url'] item_obj.type = item_json_obj['type'] item_obj.type_keywords = ",".join(item_json_obj['typeKeywords']) item_obj.description = item_json_obj['description'] item_obj.tags = ",".join(item_json_obj['tags']) item_obj.snippet = item_json_obj['snippet'] item_obj.thumbnail = item_json_obj['thumbnail'] if item_json_obj['extent']: item_obj.extent = Polygon.from_bbox(item_json_obj['extent'][0] + item_json_obj['extent'][1]) item_obj.created = datetime.datetime.today() item_obj.modified = datetime.datetime.today() item_obj.save() if 'text' in item_json_obj: item_data_obj = ItemData(item=item_obj, text=json.dumps(item_json_obj['text'])) item_data_obj.save() return redirect(reverse('content.edit_item', args=[item_obj.id])) else: return render(request, 'content/edit_item.html')
def commit_item_changes(self,item=None): creation=not(item) if not item: item=Item(parent=self.current_user.key()) item_name=self.request.get('name') item_price=self.request.get('price') item_description=rich_text.from_style_runs(self.request.get('description')) item_picture=self.request.get('picture_512') errors=[] if item_name=="": errors.append("The item name must not be blank.") if item_description=="": errors.append("The item description must not be blank.") try: item_price=float(item_price) except ValueError: errors.append("The price must be a number.") if item_price <=0: errors.append("The price must be greater than zero.") if len(errors): self.render_template('items/form.html',title="Add an Item",item_picture_data=item_picture,item_picture=("data:image/png;base64,%s"%item_picture if item_picture or creation else item.url(named=False,action="picture")),errors=errors,item_expiry=datetime.now()+Item.EXPIRATION_DELTA,item_name=item_name,item_description=item_description,item_price=item_price) else: item.name=item_name item.price=item_price item.description=item_description if item_picture: item.picture=base64.b64decode(item_picture) item.put() self.log("item %s"%("created" if creation else "edited")) self.flash("'%s' was %s!"%(item_name,"created" if creation else "edited")) self.redirect(self.current_user.url())
def add_new(request): if request.method == "POST": i = Item() i.item_name = request.POST['item_name'] if not i.description: i.description = request.POST['description'] i.save() print i.description return HttpResponseRedirect('/simple/') return render(request, 'Simpletodo/add_new.html')
def add_item(): """ add_item: Add new item to database Args: - Returns: If method is POST, redirect back to show_items.html, if method is GET, show the add_item.html template """ logged_in = True if request.method == 'POST': name = request.form['name'] description = request.form['description'] category = request.form['category'] new_category = request.form['new_category'] category_id = '' if category == 'new_category_option': # Create new category item category = new_category c = Category(name=category) session.add(c) session.commit() item_category = session.query(Category).filter_by( name=category).one() category_id = item_category.id category = item_category.name else: old_category = session.query(Category).filter_by( id=category).one() category_id = old_category.id category = old_category.name item = Item() item.name = name item.description = description item.category = category_id # Get the current user username = login_session['username'] user = session.query(User).filter_by(username=username).one() item.creator_id = user.id session.add(item) session.commit() return redirect(url_for('show_items', logged_in=logged_in, category=category)) else: categories = session.query(Category).all() return render_template("add_item.html", logged_in=logged_in, categories=categories)
def addItems(category_id): if requireLogin(): return redirect(url_for("login")) category = db_session.query(Category).filter_by(id=category_id).one() subheading = "Add items for category '{category}' (id: {id})" \ .format(category=category.name, id=category_id) last_item = db_session.query(Item).order_by(Item.id.desc()).first() image_dir = app.config["IMG_DIR"] + "/categories/" + str(category_id) \ + "/items/" + str(last_item.id + 1) + "/" if request.method == "POST": new_item = Item() new_item.category_id = category_id new_item.name = request.form["name"] new_item.price = "$" + request.form["price"] new_item.stock = request.form["stock"] new_item.description = request.form["description"] if not request.form["description"]: new_item.description = "" # TODO: Add item image functionality # if request.files["image"]: # # create the image folder for the item # if not os.path.exists(image_dir): # os.makedirs(image_dir) # uploaded_image = request.files["image"] # safe_image = secure_filename(uploaded_image.filename) # uploaded_image.save(os.path.join(image_dir, safe_image)) # new_item.image = os.path.join(image_dir, safe_image) db_session.add(new_item) db_session.commit() flash("Successfully added item '{}'.".format(new_item.name)) return redirect(url_for("displayCategory", category_id=category_id)) elif request.method == "GET": return render_template("add_items.html", title=TITLE, subheading=subheading, category=category) else: return abort(400)
def add_item(request): if request.POST: item = Item() item.name = request.POST['item_name'] item.description = request.POST['description'] item.seller = request.user item.save() # url = reverse('add_auction', kwargs={ 'item_id': item.id }) return HttpResponseRedirect(reverse('auction:add_auction', args=(item.id,))) return render(request, 'add_item.html', {})
def new_item_save(): """ salva item no banco """ form = request.form item = Item() item.category_id = int(form['category']) item.title = form['title'] item.description = form['description'] item.created_at = datetime.datetime.now() item.user_id = current_user.id db.session.add(item) db.session.commit() return redirect(url_for('index'))
def APIAddItem(): # Reject with a 422 if token parameter not provided if "token" not in request.args: return jsonRespObj( 422, "An access token is required to perform this request.") # Check whether API user has supplied a valid access token if not checkToken(request.args["token"]): return unauthenticatedError() # Item name, category ID, and price must be provided # to add an item (stock will default to 0) if "name" not in request.args: return jsonRespObj(422, "Item name must be provided for item to be added.") elif "category_id" not in request.args: return jsonRespObj( 422, "Category ID must be provided for item to be added.") elif "price" not in request.args: return jsonRespObj(422, "Price must be provided for item to be added.") # Create a new item object new_item = Item() # Default stock level to 0 parameter/value not provided if "stock" not in request.args: new_item.stock = 0 else: new_item.stock = request.args["stock"] if "description" in request.args: new_item.description = request.args["description"] # Attempt to add the new item to DB try: new_item.name = request.args["name"] # Make sure that the price is registered in currency if request.args["price"][0] != "$": new_item.price = "$" + request.args["price"] else: new_item.price = request.args["price"] new_item.category_id = request.args["category_id"] db_session.add(new_item) db_session.commit() except: # If item could not be created, return a 500 return jsonRespObj(500, "Server-side error occurred during item creation.") # Return a 200 to user on successful creation of item return jsonRespObj( 200, "Successfully added item '{}' to database.".format( request.args["name"]))
def test_update_an_item(self): """ Update an Item """ item = Item(wishlist_id=1, product_id=1, name="toothpaste", description="toothpaste for 2") item.save() self.assertEqual(item.id, 1) item.description = "toothpaste for 1" item.save() items = Item.all() self.assertEqual(len(items), 1) self.assertEqual(items[0].description, "toothpaste for 1")
def insert_items(): with open('setup_db.json') as data_file: json_categories = json.load(data_file) for json_category in json_categories['categories']: category = Category() category.name = json_category['name'] session.add(category) session.commit() for json_item in json_category['items']: item = Item() item.name = json_item['name'] item.description = json_item['description'] item.date = datetime.datetime.utcnow() item.category = category session.add(item) session.commit() session.close()
def add_item(listid): new_item = Item() dit = parse_amz(request.form['link']) print dit new_item.name = request.form['name'] new_item.image_url = dit['image_url'] new_item.amazon_link = request.form['link'] new_item.note = request.form['notes'] new_item.description = dit['description'] s_list = mongo.db.lists.find_one({'_id': listid}) item_count = s_list['item_count'] new_item.id = item_count if item_count == 0: mongo.db.lists.update({'_id': listid}, {'$set': {'default_image': new_item.image_url}}) item_count += 1 mongo.db.lists.update({'_id': listid}, {'$push': {'items': new_item.__dict__}}) mongo.db.lists.update({'_id': listid}, {'$set': {'item_count': item_count}}) return redirect(url_for('get_list', listid=listid))
def newitem(req): if req.method == "POST": ni = ItemForm(req.POST) if ni.is_valid(): # 获取表单信息 name = ni.cleaned_data['name'] description = ni.cleaned_data['description'] # 写入数据库 item = Item() uid = req.session['user_id'] item.name = name item.description = description item.uid = uid item.save() return HttpResponseRedirect('/online/index/') else: ni = ItemForm() return render_to_response('home.html', {'ni': ni}, context_instance=RequestContext(req))
def addItem(catID): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': if request.form['name']: newItem = Item(name=request.form['name'], category_id=catID, user_id=login_session['user_id']) if request.form['description']: newItem.description = request.form['description'] if request.form['price']: newItem.price = request.form['price'] if request.form['brand']: newItem.brand = request.form['brand'] session.add(newItem) flash("New Item '%s' successfully added" % newItem.name) session.commit() return redirect(url_for('showItems', catID=catID)) else: return render_template('addItem.html', catID=catID)
def post(self): checklist = Checklist.get(self.request.get('checklist')) if not helpers.checkPermissionAndRespond(self, cl=checklist): return if not self.addable(checklist): helpers.createResponse(self, 'message_can_not_create_item.html') return item = Item( title=self.request.get('title'), difficulty=int(self.request.get('difficulty')), progress=0, checklist=checklist, deleted=False) if self.request.get('description') != '': item.description=self.request.get('description') item.put() self.redirect("/cl/" + str(checklist.key().id()))
def add_inventory_item_html(form): name = form.name.data.strip() description = form.description.data.strip() quantity = form.quantity.data price = form.price.data item = Item.query.filter_by(name=name).first() if item is None: item = Item(name=name, description=description, quantity=quantity, price=price) db.session.add(item) else: item.name = name item.quantity = quantity item.price = price if description != "": item.description = description db.session.commit() return True
def add_inventory_item_json(data): name = data['name'] description = data['description'] quantity = int(data['quantity']) price = int(data['price']) item = Item.query.filter_by(name=name).first() if item is None: item = Item(name=name, description=description, quantity=quantity, price=price) db.session.add(item) else: item.name = name item.quantity = quantity item.price = price if description != "": item.description = description db.session.commit() return jsonify(status="success")
def post(self): #Getting Inputs itemname = self.request.get("item_name") itemtype = self.request.get("item_type") itemdescription = self.request.get("item_description") itemprice = self.request.get("item_price") itemstock = self.request.get("item_stock") #Placing data in model item = Item() item.name = itemname item.type = itemtype item.description = itemdescription item.price = itemprice item.stock = itemstock item.owner = users.get_current_user().email() item.put() self.redirect('success')
def item_create_update(request, id): print 'item_create_update ', id createNew = id == 'a' if createNew: item = Item(title='', description='', author='', pic='') form = bookForm() print 'create new form' else: item = Item.objects.get(id=id) form = bookForm( initial={ 'title': item.title, 'description': item.description, 'author': item.author, 'pic': item.pic }) print 'update exisiting form' if request.method == 'POST': form = bookForm(request.POST) print 'form-update-create-POST' if form.is_valid(): # coming from save button click print 'form update-create valid' item.author = form.cleaned_data['author'] item.description = form.cleaned_data[ 'description'] or 'No Description' item.title = form.cleaned_data['title'] item.pic = form.cleaned_data['pic'] or 'img/img3.jpeg' item.save() return HttpResponseRedirect( reverse('index')) # you won't see 'form' in url else: print 'form Not Valid' return render( request, 'library/item_create_update.html', { # stay if not valid 'form': form }) else: # when getting to page at first - Stay print 'Initial update-create page ', id return render(request, 'library/item_create_update.html', {'form': form})
def post(self): #Getting Inputs itemname=self.request.get("item_name") itemtype=self.request.get("item_type") itemdescription=self.request.get("item_description") itemprice=self.request.get("item_price") itemstock=self.request.get("item_stock") #Placing data in model item=Item() item.name=itemname item.type=itemtype item.description=itemdescription item.price=itemprice item.stock=itemstock item.owner=users.get_current_user().email() item.put() self.redirect('success')
def add_item(): if request.method == 'POST': if not re.match("^[a-zA-Z0-9_]*$", request.form['name']) \ or not re.match("^[a-zA-Z0-9_,\. ]*$", request.form['description']): print('Item name or description contains invalid \ special character') return redirect(url_for('add_item')) newItem = Item() newItem.name = request.form['name'] newItem.description = request.form['description'] newItem.creator_email = session['email'] cat = data_session.query(Category).filter_by \ (name = request.form['cat']).one_or_none() cat.items.append(newItem) data_session.add(cat, newItem) data_session.commit() return redirect(url_for('home_page')) categories = data_session.query(Category).all() return render_template('add_item.html', categories = categories)
def commit_item_changes(self, item=None): creation = not (item) if not item: item = Item(parent=self.current_user.key()) item_name = self.request.get('name') item_price = self.request.get('price') item_description = rich_text.from_style_runs( self.request.get('description')) item_picture = self.request.get('picture_512') errors = [] if item_name == "": errors.append("The item name must not be blank.") if item_description == "": errors.append("The item description must not be blank.") try: item_price = float(item_price) except ValueError: errors.append("The price must be a number.") if item_price <= 0: errors.append("The price must be greater than zero.") if len(errors): self.render_template( 'items/form.html', title="Add an Item", item_picture_data=item_picture, item_picture=("data:image/png;base64,%s" % item_picture if item_picture or creation else item.url(named=False, action="picture")), errors=errors, item_expiry=datetime.now() + Item.EXPIRATION_DELTA, item_name=item_name, item_description=item_description, item_price=item_price) else: item.name = item_name item.price = item_price item.description = item_description if item_picture: item.picture = base64.b64decode(item_picture) item.put() self.log("item %s" % ("created" if creation else "edited")) self.flash("'%s' was %s!" % (item_name, "created" if creation else "edited")) self.redirect(self.current_user.url())
def api_item(request, item_pk=None): created = False if item_pk: item = Item.objects.get(pk=item_pk) if not item.created_by == request.user: import pdb pdb.set_trace() return HttpResponse(status=403) else: item = Item() item.created_by = request.user created = True if request.POST.get('delete'): item.delete() else: expense = Expense.objects.get(pk=request.POST.get('expense')) if not expense.created_by == request.user: return HttpResponse(status=403) item.expense = expense item.description = request.POST.get('description') item.amount = request.POST.get('amount') item.save() user_pks = request.POST.getlist('users') item.users.clear() for pk in user_pks: user = User.objects.get(pk=pk) item.users.add(user) if request.is_ajax(): return HttpResponse(json.dumps({ 'type': 'item', 'item_pk': item.pk, 'item_created': created, 'item_form': render_to_response('item_form.html', {'expense':item.expense, 'item':item}, context_instance = RequestContext(request)).content, 'empty_form': render_to_response('item_form.html', {'expense':item.expense}, context_instance = RequestContext(request)).content })) return HttpResponseRedirect("/%s" % item.expense_id)
def populate_sample_items(): num_items = 30 lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum".split( " ") user = User.objects.get(username="******") for i in range(num_items): item = Item() item.owner = user item.name = " ".join(random.sample(lorem, rand_int(3, 10))) item.description = " ".join(random.sample(lorem, rand_int(10, 20))) item.quantity = rand_int(0, 7) item.cost = float(rand_int(0, 10)) item.save() print "{} sample entries added!".format(num_items)
def create_invoice(invoice_body): global AUTH_HEADER user_url = get_service_url('user-ms') payments_url = get_service_url('payments') inventory_url = get_service_url('inventory') statistics_url = get_service_url('statistics') discounts_url = get_service_url('discounts') update_jwt_token() # Get User Details from User microservice user = requests.get(url=f"{user_url}/details/{invoice_body['user_id']}", headers=AUTH_HEADER) # Get Transaction details from Payments microservice transaction = requests.get( url=f"{payments_url}/transactions/{invoice_body['transaction_id']}", headers=AUTH_HEADER) # Get Items from Inventory microservice items = [] for item in invoice_body['item_list']: requests.post(url=f"{statistics_url}/invoice/", headers=AUTH_HEADER, json={ 'user_id': invoice_body['user_id'], 'type_of_product': item.type, 'quantity': item.quantity }) it = Item() if item.type == 'Rent': new_item = requests.get( url=f"{inventory_url}/get/product_rent/{item.id}", headers=AUTH_HEADER) it.id = item.id it.name = new_item.name it.type = item.type it.description = new_item.description it.duration = item.quantity items.append(it) elif item.type == 'Buy': new_item = requests.get( url=f"{inventory_url}/get/product_rent/{item.id}", headers=AUTH_HEADER) it.id = item.id it.name = new_item.name it.type = item.type it.description = new_item.description it.quantity = item.quantity items.append(it) elif item.type == 'Coupon': new_item = requests.get( url=f"{inventory_url}/get/product_rent/{item.id}", headers=AUTH_HEADER) requests.post(url=f"{discounts_url}/coupon/create", headers=AUTH_HEADER, json={ 'id': item.id, 'type': new_item.type, 'userId': invoice_body['user_id'] }) new_invoice = Invoice(name=user.name, surname=user.surname, username=user.username, country=user.country, city=user.city, postal_code=user.postal_code, address=user.address, price=transaction.amount, date=date.today(), items=items) # new_invoice = Invoice(id=1, name='Petko', surname='Petkovski', # user_id=1, country='Macedonia', # city='Debar', postal_code=1250, address='Ulica br.11/11', # price=69.99, date=date.today()) db.session.add(new_invoice) db.session.commit()
DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() test_user = User() test_user.username = "******" test_user.email = "*****@*****.**" session.add(test_user) session.commit() new_category = Category() new_category.name = "Soccer" session.add(new_category) session.commit() new_item = Item() new_item.name = "Abibas Predadors" new_item.description = "I was created by admin and can't be deleted." new_item.price = 120.59 new_item.category_id = new_category.id new_item.created_by = test_user.id session.add(new_item) session.commit()
def item_post(id=None): db.session.rollback() # See comment in create_transaction() if id: itm = Item.query.get_or_404(id) else: id = make_url_safe(request.form.get('name')) itm = Item(id=id) db.session.add(itm) itm.name = request.form.get('name') itm.description = request.form.get('description') itm.count = int(request.form.get('count')) if request.form.get('count') else 1 itm.tax_base_int = request_or_none('tax_base_int') itm.tax_base_edu = request_or_none('tax_base_edu') itm.tax_base_ext = request_or_none('tax_base_ext') itm.tax_int = request_or_none('tax_int') itm.tax_edu = request_or_none('tax_edu') itm.tax_ext = request_or_none('tax_ext') itm.related = [] for iid in request.form.get('related').split(', '): if iid == '': continue i = Item.query.get(iid) if i is None: flash(u'Artikel "%s" ist nicht bekannt!' % ii ) continue itm.related.append(i) itm.tax_period = request.form.get('tax_period') itm.price_buy = request_or_none('price_buy') itm.category = request.form.get('category') db.session.commit() # Update image if necessary file = request.files['image'] if file: import os from PIL import Image as i filename = secure_filename(id).lower() + '.jpg' image = i.open(file) if image.mode != "RGB": image = image.convert("RGB") image.save(os.path.join(app.config['UPLOAD_FOLDER'], 'full', filename), "jpeg") w = image.size[0] h = image.size[1] aspect = w / float(h) ideal_aspect = 1.0 if aspect > ideal_aspect: # Then crop the left and right edges: w_ = int(ideal_aspect * h) offset = (w - w_)/2 resize = (offset, 0, w - offset, h) else: # ... crop the top and bottom: h_ = int(w/ideal_aspect) offset = (h - h_)/2 resize = (0, offset, w, h - offset) image = image.crop(resize).resize((140, 140), i.ANTIALIAS) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename), "jpeg") return redirect( url_for('item', id=id) )
def post(self): form = AddItemForm() item = Item() if form.validate_on_submit(): ar_meta = Meta() fr_meta = Meta() en_meta = Meta() ar_meta.title = form.ar_title.data.strip() ar_meta.short_description = form.ar_short_description.data ar_meta.lang = 'ar' fr_meta.title = form.fr_title.data.strip() fr_meta.short_description = form.fr_short_description.data fr_meta.lang = 'fr' en_meta.title = form.en_title.data.strip() en_meta.short_description = form.en_short_description.data en_meta.lang = 'en' item.meta_info.append(ar_meta) item.meta_info.append(fr_meta) item.meta_info.append(en_meta) item.description = form.description.data item.submitter = User.objects.get(id=current_user.id) else: flash('upload unsuccesful', 'error') return render_template('items/add_item.html', form=form) uploaded_files = request.files.getlist("files") thumbnail = request.files['thumbnail'] thumbnail_name = secure_filename(thumbnail.filename) path = os.path.join(app.config['UPLOAD_FOLDER'], str(item.item_id)) make_dir(path) if thumbnail and allowed_file(thumbnail.filename): thumbnail.save(os.path.join(path, thumbnail_name)) filenames = [] for file in uploaded_files: # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to the upload # folder we setup file.save(os.path.join(path, filename)) # Save the filename into a list, we'll use it later # filenames.append(filename) item.item_data.append(filename) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file # Load an html page with a link to each uploaded file # item.item_data.append(filenames) item.save() flash('upload succesful') return render_template('items/add_item.html', form=form)
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))
def item_post(id=None): db.session.rollback() # See comment in create_transaction() if id: itm = Item.query.get_or_404(id) else: id = make_url_safe(request.form.get('name')) itm = Item(id=id) db.session.add(itm) itm.name = request.form.get('name') itm.description = request.form.get('description') itm.count = int( request.form.get('count')) if request.form.get('count') else 1 itm.tax_base_int = request_or_none('tax_base_int') itm.tax_base_edu = request_or_none('tax_base_edu') itm.tax_base_ext = request_or_none('tax_base_ext') itm.tax_int = request_or_none('tax_int') itm.tax_edu = request_or_none('tax_edu') itm.tax_ext = request_or_none('tax_ext') itm.related = [] for iid in request.form.get('related').split(', '): if iid == '': continue i = Item.query.get(iid) if i is None: flash(u'Artikel "%s" ist nicht bekannt!' % ii) continue itm.related.append(i) itm.tax_period = request.form.get('tax_period') itm.price_buy = request_or_none('price_buy') itm.category = request.form.get('category') db.session.commit() # Update image if necessary file = request.files['image'] if file: import os from PIL import Image as i filename = secure_filename(id).lower() + '.jpg' image = i.open(file) if image.mode != "RGB": image = image.convert("RGB") image.save(os.path.join(app.config['UPLOAD_FOLDER'], 'full', filename), "jpeg") w = image.size[0] h = image.size[1] aspect = w / float(h) ideal_aspect = 1.0 if aspect > ideal_aspect: # Then crop the left and right edges: w_ = int(ideal_aspect * h) offset = (w - w_) / 2 resize = (offset, 0, w - offset, h) else: # ... crop the top and bottom: h_ = int(w / ideal_aspect) offset = (h - h_) / 2 resize = (0, offset, w, h - offset) image = image.crop(resize).resize((140, 140), i.ANTIALIAS) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename), "jpeg") return redirect(url_for('item', id=id))
def add_estrategia(request): data = json.loads(request.body) name = data['name']; description = data['description'] thumbnail = data['thumbnail'] # getlist('images[]') images = data['images'] type = data['type'] author = data['author'] if thumbnail == '': thumbnail == None itemCode = data['id'] print 'add_estrategia', itemCode if itemCode == '' or itemCode == 0: item = Item() item.type = int(smart_text(type, encoding='utf-8', strings_only=False, errors='strict')) else: item = Item.objects.get(item_code=itemCode, version=0, author=author) item.name = smart_text(name, encoding='utf-8', strings_only=False, errors='strict') item.description = smart_text(description, encoding='utf-8', strings_only=False, errors='strict') item.thumbnail = thumbnail item.status = '1' item.author_id = author ob = None if type == models.TECHNOLOGY: # TODO: agregar cosas especificas de cada tipo de item ob = models.Technology( name=name, description = ':V' ) ob.save() item.technology = ob elif type == models.TOOL: devPk = data['subclassId']; print "toolPk", devPk if devPk == '': ob = models.Tool() else: ob = models.Development.objects.get(pk=devPk) ob.name = name ob.description = ':v' ob.technology = models.Technology.objects.get(pk=data['technology']) ob.url = data['toolUrl'] ob.download_url = data['toolDownloadUrl'] ob.license_type = data['licenseType'] ob.use_restrictions = data['useRestrictions'] ob.integration = data['integration'] ob.functional_description = data['functionalDescription'] ob.operating_systems = smart_text(",".join(data['operativeSystems']), encoding='utf-8', strings_only=False, errors='strict') ob.save() item.tool = ob elif type == models.TUTORIAL: devPk = data['subclassId']; print "tutorialPk", devPk if devPk == '': ob = models.Tutorial() else: ob = models.Tutorial.objects.get(pk=devPk) ob.name = name ob.url = data['tutorialUrl'] ob.tool_id = data['tool'] ob.save() item.tutorial = ob elif type == models.EXAMPLE: devPk = data['subclassId']; print "examplePk", devPk if devPk == '': ob = models.Example() else: ob = models.Example.objects.get(pk=devPk) ob.name = name ob.url = data['exampleUrl'] ob.strategy_id = data['strategy'] ob.tool_id = data['tool'] ob.save() item.example = ob elif type == models.STRATEGY: devPk = data['subclassId']; print "strategyPk", devPk if devPk == '': ob = models.Strategy() else: ob = models.Strategy.objects.get(pk=devPk) ob.name = name ob.save() item.strategy = ob elif type == models.DEVELOPMENT: devPk = data['subclassId']; print "devPk", devPk if devPk == '': ob = models.Development( name=name ) ob.save() else: ob = models.Development.objects.get(pk=devPk) ob.dev_technologies.clear() ob.save() for tech in data['devTechs']: # the list of devTechs PK's print "tech", tech ob.dev_technologies.add(tech) ob.save() item.development = ob elif type == models.DISCIPLINE: devPk = data['subclassId'] print "disciplinePk", devPk if devPk == '': ob = models.Discipline( name=name ) ob.save() else: ob = models.Discipline.objects.get(pk=devPk) ob.tools.clear() ob.save() for _tool in data['tools']: # the list of devTechs PK's print "tool", _tool ob.tools.add(_tool) ob.save() item.discipline = ob for tech in data['devTechs']: # the list of devTechs PK's print "tech", tech ob.dev_technologies.add(tech) item.save() if item.item_code == -1: print "Version ", data['version'] if data['version'] == "2": print "Created draft of an aproved item" item.item_code = data['item_code'] else: item.item_code = item.pk item.save() item.images.clear() for image in images: newImg = models.Image.objects.create(image=image) item.images.add(newImg) item.save() print name, description, thumbnail, images _ob = serializers.serialize("json", [ob]) _item = serializers.serialize("json", [item]) sendToReview = data['sendToReview']; if (sendToReview): createReviewVersion(item) return JsonResponse({'mensaje': 'ok', 'item': _item, 'strategy': _ob})
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))