def render_template(self, file_path, **kwargs): """ Render template. :param file_path: Path to template file. :param **kwargs: Template vars """ tmpl = None if file_path.endswith('_tmpl'): _path = file_path.replace('_tmpl', '') os.rename(file_path, _path) file_path = _path #: Template variable {{foo}} with open(file_path, 'r') as f: tmpl = f.read() for k, v in iteritems(kwargs): #: Equivalent to `{{%s}} % k`. #: Should use String.template? var = '{{{}}}'.format(k) tmpl = tmpl.replace('{{{0}}}'.format(var), v) if tmpl is None: return with open(file_path, 'w') as f: f.write(tmpl)
def render_template(self, file_path, **kwargs): """ Render template. :param file_path: Path to template file. :param **kwargs: Template vars """ tmpl = None if file_path.endswith('_tmpl'): _path = file_path.replace('_tmpl', '') os.rename(file_path, _path) file_path = _path #: Template variable {{foo}} with open(file_path, 'r') as f: tmpl = f.read() for k, v in iteritems(kwargs): #: Equivalent to `{{%s}} % k`. #: Should use String.template? var = '{{{}}}'.format(k) tmpl = tmpl.replace('{{{0}}}'.format(var), v) if tmpl is None: return with open(file_path, 'w') as f: f.write(tmpl)
def _process_ajax_references(self): result = {} if self.form_ajax_refs: for name, options in iteritems(self.form_ajax_refs): if isinstance(options, dict): result[name] = self._create_ajax_loader(name, options) elif isinstance(options, AjaxModelLoader): result[name] = options else: raise ValueError('%s.form_ajax_refs can not handle %s types' % (self, type(options))) return result
def get_list_form(self): if self.form_args: # get only validators, other form_args can break FieldList wrapper validators = dict( (key, {'validators': value["validators"]}) for key, value in iteritems(self.form_args) if value.get("validators") ) else: validators = None return self.scaffold_list_form(validators=validators)
def __init__(self, **kwargs): for k in self._defaults: if not hasattr(self, k): setattr(self, k, None) for k, v in iteritems(kwargs): setattr(self, k, v) form_rules = getattr(self, 'form_rules', None) if form_rules: self._form_rules = rules.RuleSet(self, form_rules) else: self._form_rules = None
def create_editable_list_form(form_base_class, form_class, widget=None): if widget is None: widget = XEditableWidget() class ListForm(form_base_class): list_form_pk = HiddenField(validators=[InputRequired()]) for name, obj in iteritems(form_class.__dict__): obj.kwargs['widget'] = widget setattr(ListFor, name, obj) if name == 'list_form_pk': raise Exception('Form already has a list_form_pk column.') return ListForm
def _validate_form_class(self, ruleset, form_class, remove_missing=True): form_fields = [] for name, obj in iteritems(form_class.__dict__): if isinstance(obj, UnboundField): form_fields.append(name) missing_fields = [] if ruleser: visible_fields = ruleset.visible_fields for field_name in form_fields: if field_name not in visible_fields: missing_fields.append(field_name) if missing_fields: self._show_missing_fields_warning('Fields missing from ruleset: %s' % (','.join(missing_fields))) if remove_missing: self._remove_fields_from_form_class(missin, form_class)
def _connect(self): "Create a TCP socket connection" # we want to mimic what socket.create_connection does to support # ipv4/ipv6, but we want to set options prior to calling # socket.connect() err = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): family, socktype, proto, canonname, socket_address = res sock = None try: sock = socket.socket(family, socktype, proto) # TCP_NODELAY sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # TCP_KEEPALIVE if self.socket_keepalive: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) for k, v in iteritems(self.socket_keepalive_options): sock.setsockopt(socket.SOL_TCP, k, v) # set the socket_connect_timeout before we connect sock.settimeout(self.socket_connect_timeout) # connect sock.connect(socket_address) # set the socket_timeout now that we're connected sock.settimeout(self.socket_timeout) return sock except socket.error as _: err = _ if sock is not None: sock.close() if err is not None: raise err raise socket.error("socket.getaddrinfo returned an empty list")
def _export_data(self): for col, func in iteritems(self.column_formatters_export): if col not in [col for col, _ in self._export_columns]: continue if func.__name__ == 'inner': raise NotImplementedError( 'Macros are not implemented in export. Exclude column in' ' column_formatters_export, column_export_list, or ' ' column_export_exclude_list. Column: %s' % (col,) ) view_args = self._get_list_extra_args() sort_column = self._get_column_by_idx(view_args.sort) if sort_column is not None: sort_column = sort_column[0] count, data = self.get_list(0, sort_column, view_args.sort_desc, view_args.search, view_args.filters, page_size=self.export_max_rows) return count, data
def flash_errors(form, message): for field_name, errors in iteritems(form.errors): errors = form[field_name].label.text + u": " + u", ".join(errors) flash(str(errors), 'error')
def func(self, *args, **kwargs): args = _escape_argspec(list(args), enumerate(args), self.escape) _escape_argspec(kwargs, iteritems(kwargs), self.escape) return self.__class__(orig(self, *args, **kwargs))
'BaseResponse', 'BaseRequest', 'Request', 'Response', 'AcceptMixin', 'ETagRequestMixin', 'ETagResponseMixin', 'ResponseStreamMixin', 'CommonResponseDescriptorsMixin', 'UserAgentMixin', 'AuthorizationMixin', 'WWWAuthenticateMixin', 'CommonRequestDescriptorsMixin' ], 'werkzeug.security': ['generate_password_hash', 'check_password_hash'], # the undocumented easteregg ;-) 'werkzeug._internal': ['_easteregg'] } # modules that should be imported when accessed as attributes of werkzeug attribute_modules = frozenset(['exceptions', 'routing', 'script']) object_origins = {} for module, items in iteritems(all_by_module): for item in items: object_origins[item] = module class module(ModuleType): """Automatically import objects from the modules.""" def __getattr__(self, name): if name in object_origins: module = __import__(object_origins[name], None, None, [name]) for extra_name in all_by_module[module.__name__]: setattr(self, extra_name, getattr(module, extra_name)) return getattr(module, name) elif name in attribute_modules: __import__('werkzeug.' + name) return ModuleType.__getattribute__(self, name)
def from_url(cls, url, db=None, decode_components=False, **kwargs): """ Return a connection pool configured from the given URL. For example:: redis://[:password]@localhost:6379/0 rediss://[:password]@localhost:6379/0 unix://[:password]@/path/to/socket.sock?db=0 Three URL schemes are supported: - ```redis://`` <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a normal TCP socket connection - ```rediss://`` <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a SSL wrapped TCP socket connection - ``unix://`` creates a Unix Domain Socket connection There are several ways to specify a database number. The parse function will return the first specified option: 1. A ``db`` querystring option, e.g. redis://localhost?db=0 2. If using the redis:// scheme, the path argument of the url, e.g. redis://localhost/0 3. The ``db`` argument to this function. If none of these options are specified, db=0 is used. The ``decode_components`` argument allows this function to work with percent-encoded URLs. If this argument is set to ``True`` all ``%xx`` escapes will be replaced by their single-character equivalents after the URL has been parsed. This only applies to the ``hostname``, ``path``, and ``password`` components. Any additional querystring arguments and keyword arguments will be passed along to the ConnectionPool class's initializer. The querystring arguments ``socket_connect_timeout`` and ``socket_timeout`` if supplied are parsed as float values. The arguments ``socket_keepalive`` and ``retry_on_timeout`` are parsed to boolean values that accept True/False, Yes/No values to indicate state. Invalid types cause a ``UserWarning`` to be raised. In the case of conflicting arguments, querystring arguments always win. """ url_string = url url = urlparse(url) qs = '' # in python2.6, custom URL schemes don't recognize querystring values # they're left as part of the url.path. if '?' in url.path and not url.query: # chop the querystring including the ? off the end of the url # and reparse it. qs = url.path.split('?', 1)[1] url = urlparse(url_string[:-(len(qs) + 1)]) else: qs = url.query url_options = {} for name, value in iteritems(parse_qs(qs)): if value and len(value) > 0: parser = URL_QUERY_ARGUMENT_PARSERS.get(name) if parser: try: url_options[name] = parser(value[0]) except (TypeError, ValueError): warnings.warn( UserWarning( "Invalid value for `%s` in connection URL." % name)) else: url_options[name] = value[0] if decode_components: password = unquote(url.password) if url.password else None path = unquote(url.path) if url.path else None hostname = unquote(url.hostname) if url.hostname else None else: password = url.password path = url.path hostname = url.hostname # We only support redis:// and unix:// schemes. if url.scheme == 'unix': url_options.update({ 'password': password, 'path': path, 'connection_class': UnixDomainSocketConnection, }) else: url_options.update({ 'host': hostname, 'port': int(url.port or 6379), 'password': password, }) # If there's a path argument, use it as the db argument if a # querystring value wasn't specified if 'db' not in url_options and path: try: url_options['db'] = int(path.replace('/', '')) except (AttributeError, ValueError): pass if url.scheme == 'rediss': url_options['connection_class'] = SSLConnection # last shot at the db value url_options['db'] = int(url_options.get('db', db or 0)) # update the arguments from the URL values kwargs.update(url_options) # backwards compatability if 'charset' in kwargs: warnings.warn( DeprecationWarning( '"charset" is deprecated. Use "encoding" instead')) kwargs['encoding'] = kwargs.pop('charset') if 'errors' in kwargs: warnings.warn( DeprecationWarning( '"errors" is deprecated. Use "encoding_errors" instead')) kwargs['encoding_errors'] = kwargs.pop('errors') return cls(**kwargs)
def populate_obj(self, obj, name): for name, field in iteritems(self.form._fields): if name != self._pk: field.populate_obj(obj, name)