def ax_repr(o): res = [] if isinstance(o, JobWithFile): link = '/job/' + bottle.html_escape(o.job) res.append('JobWithFile(<a href="%s">job=' % (link,)) res.append(ax_repr(o.job)) name = bottle.html_escape(o.name) if o.sliced: name += '.0' res.append('</a>, <a href="%s/%s">name=' % (link, name,)) res.append(ax_repr(o.name)) res.append('</a>, sliced=%s, extra=%s' % (ax_repr(o.sliced), ax_repr(o.extra),)) res.append(')') elif isinstance(o, (list, tuple)): bra, ket = ('[', ']',) if isinstance(o, list) else ('(', ')',) res.append(bra) comma = '' for v in o: res.append(comma) res.append(ax_repr(v)) comma = ', ' res.append(ket) elif isinstance(o, dict): res.append('{') comma = '' for k, v in o.items(): res.append(comma) res.append(ax_repr(k)) res.append(': ') res.append(ax_repr(v)) comma = ', ' res.append('}') else: res.append(bottle.html_escape(repr(o))) return ''.join(res)
def form_errors(errors): """ Renders a form error. This function renders a standardized markup for form errors in your template. Please see notes for :py:func:`~bottle_utils.html.field_error` for the reasoning behind this helper function. Input dictionary must contain a special key '_' which is treated as key for form-wide errors that are not specific to any field. The value can either be a single string or an iterable of strings. Errors are always rendered as unordered list with each error message as list item, even when there is only one error. The list items always have the 'form-error' class, and the unordered list has the 'form-errors' class. For example:: >>> form_errors({'_': 'Ouch!'}) '<ul class="form-errors"><li class="form-error">Ouch!</li></ul>' >>> form_errors({'_': ['Ouf!', 'Pain!']}) '<ul class="form-errors"><li class="form-error">Ouf!</li><li clas...' :param errors: dictionary or dictionary-like object containing field name-error mappings """ try: return UL(LI(html_escape(errors['_']), _class=FERR_ONE_CLS), _class=FERR_CLS) except KeyError: return '' except TypeError: return P(SPAN(html_escape(errors['_']), _class=FERR_ONE_CLS), _class=FERR_CLS)
def preview(self, args): id = args['id'] item_value = ItemValue(id=id) item = self.store.get_item(id) lang = args.get('lang') image = self.get_image_for_item(item_value, item, lang) desc = lngfb(item.get('descriptions'), lang) if desc: desc = html_escape(desc) # if the description is really too short if not desc or not ' ' in desc: desc = autodescribe(id, lang) args = { 'id': id, 'label': html_escape(lngfb(item.get('labels'), lang) or id), 'description': desc, 'image': image, 'url': 'https://www.wikidata.org/entity/' + id, 'width': preview_width, 'height': preview_height, } return self.preview_template.render(**args)
def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast((yield from self._handle(environ))) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(_e())), html_escape(format_exc())) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info()) return [tob(err)]
def __call__(self, environ, start_response): try: return self.app(environ, start_response) except (Exception, ExceptionInBackend) as e: template_vars = {} if "bottle.request.post" in environ: environ["bottle.request.post"] = dict( filter_sensitive_params(environ["bottle.request.post"], self.sensitive_params) ) # update environ environ["foris.version"] = current_state.foris_version environ["foris.language"] = current_state.language environ["foris.backend"] = current_state.backend template_vars["environ"] = html_escape(pformat(environ)) # Handles backend exceptions in same manner as if isinstance(e, ExceptionInBackend): error = "Remote Exception: %s" % e.remote_description extra = "<h3>Remote request</h3><pre>%s</pre>" % html_escape(json.dumps(e.query)) trace = e.remote_stacktrace else: error = repr(_e()) trace = format_exc() extra = "" template_vars["error"] = html_escape(error) template_vars["trace"] = html_escape(trace) template_vars["extra"] = extra template_vars["dump_file"] = "%s/%s" % (get_root(), self.dump_file) environ["wsgi.errors"].write(format_exc()) headers = [("Content-Type", "text/html; charset=UTF-8")] err = ERROR_TEMPLATE % template_vars start_response("500 INTERNAL SERVER ERROR", headers) with open("/tmp/%s" % self.dump_file, "wb") as f: f.write(err.encode("UTF-8")) return [tob(err)]
def ax_link(v): if isinstance(v, tuple): return '(%s)' % (', '.join(ax_link(vv) for vv in v), ) elif isinstance(v, list): return '[%s]' % (', '.join(ax_link(vv) for vv in v), ) elif v: ev = bottle.html_escape(v) if isinstance(v, Dataset): job = bottle.html_escape(v.job) name = bottle.html_escape(v.name) return '<a href="/job/%s">%s</a>/<a href="/dataset/%s">%s</a>' % ( job, job, ev, name, ) elif isinstance(v, Job): return '<a href="/job/%s">%s</a>' % ( ev, ev, ) else: return ev else: return ''
def render_html(self, react_node, **kwargs): kwargs = self.calc_render_html_kwargs(kwargs) template = kwargs.get('template', 'bottlereact') render_server = kwargs.get('render_server', self._render_server) react_js = react_node.to_javascript() deps = self._build_dep_list(react_node.get_js_files()) classes = _make_json_string_browser_safe( json.dumps(list(react_node.get_react_classes()))) deps_html = [''] for dep in deps: path = dep if dep.startswith('http://') or dep.startswith( 'https://') else self.get_asset_path(dep) if path.endswith('.css'): deps_html.append('<link href="%s" rel="stylesheet">' % bottle.html_escape(path)) elif path.endswith('.js'): deps_html.append('<script src="%s"></script>' % bottle.html_escape(path)) elif path.endswith('.jsx'): deps_html.append( '<script type="text/babel" src="%s"></script>' % bottle.html_escape(path)) else: # assume javascript deps_html.append('<script src="%s"></script>' % bottle.html_escape(path)) deps_html = '\n'.join(deps_html) init_nonce = kwargs.get('init_nonce', None) init_nonce = ' nonce="%s"' % init_nonce if init_nonce else '' init = ''' <script%s> bottlereact._onLoad(%s, function() { ReactDOM.render( %s, document.getElementById('__body__') ); }); </script> ''' % (init_nonce, classes, react_js) if 'title' not in kwargs: kwargs[ 'title'] = 'bottle-react - https://github.com/keredson/bottle-react' kwargs.update({ 'deps': deps_html, 'init': init, 'prod': self.prod, 'asset_path': self.get_asset_path, 'body': '', }) if callable(render_server): render_server = render_server() if render_server: kwargs['body'] = self.render_server(deps, react_js) return bottle.template(template, **kwargs)
def do_join(): # TODO: 오류 발생 시, 오류 메시지를 만들어서 에러 페이지로 리다이렉트 class JoinError(Exception): # 회원가입 실패 시, 발생시킬 예외 def __init__(self, value): self.value = value # request.forms.decode('utf-8') try: id = html_escape(request.forms.getunicode('id', '').strip()) name = html_escape(request.forms.getunicode('name', '').strip()) email = html_escape(request.forms.getunicode('email', '').strip()) passwd = request.forms.getunicode('password', '').strip() passwd2 = request.forms.getunicode('password2', '').strip() if not id or not name or not email or not passwd or not passwd2: raise JoinError('가입 정보가 부족합니다.') if passwd != passwd2: raise JoinError('암호가 일치하지 않습니다.') if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): raise JoinError('이메일 주소가 옳바르지 않습니다.') if m.has_id(id): raise JoinError('이미 존재하는 아이디입니다') if m.has_email(email): raise JoinError('이미 등록된 이메일입니다.') if m.has_name(name): raise JoinError('이미 등록된 사용자명입니다.') m.register(id, name, email, passwd) except JoinError as e: return template('popup.tpl', msg=e.value) except Exception as e: # return template('error_popup.tpl', # err_msg='사용자 등록에 실패했습니다. 잠시 후 다시 시도해주세요.') return template('popup.tpl', msg=e.args[1]) else: # 가입 절차 완료 # TODO: 가입 환영 메시지 출력 + 사용자 페이지로 이동 # redirect('/u/{}'.format(id)) redirect('/login') print('가입 완료')
def doAdd(ADMIN, c, conn): templ = template('themes/Default/header.tpl', config=CONFIG, admin=ADMIN) result = c.execute( 'INSERT INTO messages (title, txtBody, active) VALUES(?, ?, 1)', (html_escape(request.POST.utitle), html_escape(request.POST.ubody))) conn.commit() templ += template('themes/Default/message.tpl', msgid='', msg_title='رسالة إدارية', msg_body='تم إضافة رسالتك بنجاح.') return templ
def escape_value(value): if str(type(value)) == "<class 'bson.objectid.ObjectId'>": value = str(value) elif type(value) == str: value = html_escape(value) return value
def html_content(self, current_room=None): from bottle import html_escape from utils import url_for html = "" for text, refs in self.tokens: text = html_escape(text) # highlight matching reference in bold if any(ref.room_id == current_room.id for ref in refs): text = '<b>{text}</b>'.format(text=text) # link non-self single refs if len(refs) == 1 and refs[0].room_id != current_room.id: text = '<a href="{url}">{text}</a>'.format(url=url_for( refs[0].room), text=text) # link all multirefs elif len(refs) > 1: text = '<a href="{url}">{text}</a>'.format( url=url_for('/rooms', qs={ 'filter_id': ','.join(str(ref.room_id) for ref in refs) }), text=text) html += text return ''.join('<p>' + line.replace('\n', '<br />') + '</p>' for line in html.split('\n\n'))
def comparer(self, commit, commitb=None, fichier=''): """Comparaison entre deux versions. Si le deuxième commit n'est pas précisé, on compare la version demandée avec la précédente. """ if not commitb: commitb = commit commit += '^' try: modification = b.html_escape( '\n'.join( self.depot.comparer(commit, commitb, fichier=fichier) ) ) \ .replace('[-', '<em class="suppr"><del>[-') \ .replace('-]', '-]</del></em class="suppr">') \ .replace('{+', '<strong class="add">{+') \ .replace('+}', '+}</strong class="add">') modification = re.sub( 'diff.*\n', '\n\n<hr>\n', modification ) modification = re.sub( r'index.*\n.*\n\+\+\+ b/(.*)', str(h.B(h.I('{}'))).format(h.A('\\1', href='\\1')), modification ) modification = re.sub( '(@@.*@@)', '\n{}\n'.format(h.B(h.I('\\1'))), modification ) return h.CODE(modification) except f.GitError as err: f.traiter_erreur(err) return _("Il n'y a rien avant la création !")
def field_error(name, errors): """ Renders error message for single form field. This function renders a standardized markup for individual form field errors. .. note:: This is not a generic helper function like the other ones. It's more of an opinion on how error messages should be rendered, and it has no particular rationale behind it rather than 'This is how I do things'. The reason it is included here is that having consistent markup for form errors tends to increase the speed at which we are able to implement interfaces. For the error messages the render, the error dictionary must contain a key that matches the specified key. The key may map to a single string value or an iterable containing strings. Depending on how many error messages there are, one or more of span elements will be rendered. Every span will have 'field-error' class. :param name: name of the field to look up in the dict :param errors: dict-like object containing field-name-message mappings :returns: HTML of the error message if one is found, otherwise empty string """ try: return SPAN(html_escape(errors[name]), _class=ERR_CLS) except KeyError: return ''
def check_token(key='token'): username = bottle.request.get_cookie('name') secret = base64.b64encode(ensure_bytes(username)) token = bottle.request.get_cookie(key, secret=secret) if token is None: bottle.abort(408, 'Cache expired or user\'s report not generated yet!') return deserialize(bottle.html_escape(base64.b64decode(token)))
def html_content(self, current_room=None): from bottle import html_escape from utils import url_for html = "" for text, refs in self.tokens: text = html_escape(text) # highlight matching reference in bold if any(ref.room_id == current_room.id for ref in refs): text = '<b>{text}</b>'.format(text=text) # link non-self single refs if len(refs) == 1 and refs[0].room_id != current_room.id: text = '<a href="{url}">{text}</a>'.format( url=url_for(refs[0].room), text=text ) # link all multirefs elif len(refs) > 1: text = '<a href="{url}">{text}</a>'.format( url=url_for('/rooms', qs={ 'filter_id': ','.join(str(ref.room_id) for ref in refs) }), text=text ) html += text return ''.join('<p>' + line.replace('\n', '<br />') + '</p>' for line in html.split('\n\n'))
def format_text(text): text = html_escape(text) r = re_compile( r"(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)" ) text = r.sub('<a target="_blank" href="\\1">\\1</a>', text) text = text.replace('\n', '<br />\n') return text
def get_description(self, item, lang): """ Gets a description from an item and target language. """ descriptions = item.get('descriptions') if lang in descriptions and ' ' in descriptions[lang]: return html_escape(descriptions[lang]) else: return autodescribe(item['id'], lang)
def __call__(self, environ, start_response): try: return self.app(environ, start_response) except Exception: template_vars = {} if 'bottle.request.post' in environ: environ['bottle.request.post'] = dict( filter_sensitive_params(environ['bottle.request.post'], self.sensitive_params)) template_vars['environ'] = html_escape(pformat(environ)) template_vars['error'] = html_escape(repr(_e())) template_vars['trace'] = html_escape(format_exc()) template_vars['dump_file'] = self.dump_file environ['wsgi.errors'].write(format_exc()) headers = [('Content-Type', 'text/html; charset=UTF-8')] err = ERROR_TEMPLATE % template_vars start_response('500 INTERNAL SERVER ERROR', headers) with open("/tmp/%s" % self.dump_file, "w") as f: f.write(err) return [tob(err)]
def load(self): db = sqlite3.connect('db.db') self.title = Config.get(db, 'title') self.navbar = '' for row in db.execute('SELECT key, value FROM layout WHERE part = "navbar"').fetchall(): if row[0] and len(row[0]) > 0: if row[0].startswith('/') or row[0].startswith('http://') or row[0].startswith('https://'): self.navbar += '<a href="' + bottle.html_escape(row[0]) + '">' if row[1] and len(row[1]) > 0: self.navbar += bottle.html_escape(row[1]) elif row[0].startswith('/'): try: self.navbar += db.execute('SELECT title FROM pages WHERE url = ?', (row[0][1:],)).fetchone()[0] except: self.navbar += bottle.html_escape(row[0]) else: self.navbar += bottle.html_escape(row[0]) self.navbar += '</a>' elif row[1]: self.navbar += '<span>' + bottle.html_escape(row[1]) + '</span>' db.close()
def test_hydrate_entity(self): f, formitems = self.create_form() values = { '_id':('7489107348902', '7489107348902'), 'title':('This is a title', 'This is a title'), 'content':('<a href="/a/url?with=values&more=values">a link</a>','<a href="/a/url?with=values&more=values">a link</a>'), 'content_html':('<a href="/a/url?with=values&more=values">a link</a>','<a href="/a/url?with=values&more=values">a link</a>'), 'tagIds':([1,2, '<tag>is this escaped?</tag>'], [1,2, '<tag>is this escaped?</tag>']), 'newTag':('A new tag','A new tag'), } for item in f.formitems: f.set_value(item.name, values[item.name][0]) #set the unescaped values i = f.hydrate_entity(Item()) self.assertEqual(i._id, f.get_value('_id')) self.assertEqual(i.title, f.get_value('title')) self.assertEqual(html_escape(i.content), f.get_value('content')) self.assertEqual(html_escape(i.content), f.get_value('content_html')) self.assertEqual(i.tagIds[0], f.get_value('tagIds')[0]) self.assertEqual(i.tagIds[1], f.get_value('tagIds')[1]) self.assertEqual(html_escape(i.tagIds[2]), f.get_value('tagIds')[2])
def __call__(self, environ, start_response): try: return self.app(environ, start_response) except Exception: # This code is largely taken from ``def wsgi()`` in the bottle # code itself, but logs to the log file rather than writing to # environ['wsgi.errors'] LOGGER.exception("Error processing request") err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info()) return []
def debug(error=None): if hasattr(error, 'traceback'): msg = error.traceback if not msg: # Bottle raised exception msg = error.body else: msg = error if console: header = console.get_header() if header: k,v = header response.headers[k] = v if error: if request.is_xhr and console: console.log(msg) return { 'error': True } else: return '<pre>%s</pre>' % html_escape(msg)
def preview(self, args): id = args['id'] item_value = ItemValue(id=id) item = self.store.get_item(id) lang = args.get('lang') image = self.get_image_for_item(item_value, item, lang) desc = self.get_description(item, lang) args = { 'id': id, 'label': html_escape(lngfb(item.get('labels'), lang) or id), 'description': desc, 'image': image, 'url': qid_url_pattern.replace('{{id}}', id), 'width': preview_width, 'height': preview_height, } return self.preview_template.render(**args)
def post_show(post_id): row = db.execute('SELECT `title` FROM `post` WHERE `id`=?', (post_id,)).fetchone() if row == None: return HTTPError(404, 'Post not found') title = row[0] rows = db.execute('SELECT `text` FROM `comment` WHERE `post_id`=?', (post_id,)).fetchall() escaped_comments = [] for row in rows: escaped_comments.append(bottle.html_escape(row[0]).replace("\n", "<br>")) return template('post_show', { 'title': title, 'escaped_comments': escaped_comments, 'post_id': post_id, 'group_name': "Default", 'user_name': request.get_cookie("user_name", secret=salt)})
def preview(self, args): id = args['id'] item_value = ItemValue(id=id) item = self.store.get_item(id) lang = args.get('lang') image = self.get_image_for_item(item_value, item, lang) desc = self.get_description(item, lang) args = { 'id': id, 'label': html_escape(lngfb(item.get('labels'), lang) or id), 'description': desc, 'image': image, 'url': 'https://www.wikidata.org/entity/' + id, 'width': preview_width, 'height': preview_height, } return self.preview_template.render(**args)
def new_build_request(): ''' Process request for a new build ''' selected = dict(bottle.request.POST.allitems()).keys() selected.remove('submit') try: build = data.Build(options=selected) message = 'Your new build (%s) has been submitted.' % build.id except data.ExistingBuildError as e: message = 'This build already exists as %s.' % e.build_id except KeyError as e: return render('error.html', code=200, message='Invalid build option (%s) was requested' % bottle.html_escape(e[0])) except data.BuildConflictError: message='Could not generate a unique name for your build. Please join #nginx-master on freenode to report this issue.' return render('error.html', message=message) return render('page.html', content=message)
def do_login(): id = html_escape(request.forms.getunicode('id', '').strip()) passwd = request.forms.getunicode('password', '').strip() remember = True if request.forms.getunicode('remember') else False dest = request.forms.getunicode('dest', '/u/{}'.format(id)).strip() if not id or not passwd: # 정보가 안 넘어왔을 경우, 팝업으로 경고 후, 로그인 폼으로.. redirect('/login') try: user_info = m.login(id, passwd) print('USER_INFO: ', user_info) if user_info: s.login(user_info[0], user_info[1], user_info[2], user_info[3]) else: return template('popup.tpl', msg='아이디/패스워드가 일치하지 않습니다.') except Exception as e: print(e) return template('popup.tpl', msg='일시적인 장애로 로그인할 수 없습니다') else: redirect(dest)
def test_entity_in_constructor(self): i = Item() i._id = '2436728647829' i.title = 'Test title' i.content = 'escapable <content></content>' i.tagIds = [1,2,3] formitems = [] formitems.append(FormItem(Types.HIDDEN_TYPE, '_id', id='_id')) formitems.append(FormItem(Types.TEXT_TYPE, 'title', id='title', label_text='Title', class_name="form-control", required=True)) formitems.append(FormItem(Types.TEXTAREA_TYPE, 'content', id='content', label_text='Content', class_name="form-control")) formitems.append(FormItem(Types.MULTI_SELECT_TYPE, 'tagIds', id='tagIds', label_text='Tags', class_name="form-control", select_list_items=self.tags)) formitems.append(FormItem(Types.TEXT_TYPE, 'newTag', id='newTag', label_text='New Tag', class_name="form-control")) f = FormBuilder(formitems, entity=i) #test that the form values have been populated from the entity self.assertEqual(i._id, f.get_value('_id')) self.assertEqual(i.title, f.get_value('title')) self.assertEqual(html_escape(i.content), f.get_value('content')) self.assertEqual(i.tagIds, f.get_value('tagIds'))
def rend(txt): out = bottle.html_escape(txt) out = sp(out) return out.replace('\n', '<br />')
def html_escape_nl2br(text): """ Escapes text and replaces \n with <br>. """ return html_escape(text).replace('\n', '<br>')
def linebreaks(string): return bottle.html_escape(string).replace('\n', '<br>')
def transform_notification_message(msg): return html_escape(msg).replace("\n", "<br />")
def root7(): """html_escape untaints the xss taint, so not tainted.""" return '<p>%s</p>' % html_escape(request.query.xss)
def nl2br(s): """改行文字をbrタグに変換する """ return html_escape(s).replace('\n','<br />')
def escaped_body(self): escaped = LocalizableTextValue() for k, v in self.body.iteritems(): escaped[k] = html_escape(self.body[k]).replace("\n", "<br />") return escaped
def rend(txt, image=False): out = bottle.html_escape(txt) out = sp(out, image) return out.replace('\n', '<br />')