def product(product_id): print(product_id) user = session.get('user') if (request.method == "GET"): if (user): store_result = db.get_active_store(user["id"]) p = db.get_product(store_result["data"]["id"], product_id) return render_template('product.html', product=p["data"], user=user) else: return redirect(url_for('index')) else: if (user): title = validators.string(request.form.get("title")) price = validators.string(request.form.get("price")) stock = validators.string(request.form.get("stock")) product = shopifyctrl.get_product(product_id) product.title = title product.price = float(price) product.variants[0].inventory_quantity = int(stock) # product.save() result = db.update_product(product_id, product) return redirect(url_for("product/" + product_id)) else: return redirect(url_for('index'))
def store(): user = session.get('user') if (request.method == "GET"): if (user): return render_template('store.html', user=user) else: return redirect(url_for('index')) else: if (user): user_id = user["id"] try: store_name = validators.string(request.form.get("store_name")) store_address = validators.string( request.form.get("store_address")) store_api_key = validators.string( request.form.get("store_api_key")) store_password = validators.string( request.form.get("store_password")) except: return render_template("store.html", err="datas not valid") result = db.new_store(user_id, store_name, store_address, store_api_key, store_password) if (result["err"]): return render_template("store.html", err=result["err"]) else: return redirect(url_for("account")) else: return redirect(url_for("index"))
def start(self, args: OrderedDict) -> None: key = validators.string(args["key"]) config_path = validators.string(args["config"]) self.logger.info("Starting %s.", key) config_file = Path(abspath(config_path)) print(f"Loading configuration from {config_file}.") if config_file.exists(): with open(config_file) as f: config = Configuration() config.from_dict(json.load(f)) features = filter(lambda c: isinstance(c, Feature), self.components) for feature in features: self.logger.info("Configuring feature %s.", type(feature).__name__) # noinspection PyBroadException try: cast(Feature, feature).config(config) except BaseException as e: self.logger.error("Failed to initialise feature.", exc_info=e) def except_hook(tpe, value, traceback): if tpe != KeyboardInterrupt: self.logger.exception("Unhandled error occurred:", exc_info=value, stack_info=traceback) sys.__excepthook__(tpe, value, traceback) # noinspection SpellCheckingInspection sys.excepthook = except_hook for callback in _initializers: try: callback() except Exception as e: self.logger.exception(e, exc_info=True) global _initialized _initialized = True _initializers.clear() self.logger.info("Bootstrap has completed successfully.")
def parse_json(input_data, deserialize_function=None, **kwargs): """De-serialize JSON data into a Python :class:`dict <python:dict>` object. :param input_data: The JSON data to de-serialize. :type input_data: :class:`str <python:str>` :param deserialize_function: Optionally override the default JSON deserializer. Defaults to :obj:`None <python:None>`, which calls the default :ref:`simplejson.loads() <simplejson:simplejson.loads>` function from the `simplejson <https://github.com/simplejson/simplejson>`_ library. .. note:: Use the ``deserialize_function`` parameter to override the default YAML deserializer. A valid ``deserialize_function`` is expected to accept a single :class:`str <python:str>` and return a :class:`dict <python:dict>`, similar to :ref:`simplejson.loads() <simplejson:simplejson.loads>` If you wish to pass additional arguments to your ``deserialize_function`` pass them as keyword arguments (in ``kwargs``). :type deserialize_function: callable / :obj:`None <python:None>` :param kwargs: Optional keyword parameters that are passed to the JSON deserializer function. By default, these are options which are passed to :ref:`simplejson.loads() <simplejson:simplejson.loads>`. :type kwargs: keyword arguments :returns: A :class:`dict <python:dict>` representation of ``input_data``. :rtype: :class:`dict <python:dict>` """ is_file = False if checkers.is_file(input_data): is_file = True if deserialize_function is None and not is_file: deserialize_function = json.loads elif deserialize_function is None and is_file: deserialize_function = json.load else: if checkers.is_callable(deserialize_function) is False: raise ValueError('deserialize_function (%s) is not callable' % deserialize_function) if not input_data: raise DeserializationError('input_data is empty') if not is_file: try: input_data = validators.string(input_data, allow_empty=False) except ValueError: raise DeserializationError('input_data is not a valid string') from_json = deserialize_function(input_data, **kwargs) else: with open(input_data, 'r') as input_file: from_json = deserialize_function(input_file, **kwargs) return from_json
def measure(self, value): value = validators.string(value, allow_empty = False) value = value.lower() if value not in [member.value for name, member in VariableMeasureEnum.__members__.items()]: raise ValueError(f'value ({value}) is not a recognized measure') self._measure = value
def value_metadata(self, value): value = validators.dict(value, allow_empty = True) if not value: self._value_metadata = None else: self._value_metadata = { key: validators.string(value[key], allow_empty = True) for key in value }
def alignment(self, value): value = validators.string(value, allow_empty = False) value = value.lower() if value not in [member.value for name, member in VariableAlignmentEnum.__members__.items()]: raise ValueError(f'value ({value}) is not a recognized alignment') self._alignment = value
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if value is None: return False minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs) maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs) if isinstance(value, basestring) and not value: if minimum_length and minimum_length > 0 and not whitespace_padding: return False return True try: value = validators.string(value, coerce_value = coerce_value, minimum_length = minimum_length, maximum_length = maximum_length, whitespace_padding = whitespace_padding, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def video_capture_source(self, val: (str, int, None)): try: self._video_capture_source = validators.integer( val, coerce_value=True, allow_empty=True ) except TypeError: self._video_capture_source = validators.string( val, allow_empty=True )
def from_bytes(value): if not isinstance(value, (bytes, io.BytesIO, io.StringIO)): value = validators.string(value, allow_empty=True) else: return value if value is None: return value return bytes(value)
def to_utf8(value): """Return a UTF-8 encoded version of ``value`` if ``value`` is a string. :returns: ``value`` if ``value`` is not a string or UTF-8 encoded :class:`str <python:str>` """ if is_py2 and checkers.is_string(value, coerce_value=True): value = validators.string(value, coerce_value=True) return value.encode("utf-8") return value
def store_with_id(store_id): user = session.get('user') if (request.method == "GET"): if (user): user_id = user["id"] result = db.get_store(user_id, store_id) store = result["data"] print(store) return render_template('store.html', user=user, store=store) else: return redirect(url_for("index")) else: if (user): user_id = user["id"] try: store_name = validators.string(request.form.get("store_name")) store_address = validators.string( request.form.get("store_address")) store_api_key = validators.string( request.form.get("store_api_key")) store_password = validators.string( request.form.get("store_password")) except: return redirect(render_template("store.html"), err="Datas not valid.") db.update_store(store_id, store_name, store_address, store_api_key, store_password) stores = db.get_store(user_id)["data"] user_result = db.get_user(user_id) return render_template("account.html", user=user_result["data"], stores=stores) else: return redirect(url_for("index"))
def parse_yaml(input_data, deserialize_function=None, **kwargs): """De-serialize YAML data into a Python :class:`dict <python:dict>` object. :param input_data: The YAML data to de-serialize. :type input_data: :class:`str <python:str>` :param deserialize_function: Optionally override the default YAML deserializer. Defaults to :obj:`None <python:None>`, which calls the default ``yaml.safe_load()`` function from the `PyYAML <https://github.com/yaml/pyyaml>`_ library. .. note:: Use the ``deserialize_function`` parameter to override the default YAML deserializer. A valid ``deserialize_function`` is expected to accept a single :class:`str <python:str>` and return a :class:`dict <python:dict>`, similar to ``yaml.safe_load()``. If you wish to pass additional arguments to your ``deserialize_function`` pass them as keyword arguments (in ``kwargs``). :type deserialize_function: callable / :obj:`None <python:None>` :param kwargs: Optional keyword parameters that are passed to the YAML deserializer function. By default, these are options which are passed to ``yaml.safe_load()``. :type kwargs: keyword arguments :returns: A :class:`dict <python:dict>` representation of ``input_data``. :rtype: :class:`dict <python:dict>` """ if deserialize_function is None: deserialize_function = yaml.safe_load else: if checkers.is_callable(deserialize_function) is False: raise ValueError('deserialize_function (%s) is not callable' % deserialize_function) if not input_data: raise DeserializationError('input_data is empty') try: input_data = validators.string(input_data, allow_empty=False) except ValueError: raise DeserializationError('input_data is not a valid string') from_yaml = yaml.safe_load(input_data, **kwargs) return from_yaml
def from_yaml(as_yaml: Union[str, 'PathLike[Any]', BytesIO], target: Optional[Union['PathLike[Any]', BytesIO]] = None, compress: bool = False, **kwargs): """Convert YAML data into an SPSS dataset. .. tip:: If you pass any additional keyword arguments, those keyword arguments will be passed onto the :meth:`DataFrame.from_dict() <pandas:pandas.DataFrame.from_dict>` method. :param as_yaml: The YAML data that you wish to convert into an SPSS dataset. :type as_yaml: :class:`str <python:str>` / File-location / :class:`BytesIO <python:io.BytesIO>` :param target: The target to which the SPSS dataset should be written. Accepts either a filename/path, a :class:`BytesIO <python:io.BytesIO>` object, or :obj:`None <python:None>`. If :obj:`None <python:None>` will return a :class:`BytesIO <python:io.BytesIO>` object containing the SPSS dataset. Defaults to :obj:`None <python:None>`. :type target: Path-like / :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>` :param compress: If ``True``, will return data in the compressed ZSAV format. If ``False``, will return data in the standards SAV format. Defaults to ``False``. :type compress: :class:`bool <python:bool>` :param kwargs: Additional keyword arguments which will be passed onto the :meth:`DataFrame.from_dict() <pandas:pandas.DataFrame.from_dict>` method. :type kwargs: :class:`dict <python:dict>` :returns: A :class:`BytesIO <python:io.BytesIO>` object containing the SPSS data if ``target`` is :obj:`None <python:None>` or not a filename, otherwise :obj:`None <python:None>` :rtype: :class:`BytesIO <python:io.BytesIO>` or :obj:`None <python:None>` """ if checkers.is_file(as_yaml) or checkers.is_bytesIO(as_yaml): file_path = as_yaml with open(file_path, 'rb') as yaml_file: as_dict = yaml.safe_load(yaml_file) else: as_yaml = validators.string(as_yaml, allow_empty=False) as_dict = yaml.safe_load(as_yaml) as_json = json.dumps(as_dict) return from_json(as_json, target=target, compress=compress, **kwargs)
def missing_value_metadata(self, value): if not value: self._missing_value_metadata = None return elif checkers.is_string(value): value = [value] elif checkers.is_numeric(value): value = [value] validated_values = [] for item in value: try: validated_item = validators.string(item, allow_empty = False) except (ValueError, TypeError): validated_item = validators.int(item, allow_empty = False) validated_values.append(validated_item) self._missing_value_metadata = validated_values
def format_to_tuple(format): """Retrieve a serialization/de-serialization tuple based on ``format``. :param format: The format to which the value should be serialized. Accepts either: ``csv``, ``json``, ``yaml``, or ``dict``. :type format: :class:`str <python:str>` :returns: A 4-member :class:`tuple <python:tuple>` corresponding to ``<direction>_csv``, ``<direction>_json``, ``<direction>_yaml``, ``<direction>_dict`` :rtype: :class:`tuple <python:tuple>` of :class:`bool <python:bool>` / :obj:`None <python:None>` :raises InvalidFormatError: if ``format`` is not ``csv``, ``json``, ``yaml``, or ``dict``. """ csv = None json = None yaml = None dict = None try: format = validators.string(format, allow_empty = False) except ValueError: raise InvalidFormatError('%s is not a valid format string' % format) format = format.lower() if format == 'csv': csv = True elif format == 'json': json = True elif format == 'yaml': yaml = True elif format == 'dict': dict = True else: raise InvalidFormatError('%s is not a valid format string' % format) return csv, json, yaml, dict
def string_validator(value, error_message='ingrese un string valido'): if value is None: return None if isinstance(value, bool): return 'True' if value else 'False' if isinstance(value, int) and value == 0: return '0' try: data_valid = validators.string(value, coerce_value=True, allow_empty=True) if data_valid is None: return '' if len(data_valid) > 10 and data_valid[0] == '<' and data_valid[ -1] == '>' and value.__class__ in data_valid: raise BadRequest(4010, 'no se puede convertir el string') except Exception as e: raise BadRequest(4010, error_message) return data_valid
def to_str(value): value = validators.string(value, allow_empty=True) return value
def label(self, value): self._label = validators.string(value, allow_empty = True)
def notes(self, value): if checkers.is_iterable(value): value = '\n'.join(value) self._notes = validators.string(value, allow_empty = True)
def file_encoding(self, value): self._file_encoding = validators.string(value, allow_empty = True)
def request(self, method, url, parameters=None, headers=None, request_body=None): """Execute a standard HTTP request. :param method: The HTTP method to use for the request. Accepts `GET`, `HEAD`, `POST`, `PATCH`, `PUT`, or `DELETE`. :type method: :class:`str <python:str>` :param url: The URL to execute the request against. :type url: :class:`str <python:str>` :param parameters: URL parameters to submit with the request. Defaults to :obj:`None <python:None>`. :type parameters: :class:`dict <python:dict>` / :obj:`None <python:None>` :param headers: HTTP headers to submit with the request. Defaults to :obj:`None <python:None>`. :type headers: :class:`dict <python:dict>` / :obj:`None <python:None>` :param request_body: The data to supply in the body of the request. Defaults to :obj:`None <python:None>`. :type request_body: :obj:`None <python:None>` / :class:`dict <python:dict>` / :class:`str <python:str>` / :class:`bytes <python:bytes>` :returns: The content of the HTTP response, the status code of the HTTP response, and the headers of the HTTP response. :rtype: :class:`tuple <python:tuple>` of :class:`bytes <python:bytes>`, :class:`int <python:int>`, and :class:`dict <python:dict>` :raises ValueError: if ``method`` is not either ``GET``, ``HEAD``, ``POST``, ``PATCH``, ``PUT`` or ``DELETE`` :raises ValueError: if ``url`` is not a valid URL :raises ValueError: if ``headers`` is not empty and is not a :class:`dict <python:dict>` :raises HTTPTimeoutError: if the request times out :raises SSLError: if the request fails SSL certificate verification :raises WalkScoreError: *or sub-classes* for other errors returned by the API """ method = validators.string(method, allow_empty=False) method = method.upper() if method not in HTTP_METHODS: raise ValueError('method (%s) not a recognized HTTP method' % method) url = validators.url(url, allow_empty=False) parameters = validators.dict(parameters, allow_empty=True) headers = validators.dict(headers, allow_empty=True) content, status_code, headers = self._request(method, url, parameters, headers, request_body) check_for_errors(status_code, content) return content, status_code, headers
def address(self, value): self._address = validators.string(value, allow_empty=True)
def transit_description(self, value): self._transit_description = validators.string(value, allow_empty=True)
def transit_summary(self, value): self._transit_summary = validators.string(value, allow_empty=True)
def _parse_csv(cls, csv_data, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character="\\", line_terminator='\r\n', config_set=None): """Generate a :class:`dict <python:dict>` from a CSV record. .. tip:: Unwrapped empty column values are automatically interpreted as null (:obj:`None <python:None>`). :param csv_data: The CSV record. Should be a single row and should **not** include column headers. :type csv_data: :class:`str <python:str>` :param delimiter: The delimiter used between columns. Defaults to ``|``. :type delimiter: :class:`str <python:str>` :param wrapper_character: The string used to wrap string values when wrapping is applied. Defaults to ``'``. :type wrapper_character: :class:`str <python:str>` :param null_text: The string used to indicate an empty value if empty values are wrapped. Defaults to `None`. :type null_text: :class:`str <python:str>` :param config_set: If not :obj:`None <python:None>`, the named configuration set to use. Defaults to :obj:`None <python:None>`. :type config_set: :class:`str <python:str>` / :obj:`None <python:None>` :returns: A :class:`dict <python:dict>` representation of the CSV record. :rtype: :class:`dict <python:dict>` :raises DeserializationError: if ``csv_data`` is not a valid :class:`str <python:str>` :raises CSVStructureError: if the columns in ``csv_data`` do not match the expected columns returned by :func:`get_csv_column_names() <BaseModel.get_csv_column_names>` :raises ValueDeserializationError: if a value extracted from the CSV failed when executing its :term:`de-serialization function`. """ try: csv_data = validators.string(csv_data, allow_empty=False) except (ValueError, TypeError): raise DeserializationError("csv_data expects a 'str', received '%s'" \ % type(csv_data)) if not wrapper_character: wrapper_character = '\'' if wrap_all_strings: quoting = csv.QUOTE_NONNUMERIC else: quoting = csv.QUOTE_MINIMAL if 'sqlathanor' in csv.list_dialects(): csv.unregister_dialect('sqlathanor') csv.register_dialect('sqlathanor', delimiter=delimiter, doublequote=double_wrapper_character_when_nested, escapechar=escape_character, quotechar=wrapper_character, quoting=quoting, lineterminator=line_terminator) csv_column_names = [ x for x in cls.get_csv_column_names( deserialize=True, serialize=None, config_set=config_set) ] csv_reader = csv.DictReader([csv_data], fieldnames=csv_column_names, dialect='sqlathanor', restkey=None, restval=None) rows = [x for x in csv_reader] if len(rows) > 1: raise CSVStructureError('expected 1 row of data, received %s' % len(csv_reader)) elif len(rows) == 0: data = dict_() for column_name in csv_column_names: data[column_name] = None else: data = rows[0] if data.get(None, None) is not None: raise CSVStructureError('expected %s fields, found %s' % (len(csv_column_names), len(data.keys()))) deserialized_data = dict_() for key in data: if data[key] == null_text: deserialized_data[key] = None continue attribute_name = cls._get_attribute_name(key) deserialized_value = cls._get_deserialized_value( data[key], 'csv', key, config_set=config_set) deserialized_data[attribute_name] = deserialized_value csv.unregister_dialect('sqlathanor') return deserialized_data
def parse_csv(input_data, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character="\\", line_terminator='\r\n'): """De-serialize CSV data into a Python :class:`dict <python:dict>` object. .. versionadded:: 0.3.0 .. tip:: Unwrapped empty column values are automatically interpreted as null (:obj:`None <python:None>`). :param input_data: The CSV data to de-serialize. Should include column headers and at least **one** row of data. Will ignore any rows of data beyond the first row. :type input_data: :class:`str <python:str>` :param delimiter: The delimiter used between columns. Defaults to ``|``. :type delimiter: :class:`str <python:str>` :param wrapper_character: The string used to wrap string values when wrapping is applied. Defaults to ``'``. :type wrapper_character: :class:`str <python:str>` :param null_text: The string used to indicate an empty value if empty values are wrapped. Defaults to `None`. :type null_text: :class:`str <python:str>` :returns: A :class:`dict <python:dict>` representation of the CSV record. :rtype: :class:`dict <python:dict>` :raises DeserializationError: if ``input_data`` is not a valid :class:`str <python:str>` :raises CSVStructureError: if there are less than 2 (two) rows in ``input_data`` or if column headers are not valid Python variable names """ use_file = False if not checkers.is_file(input_data) and not checkers.is_iterable( input_data): try: input_data = validators.string(input_data, allow_empty=False) except (ValueError, TypeError): raise DeserializationError("input_data expects a 'str', received '%s'" \ % type(input_data)) input_data = [input_data] elif checkers.is_file(input_data): use_file = True if not wrapper_character: wrapper_character = '\'' if wrap_all_strings: quoting = csv.QUOTE_NONNUMERIC else: quoting = csv.QUOTE_MINIMAL if 'sqlathanor' in csv.list_dialects(): csv.unregister_dialect('sqlathanor') csv.register_dialect('sqlathanor', delimiter=delimiter, doublequote=double_wrapper_character_when_nested, escapechar=escape_character, quotechar=wrapper_character, quoting=quoting, lineterminator=line_terminator) if not use_file: csv_reader = csv.DictReader(input_data, dialect='sqlathanor', restkey=None, restval=None) rows = [x for x in csv_reader] else: if not is_py2: with open(input_data, 'r', newline='') as input_file: csv_reader = csv.DictReader(input_file, dialect='sqlathanor', restkey=None, restval=None) rows = [x for x in csv_reader] else: with open(input_data, 'r') as input_file: csv_reader = csv.DictReader(input_file, dialect='sqlathanor', restkey=None, restval=None) rows = [x for x in csv_reader] if len(rows) < 1: raise CSVStructureError( 'expected 1 row of data and 1 header row, missing 1') else: data = rows[0] for key in data: try: validators.variable_name(key) except ValueError: raise CSVStructureError( 'column (%s) is not a valid Python variable name' % key) if data[key] == null_text: data[key] = None csv.unregister_dialect('sqlathanor') return data
def bike_description(self, value): self._bike_description = validators.string(value, allow_empty=True)
def name(self, value): value = validators.string(value, allow_empty=True) self._name = value
def from_string(value): return validators.string(value, allow_empty=True, coerce_value=True)