Best Python code snippet using toolium_python
util.py
Source:util.py
1# This file is part of Indico.2# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).3#4# Indico is free software; you can redistribute it and/or5# modify it under the terms of the GNU General Public License as6# published by the Free Software Foundation; either version 3 of the7# License, or (at your option) any later version.8#9# Indico is distributed in the hope that it will be useful, but10# WITHOUT ANY WARRANTY; without even the implied warranty of11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU12# General Public License for more details.13#14# You should have received a copy of the GNU General Public License15# along with Indico; if not, see <http://www.gnu.org/licenses/>.16from __future__ import absolute_import, unicode_literals17from datetime import datetime18from flask import g, has_request_context, jsonify, render_template, request, session19from markupsafe import Markup20from indico.util.i18n import _21from indico.web.flask.templating import get_template_module22def inject_js(js):23 """Injects JavaScript into the current page.24 :param js: Code wrapped in a ``<script>`` tag.25 """26 if 'injected_js' not in g:27 g.injected_js = []28 g.injected_js.append(Markup(js))29def _pop_injected_js():30 js = None31 if 'injected_js' in g:32 js = g.injected_js33 del g.injected_js34 return js35def jsonify_form(form, fields=None, submit=None, back=None, back_url=None, back_button=True, disabled_until_change=True,36 disabled_fields=(), form_header_kwargs=None, skip_labels=False, save_reminder=False,37 footer_align_right=False, disable_if_locked=True):38 """Returns a json response containing a rendered WTForm.39 This ia shortcut to the ``simple_form`` jinja macro to avoid40 adding new templates that do nothing besides importing and41 calling this macro.42 :param form: A WTForms `Form` instance43 :param fields: A list of fields to be displayed on the form44 :param submit: The title of the submit button45 :param back: The title of the back button46 :param back_url: The URL the back button redirects to47 :param back_button: Whether to show a back button48 :param disabled_until_change: Whether to disable form submission49 until a field is changed50 :param disabled_fields: List of field names to disable51 :param form_header_kwargs: Keyword arguments passed to the52 ``form_header`` macro53 :param skip_labels: Whether to show labels on the fields54 :param save_reminder: Whether to show a message when the form has55 been modified and the save button is not56 visible57 :param footer_align_right: Whether the buttons in the event footer58 should be aligned to the right.59 :param disable_if_locked: Whether the form should be disabled when60 the associated event is locked (based on61 a CSS class in the DOM structure)62 """63 if submit is None:64 submit = _('Save')65 if back is None:66 back = _('Cancel')67 if form_header_kwargs is None:68 form_header_kwargs = {}69 tpl = get_template_module('forms/_form.html')70 html = tpl.simple_form(form, fields=fields, submit=submit, back=back, back_url=back_url, back_button=back_button,71 disabled_until_change=disabled_until_change, disabled_fields=disabled_fields,72 form_header_kwargs=form_header_kwargs, skip_labels=skip_labels, save_reminder=save_reminder,73 footer_align_right=footer_align_right, disable_if_locked=disable_if_locked)74 return jsonify(html=html, js=_pop_injected_js())75def jsonify_template(template, _render_func=render_template, _success=None, **context):76 """Returns a json response containing a rendered template"""77 html = _render_func(template, **context)78 jsonify_kw = {}79 if _success is not None:80 jsonify_kw['success'] = _success81 return jsonify(html=html, js=_pop_injected_js(), **jsonify_kw)82def jsonify_data(flash=True, **json_data):83 """Returns a json response with some default fields.84 This behaves similar to :func:`~flask.jsonify`, but includes85 ``success=True`` and flashed messages by default.86 :param flash: if the json data should contain flashed messages87 :param json_data: the data to include in the json response88 """89 json_data.setdefault('success', True)90 if flash:91 json_data['flashed_messages'] = render_template('flashed_messages.html')92 return jsonify(**json_data)93def _format_request_data(data, hide_passwords=False):94 if not hasattr(data, 'iterlists'):95 data = ((k, [v]) for k, v in data.iteritems())96 else:97 data = data.iterlists()98 rv = {}99 for key, values in data:100 if hide_passwords and 'password' in key:101 values = [v if not v else '<{} chars hidden>'.format(len(v)) for v in values]102 rv[key] = values if len(values) != 1 else values[0]103 return rv104def get_request_info(hide_passwords=True):105 """Gets various information about the current HTTP request.106 This is especially useful for logging purposes where you want107 as many information as possible.108 :param hide_passwords: Hides the actual value of POST fields109 if their name contains ``password``.110 :return: a dictionary containing request information, or ``None``111 when called outside a request context112 """113 if not has_request_context():114 return None115 try:116 user_info = {117 'id': session.user.id,118 'name': session.user.full_name,119 'email': session.user.email120 } if session.user else None121 except Exception as exc:122 user_info = 'ERROR: {}'.format(exc)123 return {124 'id': request.id,125 'time': datetime.now().isoformat(),126 'url': request.url,127 'endpoint': request.url_rule.endpoint if request.url_rule else None,128 'method': request.method,129 'rh': g.rh.__class__.__name__ if 'rh' in g else None,130 'user': user_info,131 'ip': request.remote_addr,132 'user_agent': unicode(request.user_agent),133 'referrer': request.referrer,134 'data': {135 'url': _format_request_data(request.view_args) if request.view_args is not None else None,136 'get': _format_request_data(request.args),137 'post': _format_request_data(request.form, hide_passwords=hide_passwords),138 'json': request.get_json(silent=True),139 'headers': _format_request_data(request.headers, False),140 }141 }142def url_for_index(_external=False, _anchor=None):143 from indico.web.flask.util import url_for...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!