def lists_edit(name=None): if 'username' not in session: return goto_login(fname(), fparms()) action = 'delete' if request.args.get('action', request.form.get('action')) == 'delete' else 'add' item = request.args.get('item', request.form.get('item')) if not name or not action or not item: return redirect(url_for('lists')) listname = getattr(userlists, name).printedname if request.method == 'POST': if name == 'whitelist': restartstring = '<span class="halflink" onclick="document.getElementById(\'restartform\').submit();">Restart</span> the server to apply your changes.' else: restartstring = '' if action == 'add': if getattr(userlists, name).add(item): flash('<i>%s</i> added to %s. %s' % (Markup.escape(item), listname, restartstring), 'success') else: flash('<i>%s</i> is already in %s.' % (Markup.escape(item), listname), 'info') elif action == 'delete': if getattr(userlists, name).remove(item): flash('<i>%s</i> deleted from %s. %s' % (Markup.escape(item), listname, restartstring), 'success') else: flash('<i>%s</i> is not in %s.' % (Markup.escape(item), listname), 'info') returnpage = request.form.get('returnpage', 'lists') return redirect(url_for(returnpage, username=item)) return render_template('lists_delete.html', navigation=get_navi('lists'), name=name, action=action, item=item, listname=listname)
def format_links(text): url_match = re.compile(r"""( (?:https?://|www\.) # start with http:// or www. (?:[^\s<>"'/?#]+) # domain doesn't have these characters (?:[^\s<>"']+) # post-domain part of URL doesn't have these characters [^\s<>,"'\.] # no dot at end )""", re.X) matched_urls = url_match.findall(text) if matched_urls: link = '<a href="{0}" class="break-link" rel="external">{0}</a>' plaintext_link = '<span class="break-link">{0}</span>' text_array = url_match.split(text) formatted_text_array = [] for partial_text in text_array: if partial_text in matched_urls: if partial_text.startswith('www'): url = plaintext_link.format(Markup.escape(partial_text)) else: url = link.format(Markup.escape(partial_text)) formatted_text_array.append(url) else: partial_text = Markup.escape(partial_text) formatted_text_array.append(partial_text) formatted_text = Markup(''.join(formatted_text_array)) return formatted_text else: return text
def get_module_info(module_name): result = [] module = __import__(module_name.split(".")[0]) for m in module_name.split(".")[1:]: module = getattr(module, m) for attr in dir(module): at = {} at['name'] = attr at['type'] = Markup.escape( str(type(getattr(module, attr))).split("'")[1]) at['doc'] = "" at['is_func'] = False at['is_module'] = False at['value'] = "test faild" if hasattr(getattr(module, attr), '__call__'): at['is_func'] = True if attr not in ["exit", "abort"]: try: at['value'] = Markup.escape(getattr(module, attr)()) except: pass if hasattr(getattr(module, attr), '__doc__'): at['doc'] = getattr(module, attr).__doc__ else: try: at['value'] = Markup.escape(getattr(module, attr)) except: pass if isinstance(getattr(module, attr), types.ModuleType): at['is_module'] = True result.append(at) return result
def bizutage(): lien = request.values["lien"] titre = Markup.escape(request.values["titre"]) desc = Markup.escape(request.values["desc"]) categorie = Markup.escape(request.values["categories"]) tagsList = request.values["tags"].split(';') tags = [] for i in tagsList: i.strip() i = Markup.escape(i) if i not in tags: tags.append(i) nouvLien = { "titre": titre, "url": lien, "desc": desc, "categorie": categorie, "tags": tags } ret = manip.ajoutLienJson(nouvLien) if ret is Status.BON: #generateurHml.majTousFichiers() return render_template("ajout.html", reussi=ret.value) else: return render_template("ajout.html", erreur=ret.value)
def pretty(value): if isinstance(value, dict): page = markup.page() page.ul(_class='dict') for k, v in value.items(): if isinstance(v, list) and v: pretty_value = Markup.escape(', '.join(v)) elif isinstance(v, dict) and v: subul = markup.page() subul.ul(_class='subdict') for subk, subv in v.items(): subul.li() subul.span('%s: ' % subk) subul.span(Markup.escape(subv)) subul.li.close() subul.ul.close() pretty_value = subul() elif v: pretty_value = Markup.escape(v) else: continue page.li() page.span('%s:' % k.capitalize().replace('_', ' ')) page.span(pretty_value) page.li.close() page.ul.close() return page() elif isinstance(value, list): return Markup.escape(', '.join(value)) else: page = markup.page() page.span(Markup.escape(value), _class='simple') return page()
def quote(args=""): """Get stock quote.""" if request.method == "GET": return render_template("getStockQuote.html", symbol=args) symbol = request.form.get("symbol") if not symbol: return messageAlert(Markup.escape("Stock symbol is required"), 403, "error.png", "quote") stockDict = lookup(symbol) if not stockDict: message = "You have requested an invalid stock symbol " + symbol + ".<br>Please try again." return messageAlert(Markup.escape(message), 403, "error.png", "quote") stockSymbol = stockDict["symbol"] stockCompanyName = stockDict["companyName"] stockLatestPrice = stockDict["latestPrice"] title = "Quote: Stock Symbol " + stockSymbol return render_template('displayStockQuote.html', symbol=stockSymbol, stockSymbol=stockSymbol, stockCompanyName=stockCompanyName, stockLatestPrice=stockLatestPrice, title=title)
def convert(): if "text" not in request.form: return "<html><head><title>heat2dot</title></head><body>Text not found</body></html>", 403 infile = "/tmp/inheat2dot_" + str(time.time()) dotfile = "/tmp/inheat2dot_" + str(time.time()) + ".dot" with open(infile, "w") as intextfile: intextfile.write(request.form["text"]) error_messages = None svg = None try: h2d_out = subprocess.run( ["cat " + infile + " | ./heat2dot.py > " + dotfile], shell=True, stderr=subprocess.PIPE) error_messages = h2d_out.stderr.decode("UTF-8") if h2d_out.returncode != 0: return Markup( "<html><head><title>heat2dot</title></head><body>Failure<br/><pre>" ) + Markup.escape(h2d_out.stderr.decode("UTF-8")) + Markup( "</pre></body></html>") else: dot_out = subprocess.run(["dot -Tsvg " + dotfile], shell=True, stdout=subprocess.PIPE) svg = dot_out.stdout.decode("UTF-8") except Exception as e: print(e) finally: try: os.remove(infile) except: pass try: os.remove(dotfile) except: pass if error_messages != None and svg == None: return Markup( "<html><head><title>heat2dot</title></head><body>Failure<br/><pre>" ) + Markup.escape(error_messages) + Markup("</pre></body></html>") elif svg != None: if error_messages == None: return ( Markup("<html><head><title>heat2dot</title></head><body>") + Markup(svg) + Markup("</body></html>")) else: return ( Markup("<html><head><title>heat2dot</title></head><body>") + Markup(svg) + Markup("<br/><pre>") + Markup.escape(error_messages) + Markup("</pre></body></html>")) else: return "<html><head><title>heat2dot</title></head><body>Something went horribly wrong.</body></html>"
def _format_attrs(attrs, escape_attrs=True): out = [] for name, value in sorted(attrs.items()): if escape_attrs: name = Markup.escape(name) value = Markup.escape(value) out.append(' {name}="{value}"'.format(name=name, value=value)) return ''.join(out)
def _build_notice_setting_data(result, setting): """Build notice setting data. :param result: :param setting: """ result['hide_the_rest'] = Markup.escape(setting.get('setting')) result['read_more'] = Markup.escape(setting.get('read_more'))
def editTask(id): if request.method == "PUT": title = Markup.escape(request.form["title"]) desc = Markup.escape(request.form["description"]) priority = request.form["priority"] executeQuery( "UPDATE tasks SET titleTask = '{0}', descriptionTask = '{1}', valueTask = '{2}' WHERE idTask = '{3}'" .format(title, desc, priority, id)) return jsonify(message="ta bien", code=0)
def aabvfd(name=None): app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' Markup.escape('<blink>hacker</blink>') Markup('<em>Marked up</em> » HTML').striptags() return ""
def safe_non_valid_input_error(user_input,field_name): r""" Returns a formatted error message where all non-fixed parameters (in particular user input) is escaped. """ msg = Markup("Error: <span style='color:black'>")+Markup.escape(user_input) msg += Markup("</span>") msg += Markup(" is not a valid input for <span style='color:black'>") msg += Markup.escape(field_name)+Markup("</span>") return msg
def _build_new_arrivals_setting_data(result, setting): """Build New Arrivals setting data. :param result: :param setting: """ result['new_dates'] = Markup.escape( setting.get('new_dates')) or config.WEKO_GRIDLAYOUT_DEFAULT_NEW_DATE result['display_result'] = Markup.escape(setting.get( 'display_result')) or config.WEKO_GRIDLAYOUT_DEFAULT_DISPLAY_RESULT result['rss_feed'] = setting.get('rss_feed') or False
def createNewTask(id): if request.method == "POST": title = Markup.escape(request.form["title"]) desc = Markup.escape(request.form["description"]) priority = request.form["priority"] executeQuery( "INSERT INTO tasks (idUserFk, titleTask, descriptionTask, valueTask) VALUES ('{0}', '{1}', '{2}', '{3}')" .format(id, title, desc, priority)) return jsonify(message="Ta bien")
def safe_non_valid_input_error(user_input, field_name): r""" Returns a formatted error message where all non-fixed parameters (in particular user input) is escaped. """ msg = Markup("Error: <span style='color:black'>") + Markup.escape( user_input) msg += Markup("</span>") msg += Markup(" is not a valid input for <span style='color:black'>") msg += Markup.escape(field_name) + Markup("</span>") return msg
def _build_access_counter_setting_data(result, setting): """Build Access Counter setting data. :param result: :param setting: """ result['access_counter'] = Markup.escape( setting.get('access_counter')) or '0' result['following_message'] = Markup.escape( setting.get('following_message')) or '' result['other_message'] = Markup.escape(setting.get('other_message')) or '' result['preceding_message'] = Markup.escape( setting.get('preceding_message')) or ''
def add_new_language(): user = fetch_id_from_userid(current_user.id) bcp = request.args.get('bcp', None) bcp = str(Markup.escape(bcp)) iso = request.args.get('iso', None) iso = str(Markup.escape(iso)) name = request.args.get('name', None) name = str(Markup.escape(name)) if bcp and name: dbinsert = insert_new_language(bcp, iso, name, user) return jsonify(result=dbinsert) else: return jsonify(result=False)
def td_contents(self, item, attr_list, btn_class=None): if btn_class: return '<form method="post" action="{url}">'\ '<button class="{btn_class}" type="submit">{text}</button>'\ '</form>'.format( url=self.url(item), text=Markup.escape(self.text(item, attr_list)), btn_class=btn_class) else: return '<form method="post" action="{url}">'\ '<button type="submit">{text}</button>'\ '</form>'.format( url=self.url(item), text=Markup.escape(self.text(item, attr_list)))
def profile_edit(user_id=-1): """ изменение профиля пользователя """ user = current_user if session and session['logged_in']: # если юзер залогинен if user_id >= 0: if 'super_admin' in user.roles: # если запрошен user_id и если есть роль admin user = load_user(user_id) else: return redirect(url_for('users.profile')) # возвращаем форму изменения профайла if request.method == 'GET': return render_template("users/profile_edit.html", user=user) # все остальное это POST запрос, т.е. submit на форму изменения профиля # валидируем форму valid, error = profile_edit_validate(request.form, user) if not valid: return render_template("users/profile_edit.html", error=error, user=user) name = "" if 'name' in request.form: name = Markup.escape(request.form['name']) surname = "" if 'surname' in request.form: surname = Markup.escape(request.form['surname']) if 'new_password' in request.form: # если админ редактирует профиль и оставляет пароль пустым, # то не меняем этот пароль if 'super_admin' not in current_user.roles: user.set_password(request.form['new_password']) else: # если админ редактирует запись, и вбивает пользователю # новый пароль, то устанавливаем его if request.form['old_password'] == '': user.set_password(request.form['new_password']) # изменяем пользователя user['surname'] = surname user['name'] = name user.save() return redirect(request.args.get('next') or url_for('users.profile'))
def post_item(name=None): if 'logged_in' in session: uid = session['user_id'] g.db = connect_db(app.config['USER_DB']) droits = get_droits(uid) g.db.close() if droits['adm'] == 1: if (request.method == 'POST'): g.db = connect_db(app.config['USER_DB']) cur = g.db.execute('select id from items where nam like ?', [request.form['nam']]) entries = [dict(name=row[0]) for row in cur.fetchall()] if len(entries) == 0: g.db.execute('insert into items (nam, price, recette, use_in, tooltip, tooltip_untouch, des, categorie) values (?, ?, ?, ?, ?, ?, ?, ?)', [request.form['nam'], request.form['prix'], request.form['recette'], request.form['use_in'], markdown.markdown(Markup.escape(request.form['tooltip'])), request.form['tooltip'], request.form['des'], request.form['categorie']]) g.db.commit() else: g.db.execute('update items set price = ?, recette = ?, use_in = ?, tooltip = ?, tooltip_untouch = ?, des = ?, categorie = ? where nam like ?', [request.form['prix'], request.form['recette'], request.form['use_in'], markdown.markdown(Markup.escape(request.form['tooltip'])), request.form['tooltip'], request.form['categorie'], request.form['des']]) g.db.commit() g.db.close() return redirect(url_for('item', name = request.form['nam'])) else: if name == None: return render_template('post_item.html') else: g.db = connect_db(app.config['USER_DB']) cur = g.db.execute('select * from items where nam like ?', [name]) entries = [dict(id_item=row[0], nam=row[1], prix=row[2], recette=row[3], use_in=row[4], tooltip=row[6], des=row[7], cat=row[8]) for row in cur.fetchall()] g.db.close() if (len(entries) == 0): return render_template('post_item.html') else: return render_template('post_item.html', entries = entries) return redirect(url_for('default'))
def deleteUser(id): with app.app_context(): db = get_db() user = db.getUserByID(id) if user is not None: db.deleteUser(id) db.commit() flash('{0} {1} has been succesfully deleted.' .format(Markup.escape(user['name']), Markup.escape(user['surname'])), 'success') else: flash('Unable to delete user id {0}: User does not exist.'.format(id), 'error') return redirect(url_for('index'))
def handle_starttag(self, tag, attrs): self.container.append("<%s>" % tag) attrs_string = '' if attrs: for attr in attrs: str = '%s="%s" ' % (attr[0], attr[1]) attrs_string = attrs_string + str if attrs_string and attrs_string[-1] == " ": attrs_string = attrs_string[:-1] tag_string = Markup.escape('<%s %s>' % (tag, attrs_string)) else: tag_string = Markup.escape('<%s>' % tag) self.div_wrap = self.div_wrap + Markup('<span class="slack-%s">' % tag) + \ tag_string + Markup('</span>')
def signup(): """ регистрация пользователя """ error = None # проверяем доступна ли регистрация if 'REGISTRATION_ENABLED' in current_app.config: if current_app.config['REGISTRATION_ENABLED'] == False: # если регистрация отключена, и есть пользователи в БД, # то показываем форму логина if get_users_count(): return redirect(url_for('users.signin')) # возвращаем форму логина if request.method == 'GET': return render_template("users/signup.html") # остальное, метод POST, т.е. начинаем регистрацию # валидируем форму valid, error = signup_validate(request.form) if not valid: return render_template("users/signup.html", error=error) surname = None if 'surname' in request.form: surname = Markup.escape(request.form['surname']) name = None if 'name' in request.form: name = Markup.escape(request.form['name']) # регистрируем нового пользователя user = User(user_name=Markup.escape(request.form['username']), name=name, surname=surname, password='', email=Markup.escape(request.form['email']), enabled=True) user.set_password(request.form['password']) # если это первый созданный пользователь, то он # автоматом получает права администратора if not get_users_count(): user.roles = ['super_admin'] user.save() return redirect(url_for('users.signin'))
def add_resource(): form = forms.ResourceForm(request.form) if request.method == "POST" and form.validate(): # Escape user input using Markup title = Markup.escape(form.title.data) link = urllib.parse.unquote(Markup.escape(form.link.data)) note = Markup.escape(form.note.data) timestamp = datetime.datetime.fromtimestamp( time()).strftime("%Y-%m-%d %H:%M:%S") tags = Markup.escape(form.tags.data) # If not empty format for proper insertion into postgresql if tags: tags = "{" + str(tags).lower() + "}" else: tags = None user_id = session["user_id"] cur = conn.cursor() cur.execute( ("""INSERT INTO resources(user_id,title,link,note,tags,date_of_posting) VALUES (%s,%s,%s,%s,%s,%s)""" ), (user_id, title, link, note, tags, timestamp), ) cur.close() conn.commit() flash("Resource created successfully.", "success") return redirect(url_for("resources")) else: user_id = session["user_id"] cur = conn.cursor() cur.execute( ("""SELECT DISTINCT unnest(tags) FROM resources WHERE user_id = %s""" ), (user_id, ), ) tags_raw = cur.fetchall() # 'Unpack' tags_raw into one array all_tags = [] for tag_arr in tags_raw: all_tags.append(tag_arr[0]) cur.close() return render_template("add_resource.html", form=form, tags=all_tags)
def inventory(): db = get_db() form=InventoryAddForm() if form.validate_on_submit(): item_name = Markup.escape(request.form['item']) # escape the search term before broadcasting it! price = Markup.escape(request.form['price']) db.execute("insert into items (itm_name, usr, prc) values(?, ?, ?);",[item_name,g.user.id, price]) db.commit() cur = db.execute("select itm_id, itm_name, prc from items where usr=?",[g.user.id]) items = cur.fetchall() return render_template("inventory.html", user=g.user, items=items, form=form)
def login(): if "user" in session: return redirect("index") if request.method == "POST": # Get username and password and escape to avoid injection username = Markup.escape(request.form["username"]) password = Markup.escape(request.form["password"]) # Check if username and password are not empty if username == "" or password == "": return render_template( "error.html", message="Username and password cannot be blank.", ) # check if the user exists? if (db.execute( "SELECT username FROM users WHERE username = :username", { "username": username }, ).rowcount == 0): return render_template( "error.html", message="Username or password incorrect, have you registered?", ) # Check if the password matches? ## Get hash from DB correct_psw = db.execute( "SELECT psw_hash FROM users WHERE username = :username", { "username": username }, ).fetchone() ## Compare with the hash of the given password if bcrypt.check_password_hash(correct_psw[0], password): # Add session to user session["user"] = username # Return successful page and redirect to main page redirect_url = url_for("index") return render_template("success.html", user=session["user"], redirect_url=redirect_url) return render_template( "error.html", message="Username or password incorrect, have you registered?") else: return render_template("login.html")
def register(): # If logged, no need to register =] if "user" in session: return redirect("index") # IF GET REQUEST: Show register page. if request.method == "GET": return render_template("register.html") # IF POST REQUEST: if request.method == "POST": # Check if all fields are completed username = Markup.escape(request.form.get("username")) password = Markup.escape(request.form.get("password")) nickname = Markup.escape(request.form.get("nickname")) if username == None or password == None or nickname == None: return render_template( "error.html", message= "You need to type a valid username, password and nickname.", ) # Check if username is taken if (db.execute( "SELECT username FROM users WHERE username = :username", { "username": username }, ).rowcount != 0): return render_template("error.html", message="Username already exists.") # Create a password hash psw_hash = bcrypt.generate_password_hash(password).decode("utf-8") # Write user to database db.execute( "INSERT INTO users(username, psw_hash, nickname) VALUES (:username, :psw_hash, :nickname);", { "username": username, "psw_hash": psw_hash, "nickname": nickname }, ) db.commit() # Return successful page and redirect to main page session["user"] = username redirect_url = url_for("index") return render_template("success.html", user=username, redirect_url=redirect_url)
def get_bitcoin_rate(currency): valute = currency.upper() resOk, rate, msg = get_from_http("https://bitpay.com/api/rates/{}".format(valute)) if resOk: return render_template('bitcoin_rate.html', name=rate['name'], code=rate['code'], rate=rate['rate']) else: return Markup.escape(msg)
def blockcode(self, text, lang): if not lang: return '\n<pre><code>%s</code></pre>\n' % Markup.escape(text) lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True) formatter = pygments.formatters.HtmlFormatter() rendered = pygments.highlight(text, lexer, formatter) return rendered
def callback(): if request.values.get('error'): return Markup.escape(request.values['error']) discord = discord_api.make_session(state=session.get('oauth2_state')) token = discord.fetch_token( app.config['DISCORD_API_URL'] + discord_api.TOKEN_PATH, client_secret=app.config['OAUTH2_CLIENT_SECRET'], authorization_response=request.url) discord_api.token_updater(token) info = discord_api.get_me() if info == None: flash("Error: Could not authenticate with discord.") return redirect(url_for('home')) userinfo = user.get_user_document(info['id']) if userinfo == None: user.register(info) flash("You have been registered.") else: flash("You have been logged in.") user._refresh_points(userinfo, force_update=True) return redirect(url_for('home'))
def create_new_room(r, room_id, request): max_participants= request.form["participants"] try: max_participants= int(max_participants) except Exception as e: print("Exception: main.create_new_room:",e) max_participants= '' room_info={"room_kind":request.form["room_kind"], "room_title":Markup.escape(request.form["title"]), "max_participants":max_participants, "cur_participants":0, "open_time":str(time.time())} room_data={"room_seq":room_id, "room_title": room_info["room_title"], "room_kind": room_info["room_kind"], "open_time": room_info["open_time"], "max_participants": room_info["max_participants"], "voted_members":[], "out_dated":False} g.MongoDao.insert_room(room_data) if g.MongoDao.add_room_to_tag("tag_me", room_id, 0, 0)["updatedExisting"]== False: g.MongoDao.insert_tag("tag_me", room_id, 0, 0) if request.form["room_kind"]== "versus": room_data={"room_seq":room_id+"_supportA", "room_title": "", "room_kind": "support", "open_time": room_info["open_time"], "max_participants": room_info["max_participants"], "voted_members":[], "out_dated":False} g.MongoDao.insert_room(room_data) room_data={"room_seq":room_id+"_supportB", "room_title": "", "room_kind": "support", "open_time": room_info["open_time"], "max_participants": room_info["max_participants"], "voted_members":[], "out_dated":False} g.MongoDao.insert_room(room_data)
def getSafeTweet(tweet): safeTweet = str(Markup.escape(tweet)) injectedTweet = '' # Inject <a href> for hashtags HASH_TAG_STATE = 1 IGNORE_NEXT_STATE = 2 state = 0 hashTagText = '' for c in safeTweet: if state == HASH_TAG_STATE: if (c < 'A' or c > 'Z') and (c < 'a' or c > 'z') and (c < '0' or c > '9'): injectedTweet += '<a href="/hashtag/%s">#%s</a>%s' % (hashTagText.lower(), hashTagText, c) state = 0 else: hashTagText += c elif state == IGNORE_NEXT_STATE: injectedTweet += c state = 0 else: if c == '#': hashTagText = '' state = HASH_TAG_STATE elif c == '&': injectedTweet += c state = IGNORE_NEXT_STATE else: injectedTweet += c # Close hash if still in hashTagState if state == HASH_TAG_STATE: injectedTweet += '<a href="/hashtag/%s">#%s</a>' % (hashTagText.lower(), hashTagText) state = 0 return Markup(injectedTweet)
def api_book(isbn): """List details about a single book.""" isbn = Markup.escape(isbn) # check if book exist in database book_db = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn", { "isbn": isbn }).fetchone() if book_db == None: return jsonify({"error": "Invalid isbn or not in our database"}), 404 # Get detail from Goodreads res = requests.get( "https://www.goodreads.com/book/review_counts.json", params={ "key": os.getenv("GOODREADS_API"), "isbns": isbn }, ) if res.status_code != 200: raise Exception("ERROR: API request unsuccessful.") data = res.json() book = data["books"][0] # Print results return jsonify({ "title": book_db.title, "author": book_db.author, "year": book_db.year, "isbn": book_db.isbn, "review_count": book["work_ratings_count"], "average_score": book["average_rating"], })
def book(isbn): """List details about a single book.""" isbn = Markup.escape(isbn) # check if book exist in database book_db = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn", { "isbn": isbn }).fetchone() if book_db == None: return render_template("error.html", error="ISBN invalid or not in our Database.") # Get detail from Goodreads res = requests.get( "https://www.goodreads.com/book/review_counts.json", params={ "key": os.getenv("GOODREADS_API"), "isbns": isbn }, ) if res.status_code != 200: return render_template("error.html", error="Not found on our API.") data = res.json() book = data["books"][0] # Get the reviews for the book. book_reviews = db.execute( "SELECT review.*, users.nickname FROM review JOIN users ON review.user_id = users.id WHERE book_id = :book_id", { "book_id": book_db.id }, ).fetchall() # Get my own review user = session.get("user") my_review = db.execute( "SELECT * FROM review WHERE (book_id = :book_id) AND user_id = (SELECT id from users WHERE username LIKE :user)", { "book_id": book_db.id, "user": user }, ).fetchone() if my_review is not None: # Print results return render_template( "book.html", book=book, book_db=book_db, book_reviews=book_reviews, my_review=my_review, ) else: return render_template( "book.html", book=book, book_db=book_db, book_reviews=book_reviews, my_review=None, )
def description_html(self): if self.description is None: return Markup("") return Markup( str(Markup.escape(self.description)).replace("\r\n", "</br>").replace( " ", " "))
def on_send_message(self, message): if current_user.is_authenticated: safe_message = Markup.escape(message) if len(safe_message) > self.max_length: emit("flash", ("Message is too long!", "ERROR"), namespace="/", room=request.sid) return emit("process_message", (str(current_user.username), str(safe_message)), broadcast=True)
def comment_id(): user = fetch_id_from_userid(current_user.id) ili_id = request.args.get('ili_id', None) comment = request.args.get('comment', None) comment = str(Markup.escape(comment)) dbinsert = comment_ili_id(ili_id, comment, user) return jsonify(result=dbinsert)
def comment(request): if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): cdata = form.cleaned_data body = cdata['body'] post_id = int(cdata['post_id']) reco_id = cdata['reco_id'] safe_body = unicode(Markup.escape(body)) encoded_body = text_handle(safe_body, 'comment') post = Post.objects.get(id=post_id) try: reco = Comment.objects.get(id=reco_id) except: reco = None new_comment = Comment(post=post, user=request.user, reco=reco, body=safe_body, encoded_body=encoded_body, date=get_time(), is_active=True) new_comment.save() # inform @ re.sub(r"href='/u/\d+'", lambda x: inform(x.group(0)[9:-1], 'comment', new_comment.id), encoded_body) return HttpResponseRedirect(u'/post/'+unicode(post.id)+'#comment_area')
def details(objectid): """ Displays entry details. """ from flask import Markup from pprint import pformat of = "hd" bwobject = BibWorkflowObject.query.filter( BibWorkflowObject.id == objectid ).first() workflow_object = Workflow.query.filter( Workflow.uuid == bwobject.id_workflow ).first() workflow_tasks = get_workflow_definition(workflow_object.name) formatted_data = bwobject.get_formatted_data(of) if isinstance(formatted_data, dict): formatted_data = pformat(formatted_data) if of and of in ("xm", "xml", "marcxml"): data = Markup.escape(formatted_data) else: data = formatted_data engine_log = BibWorkflowEngineLog.query.filter( BibWorkflowEngineLog.id_object == workflow_object.uuid ) return dict(entry=bwobject, log=engine_log, data_preview=data, workflow_tasks=workflow_tasks)
def addComment(self, com): fullCom = Markup(u'[comment: [' + unicode(date.today()) + u']> ') + Markup.escape(com) + Markup(u']') Comment.create(idTask = self, content = unicode(fullCom[1:-1])) self.updateFile() self.parentPage.book.CommitIfNeeded() self.updatePregenNeeded = True self.save()
def quotedpost(self, forceurl=False, cutlines=False): escaped=Markup.escape(self.post) reg=re.compile(r">>\d+") ess=unicode(escaped) for m in set(reg.findall(ess)): qn=m.replace(">>","") qint=int(qn) np=Ipost.query.filter_by(id=qint) if np.count()!=0: if np.first().ithread==self.ithread and forceurl==False: ess=ess.replace(m, "<a href='#%s'>%s</a>"%(qn,m)) else: ess=ess.replace(m, "<a href='/thread/%d#%s'>%s</a>"%(np.first().ithread.id, qn, m)) ##idezes u=[] for s in ess.split("\n"): if s.startswith(">"): u.append("<span style='color: green'>"+s+"</span>") else: u.append(s) #elolnezeti sorok levagasa if cutlines and len(u)>app.config['PREVIEW_LINES']: visible=u[0:app.config['PREVIEW_LINES']] u=visible visible.append("<br><small class='threadinfo'>Comment too long</small>") ess="\n".join(u) return Markup(ess.replace("\n", "<br>"))
def testFunction(domain_url): try: address = str(dns.resolver.query(domain_url)[0]) status = 0 briefing = "Could locate domain " + domain_url + " at " + address + "!" message = briefing return (status, briefing, message, None) except dns.resolver.NXDOMAIN: status = 1 briefing = "Could not locate " + domain_url + "!" message = "We were unable to find your domain " + domain_url + "." return (status, briefing, message, None) except Exception, e: status = 2 briefing = "A problem happened while attempting to locate your domain " + domain_url + "!" message = "Something odd happened while we were trying to locate your domain " + domain_url + "!" e_type, e_value, e_trace = sys.exc_info() e_type = Markup.escape(str(type(e))).__str__() # message += "<br/>This is the exception we got: {"+str(e)+"}" message += "<br/>This is the exception we got: {type:%s, value:%s}" % (e_type, e_value) message += "<br/>It is probably a temporary issue with domain " + domain_url + "." message += "<br/>But it could also be a bug in our Inspector. Let us know at <a href='https://github.com/buddycloud/buddycloud-tests-framework/issues'>our issue tracker</a> if you think so." return (status, briefing, message, None)
def upload(): # Get the name of the uploaded file file = request.files['file'] # 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(app.config['UPLOAD_FOLDER'], filename)) try: adaptive_resize(os.path.join(app.config['UPLOAD_FOLDER'], filename)) except: pass # Redirect the user to the uploaded_file route, whicuploadh # will basicaly show on the browser the uploaded file cmd = "./darknet yolo test cfg/cpuNet6.cfg cpuNet6.weights %s%s" % (app.config['UPLOAD_FOLDER'], filename) try: stdout_result = subprocess.check_output(cmd, shell=True) info = stdout_result.split(':')[1:] info = ''.join(info) text = "" for line in info.split('\n'): text += Markup.escape(line) + Markup('<br />') return render_template('result.html', filename=os.path.join(app.config['OUTPUT_FOLDER'], os.path.basename(filename).split('.')[0] + '.png'), result_text=text) except: return render_template('result.html', filename=os.path.join(app.config['UPLOAD_FOLDER'], filename), result_text="Unexpected error occured, terminate detection.") #return redirect(url_for('uploaded_file', filename=filename)) return "Invalid file or format"
def assemble_chat(self, chatter, message): chat_message={} chat_message["proto_type"]= "chat_message" chat_message["sender"]= chatter.get_name() chat_message["message"]= Markup.escape(message["message"]).replace("\n","<br />") chat_message["chat_seq"]= self.chat_seq self.chat_seq+= 1 return chat_message
def xss_sanitised(): param = request.args.get('param', 'not set') param = Markup.escape(param) html = open('templates/xss.html').read() response = make_response(html.replace('{{ param }}', param)) return response
def add_spell_base(name): g.db.execute('insert into spells (name_hero, nam, tooltip, tooltip_untouch, pos) values (?, ?, ?, ?, ?)', [name, request.form['nam_skill'], markdown.markdown(Markup.escape(request.form['tooltip'])), request.form['tooltip'], request.form['pos_skill']]) g.db.commit() return
def add_new_project(): user = fetch_id_from_userid(current_user.id) proj = request.args.get('proj_code', None) proj = str(Markup.escape(proj)) if user and proj: dbinsert = insert_new_project(proj, user) return jsonify(result=dbinsert) else: return jsonify(result=False)
def update_spell_base(name): g.db.execute('update spells set nam = ?, tooltip = ?, tooltip_untouch = ?, pos = ? where id = ?', [request.form['nam_skill'], markdown.markdown(Markup.escape(request.form['tooltip'])), request.form['tooltip'], request.form['pos_skill'], request.form['id']]) g.db.commit() return
def update_news(id_news): g.db = connect_db(app.config['USER_DB']) g.db.execute('update news set title = ?, tag = ?, content_untouch = ?, content_markup = ?, date_last_modif = ? where id = ?', [request.form['titre'], request.form['tag'], request.form['news'], markdown.markdown(Markup.escape(request.form['news'])), datetime.today(), id_news]) g.db.commit()
def wishlist_search_delete(term): term = Markup.escape(term) # escape db = get_db() db.execute("delete from wishlists where usr=? and wishstr=?",[g.user.id, term]) db.commit() return redirect(url_for('wishlist_search'))
def add_news(): g.db = connect_db(app.config['USER_DB']) g.db.execute('insert into news (title, autor, tag, content_untouch, content_markup, date_create, date_last_modif) values (?, ?, ?, ?, ?, ?, ?)', [request.form['titre'], session['user_login'], request.form['tag'], request.form['news'], markdown.markdown(Markup.escape(request.form['news'])), datetime.today(), datetime.today()]) g.db.commit()
def debug_str(print_me): """Prints out an HTML escaped string in code and pre tags.""" if isinstance(print_me, (list, tuple)): print_me = "\n".join([str(x) for x in print_me]) if isinstance(print_me, dict): print_me = "{\n\t" + "\n\t".join([str(x) + ": " + str(y) for x, y in print_me.items()]) + "\n}" escaped = Markup.escape(str(print_me)) return """<code class="debug-str"><pre>{0}</pre></code>""".format(escaped)