Best Python code snippet using yandex-tank
ir_qweb_fields.py
Source:ir_qweb_fields.py
...33 """34 _name = 'ir.qweb.field'35 _description = 'Qweb Field'36 @api.model37 def get_available_options(self):38 """39 Get the available option informations.40 Returns a dict of dict with:41 * key equal to the option key.42 * dict: type, params, name, description, default_value43 * type:44 'string'45 'integer'46 'float'47 'model' (e.g. 'res.partner')48 'array'49 'selection' (e.g. [key1, key2...])50 """51 return {}52 @api.model53 def attributes(self, record, field_name, options, values=None):54 """ attributes(record, field_name, field, options, values)55 Generates the metadata attributes (prefixed by ``data-oe-``) for the56 root node of the field conversion.57 The default attributes are:58 * ``model``, the name of the record's model59 * ``id`` the id of the record to which the field belongs60 * ``type`` the logical field type (widget, may not match the field's61 ``type``, may not be any Field subclass name)62 * ``translate``, a boolean flag (``0`` or ``1``) denoting whether the63 field is translatable64 * ``readonly``, has this attribute if the field is readonly65 * ``expression``, the original expression66 :returns: dict (attribute name, attribute value).67 """68 data = {}69 field = record._fields[field_name]70 if not options['inherit_branding'] and not options['translate']:71 return data72 data['data-oe-model'] = record._name73 data['data-oe-id'] = record.id74 data['data-oe-field'] = field.name75 data['data-oe-type'] = options.get('type')76 data['data-oe-expression'] = options.get('expression')77 if field.readonly:78 data['data-oe-readonly'] = 179 return data80 @api.model81 def value_to_html(self, value, options):82 """ value_to_html(value, field, options=None)83 Converts a single value to its HTML version/output84 :rtype: unicode85 """86 return escape(pycompat.to_text(value))87 @api.model88 def record_to_html(self, record, field_name, options):89 """ record_to_html(record, field_name, options)90 Converts the specified field of the ``record`` to HTML91 :rtype: unicode92 """93 if not record:94 return False95 value = record[field_name]96 return False if value is False else record.env[self._name].value_to_html(value, options=options)97 @api.model98 def user_lang(self):99 """ user_lang()100 Fetches the res.lang record corresponding to the language code stored101 in the user's context.102 :returns: Model[res.lang]103 """104 return get_lang(self.env)105class IntegerConverter(models.AbstractModel):106 _name = 'ir.qweb.field.integer'107 _description = 'Qweb Field Integer'108 _inherit = 'ir.qweb.field'109 @api.model110 def value_to_html(self, value, options):111 return pycompat.to_text(self.user_lang().format('%d', value, grouping=True).replace(r'-', '-\N{ZERO WIDTH NO-BREAK SPACE}'))112class FloatConverter(models.AbstractModel):113 _name = 'ir.qweb.field.float'114 _description = 'Qweb Field Float'115 _inherit = 'ir.qweb.field'116 @api.model117 def get_available_options(self):118 options = super(FloatConverter, self).get_available_options()119 options.update(120 precision=dict(type='integer', string=_('Rounding precision')),121 )122 return options123 @api.model124 def value_to_html(self, value, options):125 if 'decimal_precision' in options:126 precision = self.env['decimal.precision'].precision_get(options['decimal_precision'])127 else:128 precision = options['precision']129 if precision is None:130 fmt = '%f'131 else:132 value = float_utils.float_round(value, precision_digits=precision)133 fmt = '%.{precision}f'.format(precision=precision)134 formatted = self.user_lang().format(fmt, value, grouping=True).replace(r'-', '-\N{ZERO WIDTH NO-BREAK SPACE}')135 # %f does not strip trailing zeroes. %g does but its precision causes136 # it to switch to scientific notation starting at a million *and* to137 # strip decimals. So use %f and if no precision was specified manually138 # strip trailing 0.139 if precision is None:140 formatted = re.sub(r'(?:(0|\d+?)0+)$', r'\1', formatted)141 return pycompat.to_text(formatted)142 @api.model143 def record_to_html(self, record, field_name, options):144 if 'precision' not in options and 'decimal_precision' not in options:145 _, precision = record._fields[field_name].get_digits(record.env) or (None, None)146 options = dict(options, precision=precision)147 return super(FloatConverter, self).record_to_html(record, field_name, options)148class DateConverter(models.AbstractModel):149 _name = 'ir.qweb.field.date'150 _description = 'Qweb Field Date'151 _inherit = 'ir.qweb.field'152 @api.model153 def get_available_options(self):154 options = super(DateConverter, self).get_available_options()155 options.update(156 format=dict(type='string', string=_('Date format'))157 )158 return options159 @api.model160 def value_to_html(self, value, options):161 return format_date(self.env, value, date_format=options.get('format'))162class DateTimeConverter(models.AbstractModel):163 _name = 'ir.qweb.field.datetime'164 _description = 'Qweb Field Datetime'165 _inherit = 'ir.qweb.field'166 @api.model167 def get_available_options(self):168 options = super(DateTimeConverter, self).get_available_options()169 options.update(170 format=dict(type='string', string=_('Pattern to format')),171 tz_name=dict(type='char', string=_('Optional timezone name')),172 time_only=dict(type='boolean', string=_('Display only the time')),173 hide_seconds=dict(type='boolean', string=_('Hide seconds')),174 date_only=dict(type='boolean', string=_('Display only the date')),175 )176 return options177 @api.model178 def value_to_html(self, value, options):179 if not value:180 return ''181 options = options or {}182 lang = self.user_lang()183 locale = babel_locale_parse(lang.code)184 format_func = babel.dates.format_datetime185 if isinstance(value, str):186 value = fields.Datetime.from_string(value)187 value = fields.Datetime.context_timestamp(self, value)188 if options.get('tz_name'):189 tzinfo = babel.dates.get_timezone(options['tz_name'])190 else:191 tzinfo = None192 if 'format' in options:193 pattern = options['format']194 else:195 if options.get('time_only'):196 strftime_pattern = ("%s" % (lang.time_format))197 elif options.get('date_only'):198 strftime_pattern = ("%s" % (lang.date_format))199 else:200 strftime_pattern = ("%s %s" % (lang.date_format, lang.time_format))201 pattern = posix_to_ldml(strftime_pattern, locale=locale)202 if options.get('hide_seconds'):203 pattern = pattern.replace(":ss", "").replace(":s", "")204 if options.get('time_only'):205 format_func = babel.dates.format_time206 return pycompat.to_text(format_func(value, format=pattern, tzinfo=tzinfo, locale=locale))207 if options.get('date_only'):208 format_func = babel.dates.format_date209 return pycompat.to_text(format_func(value, format=pattern, locale=locale))210 return pycompat.to_text(format_func(value, format=pattern, tzinfo=tzinfo, locale=locale))211class TextConverter(models.AbstractModel):212 _name = 'ir.qweb.field.text'213 _description = 'Qweb Field Text'214 _inherit = 'ir.qweb.field'215 @api.model216 def value_to_html(self, value, options):217 """218 Escapes the value and converts newlines to br. This is bullshit.219 """220 return nl2br(escape(value)) if value else ''221class SelectionConverter(models.AbstractModel):222 _name = 'ir.qweb.field.selection'223 _description = 'Qweb Field Selection'224 _inherit = 'ir.qweb.field'225 @api.model226 def get_available_options(self):227 options = super(SelectionConverter, self).get_available_options()228 options.update(229 selection=dict(type='selection', string=_('Selection'), description=_('By default the widget uses the field information'), required=True)230 )231 return options232 @api.model233 def value_to_html(self, value, options):234 if not value:235 return ''236 return escape(pycompat.to_text(options['selection'][value]) or '')237 @api.model238 def record_to_html(self, record, field_name, options):239 if 'selection' not in options:240 options = dict(options, selection=dict(record._fields[field_name].get_description(self.env)['selection']))241 return super(SelectionConverter, self).record_to_html(record, field_name, options)242class ManyToOneConverter(models.AbstractModel):243 _name = 'ir.qweb.field.many2one'244 _description = 'Qweb Field Many to One'245 _inherit = 'ir.qweb.field'246 @api.model247 def value_to_html(self, value, options):248 if not value:249 return False250 value = value.sudo().display_name251 if not value:252 return False253 return nl2br(escape(value))254class ManyToManyConverter(models.AbstractModel):255 _name = 'ir.qweb.field.many2many'256 _description = 'Qweb field many2many'257 _inherit = 'ir.qweb.field'258 @api.model259 def value_to_html(self, value, options):260 if not value:261 return False262 text = ', '.join(value.sudo().mapped('display_name'))263 return nl2br(escape(text))264class HTMLConverter(models.AbstractModel):265 _name = 'ir.qweb.field.html'266 _description = 'Qweb Field HTML'267 _inherit = 'ir.qweb.field'268 @api.model269 def value_to_html(self, value, options):270 irQweb = self.env['ir.qweb']271 # wrap value inside a body and parse it as HTML272 body = etree.fromstring("<body>%s</body>" % value, etree.HTMLParser(encoding='utf-8'))[0]273 # use pos processing for all nodes with attributes274 for element in body.iter():275 if element.attrib:276 attrib = dict(element.attrib)277 attrib = irQweb._post_processing_att(element.tag, attrib, options.get('template_options'))278 element.attrib.clear()279 element.attrib.update(attrib)280 return M(etree.tostring(body, encoding='unicode', method='html')[6:-7])281class ImageConverter(models.AbstractModel):282 """ ``image`` widget rendering, inserts a data:uri-using image tag in the283 document. May be overridden by e.g. the website module to generate links284 instead.285 .. todo:: what happens if different output need different converters? e.g.286 reports may need embedded images or FS links whereas website287 needs website-aware288 """289 _name = 'ir.qweb.field.image'290 _description = 'Qweb Field Image'291 _inherit = 'ir.qweb.field'292 @api.model293 def value_to_html(self, value, options):294 try: # FIXME: maaaaaybe it could also take raw bytes?295 image = Image.open(BytesIO(base64.b64decode(value)))296 image.verify()297 except IOError:298 raise ValueError("Non-image binary fields can not be converted to HTML")299 except: # image.verify() throws "suitable exceptions", I have no idea what they are300 raise ValueError("Invalid image content")301 return M('<img src="data:%s;base64,%s">' % (Image.MIME[image.format], value.decode('ascii')))302class ImageUrlConverter(models.AbstractModel):303 """ ``image_url`` widget rendering, inserts an image tag in the304 document.305 """306 _name = 'ir.qweb.field.image_url'307 _description = 'Qweb Field Image'308 _inherit = 'ir.qweb.field.image'309 @api.model310 def value_to_html(self, value, options):311 return M('<img src="%s">' % (value))312class MonetaryConverter(models.AbstractModel):313 """ ``monetary`` converter, has a mandatory option314 ``display_currency`` only if field is not of type Monetary.315 Otherwise, if we are in presence of a monetary field, the field definition must316 have a currency_field attribute set.317 The currency is used for formatting *and rounding* of the float value. It318 is assumed that the linked res_currency has a non-empty rounding value and319 res.currency's ``round`` method is used to perform rounding.320 .. note:: the monetary converter internally adds the qweb context to its321 options mapping, so that the context is available to callees.322 It's set under the ``_values`` key.323 """324 _name = 'ir.qweb.field.monetary'325 _description = 'Qweb Field Monetary'326 _inherit = 'ir.qweb.field'327 @api.model328 def get_available_options(self):329 options = super(MonetaryConverter, self).get_available_options()330 options.update(331 from_currency=dict(type='model', params='res.currency', string=_('Original currency')),332 display_currency=dict(type='model', params='res.currency', string=_('Display currency'), required="value_to_html"),333 date=dict(type='date', string=_('Date'), description=_('Date used for the original currency (only used for t-esc). by default use the current date.')),334 company_id=dict(type='model', params='res.company', string=_('Company'), description=_('Company used for the original currency (only used for t-esc). By default use the user company')),335 )336 return options337 @api.model338 def value_to_html(self, value, options):339 display_currency = options['display_currency']340 if not isinstance(value, (int, float)):341 raise ValueError(_("The value send to monetary field is not a number."))342 # lang.format mandates a sprintf-style format. These formats are non-343 # minimal (they have a default fixed precision instead), and344 # lang.format will not set one by default. currency.round will not345 # provide one either. So we need to generate a precision value346 # (integer > 0) from the currency's rounding (a float generally < 1.0).347 fmt = "%.{0}f".format(display_currency.decimal_places)348 if options.get('from_currency'):349 date = options.get('date') or fields.Date.today()350 company_id = options.get('company_id')351 if company_id:352 company = self.env['res.company'].browse(company_id)353 else:354 company = self.env.company355 value = options['from_currency']._convert(value, display_currency, company, date)356 lang = self.user_lang()357 formatted_amount = lang.format(fmt, display_currency.round(value),358 grouping=True, monetary=True).replace(r' ', '\N{NO-BREAK SPACE}').replace(r'-', '-\N{ZERO WIDTH NO-BREAK SPACE}')359 pre = post = ''360 if display_currency.position == 'before':361 pre = '{symbol}\N{NO-BREAK SPACE}'.format(symbol=display_currency.symbol or '')362 else:363 post = '\N{NO-BREAK SPACE}{symbol}'.format(symbol=display_currency.symbol or '')364 if options.get('label_price') and lang.decimal_point in formatted_amount:365 sep = lang.decimal_point366 integer_part, decimal_part = formatted_amount.split(sep)367 integer_part += sep368 return M('{pre}<span class="oe_currency_value">{0}</span><span class="oe_currency_value" style="font-size:0.5em">{1}</span>{post}').format(integer_part, decimal_part, pre=pre, post=post)369 return M('{pre}<span class="oe_currency_value">{0}</span>{post}').format(formatted_amount, pre=pre, post=post)370 @api.model371 def record_to_html(self, record, field_name, options):372 options = dict(options)373 #currency should be specified by monetary field374 field = record._fields[field_name]375 if not options.get('display_currency') and field.type == 'monetary' and field.get_currency_field(record):376 options['display_currency'] = record[field.get_currency_field(record)]377 if not options.get('display_currency'):378 # search on the model if they are a res.currency field to set as default379 fields = record._fields.items()380 currency_fields = [k for k, v in fields if v.type == 'many2one' and v.comodel_name == 'res.currency']381 if currency_fields:382 options['display_currency'] = record[currency_fields[0]]383 if 'date' not in options:384 options['date'] = record._context.get('date')385 if 'company_id' not in options:386 options['company_id'] = record._context.get('company_id')387 return super(MonetaryConverter, self).record_to_html(record, field_name, options)388TIMEDELTA_UNITS = (389 ('year', _lt('year'), 3600 * 24 * 365),390 ('month', _lt('month'), 3600 * 24 * 30),391 ('week', _lt('week'), 3600 * 24 * 7),392 ('day', _lt('day'), 3600 * 24),393 ('hour', _lt('hour'), 3600),394 ('minute', _lt('minute'), 60),395 ('second', _lt('second'), 1)396)397class FloatTimeConverter(models.AbstractModel):398 """ ``float_time`` converter, to display integral or fractional values as399 human-readable time spans (e.g. 1.5 as "01:30").400 Can be used on any numerical field.401 """402 _name = 'ir.qweb.field.float_time'403 _description = 'Qweb Field Float Time'404 _inherit = 'ir.qweb.field'405 @api.model406 def value_to_html(self, value, options):407 return format_duration(value)408class DurationConverter(models.AbstractModel):409 """ ``duration`` converter, to display integral or fractional values as410 human-readable time spans (e.g. 1.5 as "1 hour 30 minutes").411 Can be used on any numerical field.412 Has an option ``unit`` which can be one of ``second``, ``minute``,413 ``hour``, ``day``, ``week`` or ``year``, used to interpret the numerical414 field value before converting it. By default use ``second``.415 Has an option ``round``. By default use ``second``.416 Has an option ``digital`` to display 01:00 instead of 1 hour417 Sub-second values will be ignored.418 """419 _name = 'ir.qweb.field.duration'420 _description = 'Qweb Field Duration'421 _inherit = 'ir.qweb.field'422 @api.model423 def get_available_options(self):424 options = super(DurationConverter, self).get_available_options()425 unit = [(value, str(label)) for value, label, ratio in TIMEDELTA_UNITS]426 options.update(427 digital=dict(type="boolean", string=_('Digital formatting')),428 unit=dict(type="selection", params=unit, string=_('Date unit'), description=_('Date unit used for comparison and formatting'), default_value='second', required=True),429 round=dict(type="selection", params=unit, string=_('Rounding unit'), description=_("Date unit used for the rounding. The value must be smaller than 'hour' if you use the digital formatting."), default_value='second'),430 format=dict(431 type="selection",432 params=[433 ('long', _('Long')),434 ('short', _('Short')),435 ('narrow', _('Narrow'))],436 string=_('Format'),437 description=_("Formatting: long, short, narrow (not used for digital)"),438 default_value='long'439 ),440 add_direction=dict(441 type="boolean",442 string=_("Add direction"),443 description=_("Add directional information (not used for digital)")444 ),445 )446 return options447 @api.model448 def value_to_html(self, value, options):449 units = {unit: duration for unit, label, duration in TIMEDELTA_UNITS}450 locale = babel_locale_parse(self.user_lang().code)451 factor = units[options.get('unit', 'second')]452 round_to = units[options.get('round', 'second')]453 if options.get('digital') and round_to > 3600:454 round_to = 3600455 r = round((value * factor) / round_to) * round_to456 sections = []457 sign = ''458 if value < 0:459 r = -r460 sign = '-'461 if options.get('digital'):462 for unit, label, secs_per_unit in TIMEDELTA_UNITS:463 if secs_per_unit > 3600:464 continue465 v, r = divmod(r, secs_per_unit)466 if not v and (secs_per_unit > factor or secs_per_unit < round_to):467 continue468 sections.append(u"%02.0f" % int(round(v)))469 return sign + u':'.join(sections)470 for unit, label, secs_per_unit in TIMEDELTA_UNITS:471 v, r = divmod(r, secs_per_unit)472 if not v:473 continue474 section = babel.dates.format_timedelta(475 v*secs_per_unit,476 granularity=round_to,477 add_direction=options.get('add_direction'),478 format=options.get('format', 'long'),479 threshold=1,480 locale=locale)481 if section:482 sections.append(section)483 if sign:484 sections.insert(0, sign)485 return u' '.join(sections)486class RelativeDatetimeConverter(models.AbstractModel):487 _name = 'ir.qweb.field.relative'488 _description = 'Qweb Field Relative'489 _inherit = 'ir.qweb.field'490 @api.model491 def get_available_options(self):492 options = super(RelativeDatetimeConverter, self).get_available_options()493 options.update(494 now=dict(type='datetime', string=_('Reference date'), description=_('Date to compare with the field value, by default use the current date.'))495 )496 return options497 @api.model498 def value_to_html(self, value, options):499 locale = babel_locale_parse(self.user_lang().code)500 if isinstance(value, str):501 value = fields.Datetime.from_string(value)502 # value should be a naive datetime in UTC. So is fields.Datetime.now()503 reference = fields.Datetime.from_string(options['now'])504 return pycompat.to_text(babel.dates.format_timedelta(value - reference, add_direction=True, locale=locale))505 @api.model506 def record_to_html(self, record, field_name, options):507 if 'now' not in options:508 options = dict(options, now=record._fields[field_name].now())509 return super(RelativeDatetimeConverter, self).record_to_html(record, field_name, options)510class BarcodeConverter(models.AbstractModel):511 """ ``barcode`` widget rendering, inserts a data:uri-using image tag in the512 document. May be overridden by e.g. the website module to generate links513 instead.514 """515 _name = 'ir.qweb.field.barcode'516 _description = 'Qweb Field Barcode'517 _inherit = 'ir.qweb.field'518 @api.model519 def get_available_options(self):520 options = super(BarcodeConverter, self).get_available_options()521 options.update(522 symbology=dict(type='string', string=_('Barcode symbology'), description=_('Barcode type, eg: UPCA, EAN13, Code128'), default_value='Code128'),523 width=dict(type='integer', string=_('Width'), default_value=600),524 height=dict(type='integer', string=_('Height'), default_value=100),525 humanreadable=dict(type='integer', string=_('Human Readable'), default_value=0),526 quiet=dict(type='integer', string='Quiet', default_value=1),527 mask=dict(type='string', string='Mask', default_value='')528 )529 return options530 @api.model531 def value_to_html(self, value, options=None):532 if not value:533 return ''534 barcode_symbology = options.get('symbology', 'Code128')535 barcode = self.env['ir.actions.report'].barcode(536 barcode_symbology,537 value,538 **{key: value for key, value in options.items() if key in ['width', 'height', 'humanreadable', 'quiet', 'mask']})539 img_element = html.Element('img')540 for k, v in options.items():541 if k.startswith('img_') and k[4:] in safe_attrs:542 img_element.set(k[4:], v)543 if not img_element.get('alt'):544 img_element.set('alt', _('Barcode %s') % value)545 img_element.set('src', 'data:image/png;base64,%s' % base64.b64encode(barcode).decode())546 return M(html.tostring(img_element, encoding='unicode'))547class Contact(models.AbstractModel):548 _name = 'ir.qweb.field.contact'549 _description = 'Qweb Field Contact'550 _inherit = 'ir.qweb.field.many2one'551 @api.model552 def get_available_options(self):553 options = super(Contact, self).get_available_options()554 contact_fields = [555 {'field_name': 'name', 'label': _('Name'), 'default': True},556 {'field_name': 'address', 'label': _('Address'), 'default': True},557 {'field_name': 'phone', 'label': _('Phone'), 'default': True},558 {'field_name': 'mobile', 'label': _('Mobile'), 'default': True},559 {'field_name': 'email', 'label': _('Email'), 'default': True},560 {'field_name': 'vat', 'label': _('VAT')},561 ]562 separator_params = dict(563 type='selection',564 selection=[[" ", _("Space")], [",", _("Comma")], ["-", _("Dash")], ["|", _("Vertical bar")], ["/", _("Slash")]],565 placeholder=_('Linebreak'),566 )567 options.update(...
__main__.py
Source:__main__.py
...69 if 'host' not in form:70 form['host'] = socket.getfqdn()71 all_params = {'run': run, **form}72 return render_template('welcome.html',73 menu_options=wizard.get_available_options(),74 **all_params)75@app.route('/sshkey/<int:run>')76def determine_ssh_status(run=0):77 if not os.path.exists('etc/ssh'):78 os.mkdir('etc/ssh')79 if not os.path.exists('etc/ssh/authorized_keys'):80 return render_template('need_ssh.html', run=run,81 menu_options=wizard.get_available_options())82 else:83 return redirect(url_for('explain_certificate_authority', run=0))84@app.route('/ca/<int:run>')85def explain_certificate_authority(run=0):86 # TODO: this needs to be changed87 if not os.path.exists('etc/ca'):88 os.mkdir('etc/ca')89 if not os.path.exists('etc/ca/UNDERSTAND') and \90 not os.path.exists('etc/ca/demoCA'):91 return render_template('need_ca.html',92 menu_options=wizard.get_available_options(),93 run=run)94 else:95 return redirect(url_for('get_named_directories_root'))96@app.route('/create_ca')97def create_certificate_authority(run=0):98 if os.path.exists('etc/ca/demoCA'):99 return render_template('exists_ca.html',100 menu_options=wizard.get_available_options(),101 next_route='/named_directories')102 ca_template = _ca_template.format(103 country=wizard.config['General']['country'],104 state=wizard.config['General']['state'],105 locality=wizard.config['General']['locality'],106 orgname=wizard.config['General']['orgname'],107 orgunit=wizard.config['General']['orgunit'],108 commonname=wizard.config['General']['commonname'],109 email=wizard.config['General']['email'])110 with open('init.ssl', 'wt') as w:111 w.write(ca_template)112 ca_ok = ca.create_ca()113 if ca_ok:114 wizard.change_config('CA', type='self-signed')115 return redirect(url_for('get_named_directories_root'))116 return render_template('ca_not_created.html',117 menu_options=wizard.get_available_options())118@app.route('/named_directories', methods=['GET', 'POST'])119def get_named_directories_root():120 form = _delist(request.form)121 if 'named' in form:122 root = form['named']123 else:124 root = wizard.config['General'].get('nameddirectoriesroot', None)125 if root is None or not os.path.isdir(root):126 return render_template('named_directories.html',127 menu_options=wizard.get_available_options(),128 root=root)129 wizard.change_config('General', nameddirectoriesroot=root)130 return redirect(url_for('choose_containers'))131@app.route('/choose', methods=['GET', 'POST'])132def choose_containers():133 if len(request.form) > 0:134 active_containers = []135 for entry in request.form:136 active_containers.append(entry)137 wizard.change_config('General', containers=active_containers)138 return redirect(url_for('configure_containers'))139 active_containers = wizard.config['General'].get('containers', ['ldap'])140 return render_template('choose_containers.html',141 menu_options=wizard.get_available_options(),142 descriptive_names=wizard.descriptive_names,143 dependencies=wizard.dependencies,144 container_role=wizard.container_role,145 active_containers=active_containers,146 container_order=wizard.container_order)147def _render_configure_template(template, container, **kwargs):148 complete_configuration = [149 container for container in wizard.container_order150 if wizard.is_configuration_complete(container)]151 if container is not None:152 samples = wizard.get_configuration_file_samples(container)153 requirements = [(req, wizard.descriptive_requirements[req])154 for req in wizard.requirements[container]]155 complete_samples = [156 file_name for file_name in samples157 if wizard.is_file_configured(container, file_name)]158 else:159 samples = None160 complete_samples = None161 requirements = None162 complete_requirements = [req for req in wizard.requirements[container]163 if wizard.is_requirement_fullfiled(164 container, req)]165 my_containers = [container166 for container in wizard.container_order167 if container in wizard.config['General']['containers']]168 return render_template(template,169 menu_options=wizard.get_available_options(),170 current_container=container,171 samples=samples,172 complete_samples=complete_samples,173 security=requirements,174 complete_requirements=complete_requirements,175 complete_configuration=complete_configuration,176 containers=my_containers,177 **kwargs)178@app.route('/configure')179@app.route('/configure/<string:container>')180def configure_containers(container=None):181 return _render_configure_template('configure_containers.html',182 container)183@app.route('/configure_file/<string:container>/<path:file_name>')184def configure_container_file(container, file_name):185 final_file = file_name[:-7]186 if os.path.exists(final_file):187 warn = 'File Already exists, editing'188 load_name = final_file189 else:190 warn = 'Using sample file'191 load_name = file_name192 with open(load_name) as f:193 file_contents = f.read()194 with open(file_name + '.doc') as d:195 documentation = d.read()196 return _render_configure_template('configure_container_file.html',197 container,198 file_name=file_name,199 file_contents=file_contents,200 documentation=documentation,201 warn=warn)202@app.route('/process_file', methods=['POST'])203def process_file():204 container = request.form['container']205 file_name = request.form['file_name']206 file_contents = request.form['file_contents'].replace('\r', '')207 # html textareas newlines are DOS, thus the replace208 final_file = '_instance/' + file_name[:-7]209 wizard.make_instance_directory(final_file)210 operation = request.form['operation']211 if operation == 'save':212 with open(final_file, 'wt') as w:213 w.write(file_contents)214 wizard.link_existing_configuration(final_file)215 warn = 'File Saved'216 elif operation == 'reload':217 warn = 'Sample reloaded'218 with open(file_name) as f:219 file_contents = f.read()220 else:221 warn = 'Unknown operation'222 return _render_configure_template('configure_container_file.html',223 container,224 file_name=file_name,225 file_contents=file_contents,226 warn=warn)227def _configure_ca(container):228 return _render_configure_template(229 'configure_containers.html', container,230 warn='Certificate Authorithy already configured')231@app.route('/create_ssl/<string:container>', methods=['POST'])232def configure_ssl(container):233 form = _delist(request.form)234 if _has_all_parameters(form, ['country', 'state', 'locality',235 'orgname', 'orgunit', 'commonname',236 'email']):237 ssl_config = _ssl_template.format(**form)238 ssl_ok = ca.create_ssl('/etc/%s' % container, ssl_config)239 if ssl_ok:240 try:241 os.mkdir('etc/%s' % container)242 except:243 pass # Already exists, that is fine244 shutil.move('etc/ca/privkey.pem', 'etc/%s/ssl.key.pem' % container)245 shutil.move('etc/ca/newcert.pem',246 'etc/%s/ssl.cert.pem' % container)247 return redirect(url_for('configure_containers'))248 return render_template('ssl_not_created.html',249 menu_options=wizard.get_available_options())250 return _configure_ssl(container)251def _configure_ssl(container):252 return _render_configure_template(253 'configure_ssl.html', container=container,254 already_created=wizard.is_ssl_configured(container),255 country=wizard.config['General']['country'],256 state=wizard.config['General']['state'],257 locality=wizard.config['General']['locality'],258 orgname=wizard.config['General']['orgname'],259 orgunit=wizard.config['General']['orgunit'],260 email=wizard.config['General']['email'])261@app.route('/configure_requirements/<string:container>/<string:requirement>')262def configure_requirements(container, requirement):263 if requirement == 'ca':264 return _configure_ca(container)265 elif requirement == 'ssl':266 return _configure_ssl(container)267@app.route('/generate')268def generate_configuration():269 wizard.generate_configuration()270 return render_template('generate_configuration.html',271 container_confs=wizard.requirements,272 menu_options=wizard.get_available_options())273@app.route('/deploy')274def deploy_configuration():275 wizard.deploy_on_volumes()276 return render_template('deployment.html',277 container_confs=wizard.requirements,278 menu_options=wizard.get_available_options())279@app.route('/check_deployment')280def check_deployment():281 checkup = wizard.check_deployment()282 return render_template('check_deployment.html',283 checkup=checkup,284 container_confs=wizard.requirements,285 menu_options=wizard.get_available_options())286if __name__ == "__main__":287 app.debug = True...
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!!