How to use request_vars method in tavern

Best Python code snippet using tavern

chimitheque_multiple_widget.py

Source:chimitheque_multiple_widget.py Github

copy

Full Screen

1# -*- coding: utf-8; -*-2#3# (c) 2011-2015 Thomas Bellembois thomas.bellembois@ens-lyon.fr4#5# This file is part of Chimithèque.6#7# Chimithèque is free software; you can redistribute it and/or modify8# it under the terms of the Cecill as published by the CEA, CNRS and INRIA9# either version 2 of the License, or (at your option) any later version.10#11# Chimithèque is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU General Public License for more details.15#16# You should have received a copy of the Cecill along with Chimithèque.17# If not, see <http://www.cecill.info/licences/>.18#19# SVN Revision:20# -------------21# $Id: chimitheque_multiple_widget.py 210 2015-05-11 08:46:57Z tbellemb $22#23import base6424import json25import re26from types import ListType27from chimitheque_logger import chimitheque_logger28from fake import *29mylogger = chimitheque_logger()30def lambdaempiricalformula(formula):31 existing_atoms = sorted(current.settings['atom_array'].keys(), key=lambda atom: len(atom), reverse=True)32 regex = '(' + '|'.join([_atom + '[0-9]*' for _atom in existing_atoms]) + ')'33 mylogger.debug(message='regex:%s' % regex)34 return '%%'.join([_atom for _atom in filter(lambda v: v != '', re.split(regex, formula))])35def lambdaname(label):36 return label.replace('-', '_')37def item_add():38 # getting request vars and keys39 request_vars = request.vars # a Gluon.storage.Storage object40 mylogger.debug(message='request_vars:%s' %request_vars)41 # getting the request vars42 uid = request_vars['uid']43 multiple = request_vars['multiple']44 field_tablename = request_vars['field_tablename']45 ref_field_tablename = request_vars['ref_field_tablename']46 ref_field_name = request_vars['ref_field_name']47 search = request_vars['search'].strip()48 mylogger.debug(message='search:%s' %search)49 mylogger.debug(message='type(search):%s' %type(search))50 mylogger.debug(message='ref_field_tablename:%s' % ref_field_tablename)51 mylogger.debug(message='ref_field_name:%s' % ref_field_name)52 is_not_a_reference = (field_tablename == ref_field_tablename)53 if search == '':54 return ''55 _requires = db['%s' %ref_field_tablename]['%s' % ref_field_name].requires56 mylogger.debug(message='_requires:%s' % _requires)57 (value, error) = db['%s' %ref_field_tablename]['%s' %ref_field_name].validate(search.encode('utf8'))58 value = value.decode('utf-8')59 value = value.replace("'", "\'")60 mylogger.debug(message='value:%s' % value)61 mylogger.debug(message='error:%s' % error)62 if error:63 mylogger.debug(message='error')64 return DIV('',65 SCRIPT("""66 jQuery(function() {67 displayMessage%s('%s');68 });69 """ %(uid, '%s: %s insert -> %s' %('ERROR', value, error))))70 elif not is_not_a_reference:71 mylogger.debug(message='no error')72 search = value73 try:74 db['%s' %ref_field_tablename].bulk_insert([{'%s' %ref_field_name: value}])75 except:76 mylogger.debug(message='exception catch bulk_insert')77 return DIV('',78 SCRIPT("""79 jQuery(function() {80 displayMessage%s('%s');81 });82 """ %(uid, '%s: %s bulk_insert -> %s' %('ERROR', value, error))))83 row = db((db['%s' %ref_field_tablename]['%s' %ref_field_name] == value)).select().first()84 mylogger.debug(message='row:%s' %row)85 inserted_id = row['id']86 inserted_val = db['%s' %ref_field_tablename]._format(row)87 else:88 inserted_id = value89 inserted_val = value90 mylogger.debug(message='type(inserted_val):%s' %type(inserted_val)) # <type 'str'>91 inserted_val = inserted_val.decode('utf-8')92 mylogger.debug(message='inserted_val:%s' %inserted_val)93 #inserted_val = inserted_val.replace("'", "\\'")94 if multiple:95 action = 'add'96 else:97 action = 'replace'98 return json.dumps({'action': action,99 'id': inserted_id,100 'val': base64.b64encode(inserted_val.encode('utf-8')),101 'encval': uid})102def item_selector():103 # getting request vars and keys104 request_vars = request.vars # a Gluon.storage.Storage object105 mylogger.debug(message='request_vars:%s' %request_vars)106 # getting the request vars107 uid = request_vars['uid']108 multiple = request_vars['multiple']109 disable_validate = request_vars['disable_validate']110 field_tablename = request_vars['field_tablename']111 ref_field_tablename = request_vars['ref_field_tablename']112 ref_field_name = request_vars['ref_field_name']113 search = request_vars['search'].strip()114 max_nb_item = int(request_vars['max_nb_item'])115 max_item_length = int(request_vars['max_item_length'])116 func_lambda = request_vars['lambda']117 text_close_list = request_vars['text_close_list']118 text_submit = request_vars['text_submit'],119 image_select_url = request_vars['image_select_url']120 submit_on_select = request_vars['submit_on_select']121 is_not_a_reference = (field_tablename == ref_field_tablename)122 mylogger.debug(message='search:%s' % search)123 mylogger.debug(message='type(search):%s' % type(search)) # Unicode here124 mylogger.debug(message='field_tablename:%s' % field_tablename)125 mylogger.debug(message='ref_field_tablename:%s' % ref_field_tablename)126 mylogger.debug(message='ref_field_name:%s' % ref_field_name)127 mylogger.debug(message='is_not_a_reference:%s' % is_not_a_reference)128 mylogger.debug(message='submit_on_select:%s' % submit_on_select)129 # search var empty = return130 if search == '':131 return ''132 # validating the entry133 error = False134 if not disable_validate:135 _requires = db['%s' %ref_field_tablename]['%s' %ref_field_name].requires136 mylogger.debug(message='_requires:%s' %_requires)137 # removing IS_NOT_IN_DB if present138 # we do not want to throw an error if the value is not in DB139 # note: this procedure will not work with recursive validators140 if type(_requires) is not ListType:141 _requires = [_requires]142 _new_requires = []143 is_in_db = False144 for _require in _requires:145 mylogger.debug(message='type(_require):%s' %type(_require))146 if not isinstance(_require, IS_NOT_IN_DB):147 mylogger.debug(message='_require not IS_NOT_IN_DB')148 _new_requires.append(_require)149 # validating150 mylogger.debug(message='_new_requires:%s' %_new_requires)151 db['%s' %ref_field_tablename]['%s' %ref_field_name].requires = _new_requires152 (search, error) = db['%s' %ref_field_tablename]['%s' %ref_field_name].validate(search.encode('utf8'))153 search = search.decode('utf-8')154 error = error.decode('utf-8') if error is not None else None155 mylogger.debug(message='type(search):%s' % type(search))156 mylogger.debug(message='type(error):%s' % type(error))157 mylogger.debug(message='search:%s' % search)158 mylogger.debug(message='error:%s' % error)159 if error:160 return '%s: %s -> %s' % ('ERROR', search, error)161 else:162 #mylogger.debug(message='search:%s' %search)163 # calling lambda164 if func_lambda != '':165 search = eval(func_lambda)(search)166 mylogger.debug(message='search:%s' %search)167 # search already in DB ?168 _count = db(db['%s' %ref_field_tablename]['%s' %ref_field_name] == '%s' %search).count()169 mylogger.debug(message='_count:%s' %_count)170 is_in_db = _count != 0171 # requesting the DB172 suggestions = []173 _search = search.lower()174 mylogger.debug(message='_search:%s' %_search)175 mylogger.debug(message='type(_search):%s' %type(_search))176 req1 = db(177 (db['%s' %ref_field_tablename]['%s' %ref_field_name].lower().like('%s%%' %_search))).select(orderby=ref_field_name, limitby=(0, max_nb_item))178 req2 = db(179 (db['%s' %ref_field_tablename]['%s' %ref_field_name].lower().like('%%%s%%' %_search))).select(orderby=ref_field_name, limitby=(0, max_nb_item))180 req3 = db(181 (db['%s' %ref_field_tablename]['%s' %ref_field_name].lower().like('%%|%%%s%%|%%' %_search))).select(orderby=ref_field_name, limitby=(0, max_nb_item))182 for _req in req1:183 _suggestion = db['%s' %ref_field_tablename]._format(_req)184 #185 # backward compatibility: some entries may have been stored with different encodings ISO-8859-1 ISO-8859-2 windows-1250...186 # so we utf8 decode the entry with the errors='replace' to get a pure Unicode object187 #188 _suggestion = _suggestion.decode('utf8', errors='replace')189 suggestion_txt = suggestion_txt_small = _suggestion190 if len(suggestion_txt) > max_item_length:191 suggestion_txt_small = suggestion_txt[0:max_item_length] + '...'192 suggestions.append((_req.id, suggestion_txt, suggestion_txt_small))193 for _req in req2:194 if _req.id not in [suggestion[0] for suggestion in suggestions]:195 _suggestion = db['%s' %ref_field_tablename]._format(_req)196 _suggestion = _suggestion.decode('utf8', errors='replace')197 suggestion_txt = suggestion_txt_small = _suggestion198 if len(suggestion_txt) > max_item_length:199 suggestion_txt_small = suggestion_txt[0:max_item_length] + '...'200 suggestions.append((_req.id, suggestion_txt, suggestion_txt_small))201 for _req in req3:202 if _req.id not in [suggestion[0] for suggestion in suggestions]:203 _suggestion = db['%s' %ref_field_tablename]._format(_req)204 _suggestion = _suggestion.decode('utf8', errors='replace')205 suggestion_txt = suggestion_txt_small = _suggestion206 if len(suggestion_txt) > max_item_length:207 suggestion_txt_small = suggestion_txt[0:max_item_length] + '...'208 suggestions.append((_req.id, suggestion_txt, suggestion_txt_small))209 mylogger.debug(message='suggestions:%s' %suggestions)210 if len(suggestions) == 0:211 return 'NONE:%s' % search.encode('utf-8')212 else:213 close_list = A(text_close_list, _onclick="""214 $('input[name=%s_search]').attr('value', '');215 $('#%s_suggestions div').remove();216 """ %(uid, uid)) + BR()217 if multiple:218 action = 'add'219 else:220 action = 'replace'221 if is_in_db:222 script = SCRIPT("""223 disableAddButton%s();224 """ % uid)225 else:226 script = SCRIPT("")227 suggestion_list = DIV(close_list,228 script,229 _id='suggestions_list')230 for _suggestion in suggestions:231 _onclick = """232 jQuery(function() {233 addReplaceCheckBox%(uid)s("%(action)s", "%(id)s", "%(val)s", "%(encval)s");234 """ % { 'uid': uid,235 'action': action,236 'id': search if is_not_a_reference else _suggestion[0],237 'val': base64.b64encode(_suggestion[1].encode('utf-8')),238 'encval': uid}239 if submit_on_select:240 _onclick = _onclick + """241 $('#%s').closest("form").submit();242 });243 """ % uid244 else:245 _onclick = _onclick + """246 });247 """248 suggestion_list.append(DIV(_suggestion[2],249 IMG(_src=image_select_url,250 _alt=text_submit,251 _title=_suggestion[1]),252 _onclick=_onclick,253 _class='CHIMITHEQUE_MULTIPLE_widget_suggestion'))...

Full Screen

Full Screen

disco_api.py

Source:disco_api.py Github

copy

Full Screen

1# copyright (c) 2016 Industrial Technology Research Institute.2# All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License"); you may5# not use this file except in compliance with the License. You may obtain6# a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13# License for the specific language governing permissions and limitations14# under the License.15"""DISCO Backup Service Implementation."""16import json17import requests18import six19class DiscoApi(object):20 """Class for all the requests to Disco API."""21 def __init__(self, ip, port):22 """Init client."""23 # Rest related variables24 self.req_headers = {'Content-type': 'application/json'}25 prefix_vars = {'server_ip': ip,26 'server_port': port,27 'api_prefix': 'RM-REST-Server/disco'}28 self.request_prefix = ("http://%(server_ip)s:%(server_port)s"29 "/%(api_prefix)s") % prefix_vars30 self.prefix_var = {'req_prefix': self.request_prefix}31 def volumeCreate(self, volume_name, size):32 """Create a DISCO volume."""33 params = {'volumeName': volume_name, 'volumeSize': size,34 'backupPolicyId': -1}35 data = json.dumps(params,36 sort_keys=True,37 indent=4,38 separators=(',', ': '))39 request = ("%(req_prefix)s/volume" % self.prefix_var)40 r = requests.post(request, data, headers=self.req_headers)41 return r.json()42 def volumeDelete(self, volume_id):43 """Delete the temporary volume."""44 request_vars = {'req_prefix': self.request_prefix,45 'volume_id': six.text_type(volume_id)}46 request = ("%(req_prefix)s/volume/%(volume_id)s") % request_vars47 r = requests.delete(request)48 return r.json()49 def volumeExtend(self, vol_id, size):50 """Extend DISCO volume."""51 params = {'volumeSize': six.text_type(size),52 'volumeId': six.text_type(vol_id)}53 data = json.dumps(params,54 sort_keys=True,55 indent=4,56 separators=(',', ': '))57 request = ("%(req_prefix)s/volume/extend" % self.prefix_var)58 r = requests.put(request, data, headers=self.req_headers)59 return r.json()60 def volumeDetail(self, volume_id):61 """Get volume information of the destination DISCO volume."""62 request_vars = {'req_prefix': self.request_prefix,63 'vol_id': six.text_type(volume_id)}64 request = ("%(req_prefix)s/volume/%(vol_id)s") % request_vars65 r = requests.get(request)66 volume_info = r.json()67 return volume_info68 def volumeDetailByName(self, volume_name):69 """Get volume information of the DISCO volume."""70 request_vars = {'req_prefix': self.request_prefix,71 'volume_name': six.text_type(volume_name)}72 request = ("%(req_prefix)s/volume?name=%(volume_name)s") % request_vars73 r = requests.get(request)74 return r.json()75 def volumeClone(self, volume_id, volume_name):76 """Clone a DISCO volume."""77 params = {'volumeName': volume_name, 'volumeId': volume_id}78 data = json.dumps(params,79 sort_keys=True,80 indent=4,81 separators=(',', ': '))82 request = ("%(req_prefix)s/clone" % self.prefix_var)83 r = requests.post(request, data, headers=self.req_headers)84 return r.json()85 def cloneDetail(self, clone_id, clone_name):86 """Get detail of the clone."""87 request_vars = {'req_prefix': self.request_prefix,88 'clone_name': clone_name,89 'clone_id': six.text_type(clone_id)}90 request = ("%(req_prefix)s/clone?cloneId=%(clone_id)s&"91 "name=%(clone_name)s") % request_vars92 r = requests.get(request)93 return r.json()94 def snapshotCreate(self, disco_volume_id, reserve_days, zone_id=None,95 description=None):96 """Take a snapshot of the volume."""97 params = {'volumeId': disco_volume_id,98 'reserveDays': reserve_days,99 'description': description}100 data = json.dumps(params, sort_keys=True, indent=4,101 separators=(',', ': '))102 request = ("%(req_prefix)s/snapshot" % self.prefix_var)103 r = requests.post(request, data, headers=self.req_headers)104 return r.json()105 def snapshotDelete(self, snapshot_id):106 """Delete a snapshot."""107 request_vars = {'req_prefix': self.request_prefix,108 'snapshot_id': six.text_type(snapshot_id)}109 request = ("%(req_prefix)s/snapshot/%(snapshot_id)s") % request_vars110 r = requests.delete(request)111 return r.json()112 def snapshotDetail(self, snapshot_id):113 """Monitor end of the snapshot."""114 request_vars = {'req_prefix': self.request_prefix,115 'snapshot_id': snapshot_id}116 request = ("%(req_prefix)s/snapshot/%(snapshot_id)s") % request_vars117 r = requests.get(request)118 return r.json()119 def restoreFromSnapshot(self, snapshot_id, volume_name, zone_id,120 description, volume_id):121 """restore a snapshot of into a volume."""122 params = {'snapshotId': snapshot_id,123 'volumeName': volume_name,124 'zone_id': zone_id,125 'description': "local restore snapshot",126 'volumeId': volume_id}127 data = json.dumps(params,128 sort_keys=True,129 indent=4,130 separators=(',', ': '))131 request = ("%(req_prefix)s/restore" % self.prefix_var)132 r = requests.post(request, data, headers=self.req_headers)133 return r.json()134 def restoreDetail(self, restore_id):135 """Monitor end of the restore."""136 request_vars = {'req_prefix': self.request_prefix,137 'restore_id': restore_id}138 request = ("%(req_prefix)s/restore/%(restore_id)s") % request_vars139 r = requests.get(request)140 return r.json()141 def systemInformationList(self):142 """Get the list of the system information."""143 request = ("%(req_prefix)s/systemInformationList") % self.prefix_var144 r = requests.get(request)...

Full Screen

Full Screen

render_admin.py

Source:render_admin.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from web import template3from configuration import WEBSITE_NAME, ADMIN_VERSION4from auth import get_logged_user, get_logoff_url5from model import get_exposed_managed_tables6import os7rootpath = os.path.abspath(os.path.dirname(__file__))8admin_template_path = template.render(rootpath + '/templates/admin', cache=False)9def layout(content):10 usuario = get_logged_user()11 if usuario:12 render_vars = {'website_name': WEBSITE_NAME, 'version': ADMIN_VERSION, 'user': get_logged_user(), 'logoff_url': get_logoff_url(), 'exposed_managed_tables': get_exposed_managed_tables(usuario.nivel_acesso)}13 else:14 render_vars = {'website_name': WEBSITE_NAME, 'version': ADMIN_VERSION, 'user': get_logged_user(), 'logoff_url': get_logoff_url(), 'exposed_managed_tables': []}15 return admin_template_path.admin(render_vars, content)16def index_admin():17 return admin_template_path.index_admin()18def form(request_vars):19 request_vars['method'] = 'post'20 request_vars['action'] = ''21 if request_vars['in_moderation_mode'] == 'yes':22 request_vars['display_message'] = 'Em Moderação - Visualizando Registro !'23 return admin_template_path.moderate_form(request_vars)24 else:25 return admin_template_path.form(request_vars)26def form_update(request_vars):27 request_vars['method'] = 'post'28 request_vars['action'] = ''29 return admin_template_path.form_update(request_vars)30def listar(request_vars):31 filtro = ''32 if request_vars['pagination'].query is not None and request_vars['pagination'].query != 'None' and request_vars['pagination'].query != 'all' and request_vars['pagination'].query != '':33 query = request_vars['pagination'].query34 if query == "status='A'":35 query = 'Approved'36 elif query == "status='W'":37 query = 'Waiting'38 elif query == "status='R'":39 query = 'Refused'40 elif query == "locked='S'":41 query = 'Em Edição'42 filtro = 'Filtrando por: %(query)s' % {'query': query}43 request_vars['filtro'] = filtro44 return admin_template_path.lista(request_vars)45def moderar(request_vars):46 if request_vars['pagination'].query is not None and request_vars['pagination'].query != 'None' and request_vars['pagination'].query != 'all' and request_vars['pagination'].query != '':47 query = request_vars['pagination'].query48 if query == "acao='A'":49 query = 'Approved'50 elif query == "acao='R'":51 query = 'Refused'52 request_vars['filtro'] = 'Filtrando por: %(query)s' % {'query': query}53 return admin_template_path.modera(request_vars)54"""55def moderar(frm, pagination, display_message=None):56 filtro = ''57 if pagination.query is not None and pagination.query != 'None' and pagination.query != 'all' and pagination.query != '':58 query = pagination.query59 if query == "acao='A'":60 query = 'Approved'61 elif query == "acao='R'":62 query = 'Refused'63 filtro = 'Filtrando por: %(query)s' % {'query': query}64 return admin_template_path.modera(frm, filtro, pagination, display_message)65"""66def login(**d):67 error = d.pop('error', '')68 return admin_template_path.login(error)69def show_template(param):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tavern automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful