def edit_item(item_id): item = crud.get_item_no_categories(item_id) if item: form = EditItemForm() if form.validate_on_submit(): filename = save_image_upload(form.image) if form.image.data \ else item["image"] # update data # escape()したデータはテンプレートでsafeフィルターを併用すること crud.update_item(item_id, title=escape(form.title.data), description=escape(form.description.data), price=float(form.price.data), image=filename) flash( "Item {} has been successfully updated".format( form.title.data), "success") return redirect(url_for("item", item_id=item_id)) form.title.data = unescape(item["title"]) form.description.data = unescape(item["description"]) form.price.data = item["price"] return render_template("edit_item.html", item=item, form=form) return redirect(url_for("home"))
def _shorten_links(self, html, link_tracker_vals, blacklist=None, base_url=None): """ :param link_tracker_vals: values given to the created link.tracker, containing for example: campaign_id, medium_id, source_id, and any other relevant fields like mass_mailing_id in mass_mailing; :return: update """ base_url = base_url or self.env['ir.config_parameter'].sudo( ).get_param('web.base.url') short_schema = base_url + '/r/' for match in re.findall(tools.HTML_TAG_URL_REGEX, html): href = match[0] long_url = match[1] label = (match[3] or '').strip() if not blacklist or not [ s for s in blacklist if s in long_url ] and not long_url.startswith(short_schema): create_vals = dict(link_tracker_vals, url=utils.unescape(long_url), label=utils.unescape(label)) link = self.env['link.tracker'].create(create_vals) if link.short_url: new_href = href.replace(long_url, link.short_url) html = html.replace(href, new_href) return html
def edit(username): form = UpdateAccountForm() user = User.query.filter_by(username=username).first() if user == current_user or current_user.is_admin(): if form.validate_on_submit(): user.location = escape(form.location.data) user.username = form.username.data user.first_name = escape(form.first_name.data) user.last_name = escape(form.last_name.data) user.email = form.email.data user.phone = form.phone.data user.dob = form.dob.data user.password = form.password.data db.session.add(user) db.session.commit() flash("Account has been updated.", "success") return redirect(url_for("account.show", username=user.username)) form.location.data = unescape(user.location) form.username.data = user.username form.first_name.data = unescape(user.first_name) form.last_name.data = unescape(user.last_name) form.email.data = user.email form.phone.data = user.phone form.dob.data = user.dob return render_template("edit_account.html", form=form, user=user) return abort(403)
def edit(): form = UpdateAccountForm() if form.validate_on_submit(): current_user.location = escape(form.location.data) current_user.description = escape(form.description.data) db.session.add(current_user._get_current_object()) db.session.commit() flash('Your account has been updated.', 'success') return redirect(url_for('account.show', username=current_user.username)) form.location.data = unescape(current_user.location) form.description.data = unescape(current_user.description) return render_template('account/edit_account.html', form=form)
def _shorten_links_text(self, content, link_tracker_vals, blacklist=None, base_url=None): """ Shorten links in a string content. Works like ``_shorten_links`` but targetting string content, not html. :return: updated content """ base_url = base_url or self.env['ir.config_parameter'].sudo( ).get_param('web.base.url') shortened_schema = base_url + '/r/' unsubscribe_schema = base_url + '/sms/' for original_url in re.findall(tools.TEXT_URL_REGEX, content): # don't shorten already-shortened links or links towards unsubscribe page if original_url.startswith( shortened_schema) or original_url.startswith( unsubscribe_schema): continue # support blacklist items in path, like /u/ parsed = urls.url_parse(original_url, scheme='http') if blacklist and any(item in parsed.path for item in blacklist): continue create_vals = dict(link_tracker_vals, url=utils.unescape(original_url)) link = self.env['link.tracker'].create(create_vals) if link.short_url: content = content.replace(original_url, link.short_url, 1) return content
def open_moinpage_part(self, elem): type = elem.get(moin_page.content_type, "").split(';') if len(type) == 2: if type[0] == "x-moin/macro": name = type[1].split('=')[1] eol = '\n\n' if elem.tag.name == 'part' else '' if len(elem) and elem[0].tag.name == "arguments": return "{0}<<{1}({2})>>{0}".format(eol, name, elem[0][0]) else: return "{0}<<{1}()>>{0}".format(eol, name) elif type[0] == "x-moin/format": elem_it = iter(elem) ret = "{{{{{{#!{0}".format(type[1].split('=')[1]) if len(elem) and next(elem_it).tag.name == "arguments": args = [] for arg in next(iter(elem)): if arg.tag.name == "argument": args.append("{0}=\"{1}\"".format( arg.get(moin_page.name, ""), ' '.join(arg.itertext()))) ret = '{0}({1})'.format(ret, ' '.join(args)) elem = next(elem_it) ret = "{0}\n{1}\n}}}}}}\n".format(ret, ' '.join(elem.itertext())) return ret return unescape(elem.get(moin_page.alt, '')) + "\n"
def show_results(): """This shows the results of search on search page. Working here May 31th. """ user_query = request.args.get("search") search_activity = SearchActivity(user_id=session.get('user_id'), search_query=user_query, datetime = datetime.now()) db.session.add(search_activity) db.session.commit() search_items_not_filtered_list = user_search(user_query) found_items = [] for item in search_items_not_filtered_list: Taxonomy_obj = db.session.query(Taxonomy).filter(Taxonomy.path.like("%Food%")).filter_by(category_node=item[u'categoryNode']).all() for obj in Taxonomy_obj: if item[u'categoryNode'] == obj.category_node: found_items.append({ "name": item.get(u'name', ""), "item_id": item.get(u'itemId', ""), "category": item.get(u'categoryPath', ""), "sale_price": format(item.get(u'salePrice', ""), ".2f"), "description": unescape(item.get(u'shortDescription', "")), "customer_rating_img": item.get(u'customerRatingImage', ""), "thumbnail_image": item.get(u'thumbnailImage', "") }) return render_template("searchresults.html", found_items=found_items)
def open_moinpage_part(self, elem): type = elem.get(moin_page.content_type, u"").split(u';') if len(type) == 2: if type[0] == "x-moin/macro": if len(elem) and iter(elem).next().tag.name == "arguments": return u"<<%s(%s)>>\n" % (type[1].split(u'=')[1], u','.join([ u''.join(c.itertext()) for c in iter(elem).next() if c.tag.name == u"argument" ])) else: return u"<<%s()>>\n" % type[1].split(u'=')[1] elif type[0] == "x-moin/format": elem_it = iter(elem) ret = u"{{{#!%s" % type[1].split(u'=')[1] if len(elem) and elem_it.next().tag.name == "arguments": args = [] for arg in iter(elem).next(): if arg.tag.name == "argument": args.append(u"%s=\"%s\"" % (arg.get(moin_page.name, u""), u' '.join(arg.itertext()))) ret = u'%s(%s)' % (ret, u' '.join(args)) elem = elem_it.next() ret = u"%s\n%s\n}}}\n" % (ret, u' '.join(elem.itertext())) return ret return unescape(elem.get(moin_page.alt, u'')) + u"\n"
def _convert_links_text(self, body, vals, blacklist=None): if not body: return body shortened_schema = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') + '/r/' unsubscribe_schema = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') + '/sms/' for original_url in re.findall(TEXT_URL_REGEX, body): # don't shorten already-shortened links or links towards unsubscribe page if original_url.startswith( shortened_schema) or original_url.startswith( unsubscribe_schema): continue # support blacklist items in path, like /u/ parsed = urls.url_parse(original_url, scheme='http') if blacklist and any(item in parsed.path for item in blacklist): continue vals['url'] = utils.unescape(original_url) link = self.create(vals) shortened_url = link.short_url if shortened_url: body = body.replace(original_url, shortened_url, 1) return body
def show_results(): """This shows the results of search on search page. Working here May 31th. """ user_query = request.args.get("search") # user = session.get("name") # print user_query search_activity = SearchActivity(user_id=session.get('user_id'), search_query=user_query, datetime=datetime.now()) db.session.add(search_activity) db.session.commit() # print search_activity.query_id # print search_activity.search_query search_items_not_filtered_list = user_search(user_query) found_items = [] # name = item_stuff_dict[item[u'name']] # print item_stuff_dict for item in search_items_not_filtered_list: # search_items_not_filtered_list is a list of dicts # print type(item) ==> this is dict # print type(search_items_not_filtered_list) this is a list # print item[u'categoryNode'] # print item[u'categoryNode'] => this prints a categoryNode in the terminal Taxonomy_obj = db.session.query(Taxonomy).filter( Taxonomy.path.like("%Food%")).filter_by( category_node=item[u'categoryNode']).all() # print Taxonomy_obj # this is a list for obj in Taxonomy_obj: # print item[u'categoryNode'] => this prints category nodes such as 976759_976796_1001442, for canned chicken search this returned 9 # print obj # print item[u'thumbnailImage'] if item[u'categoryNode'] == obj.category_node: # here i am trying to assign name, category, sale_price, description, customer_rating_img to # item_stuff_dict[item[u'name']] but i need to assigned to item_stuff_dict not item_stuff_dict[item[u'name']] found_items.append({ "name": item.get(u'name', ""), "item_id": item.get(u'itemId', ""), "category": item.get(u'categoryPath', ""), "sale_price": format(item.get(u'salePrice', ""), ".2f"), "description": unescape(item.get(u'shortDescription', "")), # when I run server.py I receive a KeyError: u'ShortDescription' "customer_rating_img": item.get(u'customerRatingImage', ""), "thumbnail_image": item.get(u'thumbnailImage', "") }) # print found # [(2.50, 'green', 'dsd sdsd'), (3.50, 'red', '34343')] # [{'price': 2.50, 'color': 'red'}] return render_template("searchresults.html", found_items=found_items)
def parse_meta(content, link=None): """Parse og information from HTML content. :param content: HTML content to be parsed. unicode required. """ head = content.split(u'</head>', 1)[0] pairs = {} def parse_pair(kv): name = kv.get(u'name') if not name: name = kv.get(u'property') if not name: return if name in pairs: return content = kv.get(u'content') if not content: return pairs[name] = content for text in META_TAG.findall(head): kv = META_ATTR.findall(text) if kv: parse_pair(dict(kv)) rv = {} def get_og_value(key): for name in [u'og:%s' % key, u'twitter:%s' % key]: if name in pairs: rv[key] = pairs[name] for key in [u'title', u'image', u'description', u'url']: get_og_value(key) if u'twitter:creator' in pairs: rv[u'twitter'] = pairs[u'twitter:creator'] if u'title' not in rv: m = TITLE.findall(head) if m: rv[u'title'] = m[0] if u'description' not in rv: desc = rv.get(u'description') if desc: rv[u'description'] = desc # format absolute link if link and u'image' in rv: rv[u'image'] = url_join(link, rv[u'image']) rv.update(parse_embed(pairs)) for key in [u'title', u'description']: if rv.get(key): rv[key] = unescape(rv[key]) return rv
def edit_item(item_id): conn = get_db() c = conn.cursor() item_from_db = c.execute("SELECT * FROM items WHERE id = ?", (item_id, )) row = c.fetchone() try: item = { "id": row[0], "title": row[1], "description": row[2], "price": row[3], "image": row[4] } except: item = {} if item: form = EditItemForm() if form.validate_on_submit(): filename = item["image"] if form.image.data: filename = save_image_upload(form.image) c.execute( """UPDATE items SET title = ?, description = ?, price = ?, image = ? WHERE id = ?""", (form.title.data, form.description.data, float( form.price.data), filename, item_id)) conn.commit() flash( "Item {} has been successfully updated.".format( form.title.data), "success") return redirect(url_for("item", item_id=item_id)) form.title.data = unescape(item["title"]) form.description.data = unescape(item["description"]) form.price.data = item["price"] # if form.errors: # flash("{}".format(form.errors), "danger") return render_template("edit_item.html", item=item, form=form) return redirect(url_for("home"))
def edit_item(item_id): conn = get_db() c = conn.cursor() item_from_db = c.execute("""SELECT * FROM items WHERE id = ?""", (item_id, )) row = c.fetchone() try: item = { "id": row[0], "title": row[1], "description": row[2], "price": row[3], "image": row[4] } except TypeError: item = {} if item: form = EditItemForm() if form.validate_on_submit(): filename = item["image"] if form.image.data: filename = save_image_upload(form.image.data) # form = EditItemForm(title=item['title'], # description=item['description'], # price=item['price'], # image="") c.execute( """UPDATE items SET title = ?, description = ?, price = ?, image = ? WHERE id = ? """, (form.title.data, form.description.data, float( form.price.data), filename, item_id)) conn.commit() flash(f"Item {form.title.data} has been successfully edited.", "success") return redirect(url_for('items.item', item_id=item_id)) form.title.data = item["title"] form.description.data = unescape(item["description"]) form.price.data = item["price"] if form.errors: flash(f"{form.errors}", "danger") return render_template('edit_item.html', form=form, item=item) return redirect(url_for("main.index"))
def edit(slug): form = UpdateGigForm() gig = Gig.query.filter_by(slug=slug).first() if not gig: abort(404) if form.validate_on_submit(): gig.update(title=escape(form.title.data), description=escape(form.description.data), payment=form.payment.data, location=escape(form.location.data)) db.session.add(gig) db.session.commit() flash('The gig has been updated.', 'success') return redirect(url_for('gig.show', slug=gig.slug)) form.title.data = unescape(gig.title) form.description.data = unescape(gig.description) form.payment.data = gig.payment form.location.data = unescape(gig.location) return render_template('gig/edit_gig.html', gig=gig, form=form)
def edit(slug): form = UpdateGigForm() gig = Gig.query.filter_by(slug=slug).first() if form.validate_on_submit(): gig.title = escape(form.title.data) gig.description = escape(form.description.data) gig.payment = form.payment.data gig.location = escape(form.location.data) db.session.add(gig) db.session.commit() flash("The gig is updated.", "success") return redirect(url_for("gig.show", slug=gig.slug)) form.title.data = unescape(gig.title) form.description.data = unescape(gig.description) form.payment.data = gig.payment form.location.data = unescape(gig.location) return render_template("edit_gig.html", gig=gig, form=form)
def _shorten_links(self, html, link_tracker_vals, blacklist=None, base_url=None): """ Shorten links in an html content. It uses the '/r' short URL routing introduced in this module. Using the standard Odoo regex local links are found and replaced by global URLs (not including mailto, tel, sms). TDE FIXME: could be great to have a record to enable website-based URLs :param link_tracker_vals: values given to the created link.tracker, containing for example: campaign_id, medium_id, source_id, and any other relevant fields like mass_mailing_id in mass_mailing; :param list blacklist: list of (local) URLs to not shorten (e.g. '/unsubscribe_from_list') :param str base_url: either given, either based on config parameter :return: updated html """ base_url = base_url or self.env['ir.config_parameter'].sudo( ).get_param('web.base.url') short_schema = base_url + '/r/' for match in re.findall(tools.HTML_TAG_URL_REGEX, html): href = markupsafe.Markup(match[0]) long_url = match[1] label = (match[3] or '').strip() if not blacklist or not [ s for s in blacklist if s in long_url ] and not long_url.startswith(short_schema): create_vals = dict(link_tracker_vals, url=utils.unescape(long_url), label=utils.unescape(label)) link = self.env['link.tracker'].create(create_vals) if link.short_url: new_href = href.replace(long_url, link.short_url) html = html.replace(href, new_href) return html
def edit_item(item_id): conn = get_db() c = conn.cursor() item_from_db = c.execute("SELECT * FROM items WHERE id = ?", (item_id, )) row = c.fetchone() try: item = { "id": row[0], "title": row[1], "description": row[2], "price": row[3], "image": row[4] } except: item = dict() if item: form = EditItemForm() print('before validate_on_submit') if form.validate_on_submit(): print('inside validate_on_submit') filename = item["image"] if form.image.data: filename = save_image_upload(form.image) c.execute( """ UPDATE items SET title = ?, description = ?, price = ?, image = ? WHERE id = ?""", (escape(form.title.data), escape(form.description.data), float(form.price.data), filename, item_id)) conn.commit() flash(f"Item {form.title.data} has been successfully updated.", "success") return redirect(url_for('item', item_id=item_id)) print('after validate_on_submit') form.title.data = item['title'] form.description.data = unescape(item['description']) form.price.data = item['price'] # if form.errors: # flash(f"{form.errors}", "danger") return render_template("edit_item.html", item=item, form=form) return redirect(url_for('home'))
def show_results(): """This shows the results of search on search page. Working here May 31th. """ user_query = request.args.get("search") # user = session.get("name") # print user_query search_activity = SearchActivity(user_id=session.get('user_id'), search_query=user_query, datetime = datetime.now()) db.session.add(search_activity) db.session.commit() # print search_activity.query_id # print search_activity.search_query search_items_not_filtered_list = user_search(user_query) found_items = [] # name = item_stuff_dict[item[u'name']] # print item_stuff_dict for item in search_items_not_filtered_list: # search_items_not_filtered_list is a list of dicts # print type(item) ==> this is dict # print type(search_items_not_filtered_list) this is a list # print item[u'categoryNode'] # print item[u'categoryNode'] => this prints a categoryNode in the terminal Taxonomy_obj = db.session.query(Taxonomy).filter(Taxonomy.path.like("%Food%")).filter_by(category_node=item[u'categoryNode']).all() # print Taxonomy_obj # this is a list for obj in Taxonomy_obj: # print item[u'categoryNode'] => this prints category nodes such as 976759_976796_1001442, for canned chicken search this returned 9 # print obj # print item[u'thumbnailImage'] if item[u'categoryNode'] == obj.category_node: # here i am trying to assign name, category, sale_price, description, customer_rating_img to # item_stuff_dict[item[u'name']] but i need to assigned to item_stuff_dict not item_stuff_dict[item[u'name']] found_items.append({ "name": item.get(u'name', ""), "item_id": item.get(u'itemId', ""), "category": item.get(u'categoryPath', ""), "sale_price": format(item.get(u'salePrice', ""), ".2f"), "description": unescape(item.get(u'shortDescription', "")), # when I run server.py I receive a KeyError: u'ShortDescription' "customer_rating_img": item.get(u'customerRatingImage', ""), "thumbnail_image": item.get(u'thumbnailImage', "") }) # print found # [(2.50, 'green', 'dsd sdsd'), (3.50, 'red', '34343')] # [{'price': 2.50, 'color': 'red'}] return render_template("searchresults.html", found_items=found_items)
def convert_links(self, html, vals, blacklist=None): for match in re.findall(URL_REGEX, html): short_schema = self.env['ir.config_parameter'].sudo().get_param('web.base.url') + '/r/' href = match[0] long_url = match[1] vals['url'] = utils.unescape(long_url) if not blacklist or not [s for s in blacklist if s in long_url] and not long_url.startswith(short_schema): link = self.create(vals) shorten_url = self.browse(link.id)[0].short_url if shorten_url: new_href = href.replace(long_url, shorten_url) html = html.replace(href, new_href) return html
def open_moinpage_part(self, elem): type = elem.get(moin_page.content_type, u"").split(u';') if len(type) == 2: if type[0] == "x-moin/macro": if len(elem) and iter(elem).next().tag.name == "arguments": return u"<<{0}({1})>>\n".format(type[1].split(u'=')[1], u','.join([u''.join(c.itertext()) for c in iter(elem).next() if c.tag.name == u"argument"])) else: return u"<<{0}()>>\n".format(type[1].split(u'=')[1]) elif type[0] == "x-moin/format": elem_it = iter(elem) ret = u"{{{{{{#!{0}".format(type[1].split(u'=')[1]) if len(elem) and elem_it.next().tag.name == "arguments": args = [] for arg in iter(elem).next(): if arg.tag.name == "argument": args.append(u"{0}=\"{1}\"".format(arg.get(moin_page.name, u""), u' '.join(arg.itertext()))) ret = u'{0}({1})'.format(ret, u' '.join(args)) elem = elem_it.next() ret = u"{0}\n{1}\n}}}}}}\n".format(ret, u' '.join(elem.itertext())) return ret return unescape(elem.get(moin_page.alt, u'')) + u"\n"
def api(): if 'q' in request.args: query = request.args['q'] if not isinstance(query, str): return Response('To Short', mimetype='text/html') if len(query) < 3: return Response('To Short', mimetype='text/html') else: return Response('No arguments', mimetype='text/html') if model is None: load_fasttext_model() qclean = unescape(query).lower() result = model.predict(qclean, k=5) ret = [] for i, pred in enumerate(result[0]): ret.append({ 'nace': pred.replace('__label__', '').replace('"', ''), 'value': str(result[1][i]) }) return Response(json.dumps(ret), mimetype='application/json')
def search(self): """ This page is called by AJAX (javascript) on the home page, to get the songlist. Arguments to the call are the query, the page and the page_size (defaults to 50). """ page_size = request.args.get("page_size", default=100, type=int) page = request.args.get("page", default=0, type=int) query_string = unescape(request.args.get("query", default="")) sort_by = request.args.get("sort_by", default="") favourites = request.args.get("favourites", default="False") == "True" average_rating_for_songs = db.session.query(Rating.song_id, func.avg(Rating.value).label("rating")) \ .group_by(Rating.song_id).subquery() user_rating_for_songs = Song.query.join(Rating).with_entities(Rating.song_id, Rating.value.label("rating")) \ .filter(Rating.user_id == current_user.id) \ .subquery() filter_condition = (Artist.name.contains(query_string) | Dance.name.contains(query_string) | Song.title.contains(query_string) | Label.name.contains(query_string)) filter_condition &= self._filter_condition_for_wishlist() if favourites: rating = user_rating_for_songs else: rating = average_rating_for_songs songs_with_queried_content = Song.query.join(Artist, Dance).outerjoin(LabelsToSongs, Label) \ .filter(filter_condition) songs_with_rating = songs_with_queried_content \ .outerjoin(rating, Song.id == rating.c.song_id) \ .group_by(Song.id) \ .with_entities(Song, rating.c.rating.label("rating")) ordering_tuples = () if sort_by == "title": ordering_tuples += (Song.title,) elif sort_by == "artist": ordering_tuples += (Artist.name,) elif sort_by == "dance": ordering_tuples += (Dance.name,) elif sort_by == "label": ordering_tuples += (Label.name,) elif sort_by == "rating": ordering_tuples += (desc("rating"),) elif sort_by == "duration": ordering_tuples += (desc(Song.duration),) elif sort_by == "bpm": ordering_tuples += (Song.bpm,) ordering_tuples = ordering_tuples + (desc("rating"), Song.title, Dance.name) sorted_songs_with_rating = songs_with_rating.order_by(*ordering_tuples) songs = sorted_songs_with_rating.limit(page_size).offset(page * page_size).all() songs = [(song, get_rating(rating)) for song, rating in songs] return render_template("songs/search_ajax.html", songs=songs)
def _get_unescaped_parameter(parameter, default=''): return unescape(request.args.get(parameter, default, str))
def test_unescape(): assert utils.unescape("<ä>") == "<ä>"
def test_unescape(): assert utils.unescape('<ä>') == u'<ä>'
def unescape_repl(m): if m.group(1): return "```" + unescape(m.group(1)) + "```"
def action(): response = request.json text = beautify_text(response['text']) return jsonify(beauty_text=unescape(text))
def test_unescape(self): self.assert_equal(utils.unescape('<ä>'), u'<ä>')
def test_unescape(): assert utils.unescape("<ä>") == u"<ä>"