How to use the validators.url function in validators

To help you get started, we’ve selected a few validators examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Morgan-Stanley / testplan / testplan / common / utils / validation.py View on Github external
def is_valid_url(url):
    """Validator that checks if a url is valid"""
    return bool(validators.url(url))
github aalto-ui / aim / aim_backend / uimetrics_backend / handlers / metric_ws_handler.py View on Github external
message_type = message["type"]
            url = message["url"]
            filename = message["filename"]
            metrics = {k: v for k, v in message["metrics"].items() if v == True} # filter
            data = message["data"]
            server = options.name
            session = uuid.uuid4().hex

            if message_type != "execute":
                raise ValidationError("Unsupported message type: '{}'".format(message_type))

            # Generate base64 encoded images
            # print("Generating base64 encoded images...")
            if filename is None: # URL as input
                url = url.strip().lower()
                if (options.environment == "development" and not validators.url(url, public=False)) or \
                    (options.environment == "production" or options.environment == "test") and (not validators.url(url, public=True) or re.match("^https?://localhost\.", url)):
                    raise ValidationError("Invalid URL: {}".format(url))
                pngb64 = metrics_util.generate_screenshot(url)
            else: # screenshot as input
                url = None
                filename = filename.strip().lower()
                file_extension = (os.path.splitext(filename)[1]).split(".")[1]
                data_format = data.split(",")[0][5:] # remove scheme 'data:'
                data_raw = data.split(",")[1]
                if file_extension != "png":
                    raise ValidationError("Invalid file extension: '{}'".format(file_extension))
                if data_format != "image/png;base64":
                    raise ValidationError("Invalid data format: '{}'".format(data_format))

                pngb64 = metrics_util.resize_uploaded_image(data_raw)
                size = metrics_util.get_screenshot_size()
github curif / cumulus-tv-m3u8-loader / src / m3u8_loader.py View on Github external
url = url.split(urlEndChar)[0]

      valid = True
      if validation and validation.get("active", False):
        try:
          valid = validate(validation, url)
        except Exception as e:
          valid = False
          print "Validation error:" + str(e)
          pass

      #avoid duplicates
      valid = valid and url not in urlCollector

      #valid url
      valid = valid and validators.url(url) == True

      logging.info(" - Channel: " + name + " - valid: " + str(valid) + " " + url)

      if valid:
        contStart += 1

        genres = mapGenres(group, provider)
        if genres.strip() == "":
          genres = mapGenresByName(name, provider)

        #valid logo:
        if logo is not None and logo != "":
          if validators.url(logo) != True:
            logo = None

        cumulusData = {
github indrajithi / tiny-web-crawler / crawler.py View on Github external
def _isvalidurl(self, url):
		"""
		Returns True for a valid url, False for an invalid url.
		"""
		return bool(validators.url(url))
github DCASE-REPO / dcase_util / dcase_util / files / remote.py View on Github external
self._local_bytes = None
        self._local_modified = None

        # Remote
        self._remote_file = None
        self.remote_file = remote_file
        self.remote_md5 = remote_md5
        self._remote_bytes = remote_bytes
        self._remote_status = None
        self._remote_modified = None

        # Run DictContainer init
        DictContainer.__init__(self, **kwargs)

        # Check remote url
        if self.remote_file is not None and validators.url(self.remote_file) is not True:
            message = '{name}: Remote file URL not valid [{url}]'.format(
                name=self.__class__.__name__,
                url=self.remote_file,
            )
            self.logger.exception(message)
            raise ValueError(message)

        # Check local filename
        if self.filename is None:
            message = '{name}: Local file not set.'.format(
                name=self.__class__.__name__)
            self.logger.exception(message)
            raise ValueError(message)

        # Check content types
        if self.content_type is not None:
github phage-nz / ph0neutria / util / StringUtils.py View on Github external
def isValidUrl(url):
    return validators.url(url)
github Limych / media_player.linkplay / custom_components / linkplay / media_player.py View on Github external
xml_path = "{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}item/"
        title_xml_path = "{http://purl.org/dc/elements/1.1/}title"
        artist_xml_path = "{urn:schemas-upnp-org:metadata-1-0/upnp/}artist"
        album_xml_path = "{urn:schemas-upnp-org:metadata-1-0/upnp/}album"
        image_xml_path = "{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI"

        self._media_title = \
            xml_tree.find("{0}{1}".format(xml_path, title_xml_path)).text
        self._media_artist = \
            xml_tree.find("{0}{1}".format(xml_path, artist_xml_path)).text
        self._media_album = \
            xml_tree.find("{0}{1}".format(xml_path, album_xml_path)).text
        self._media_image_url = \
            xml_tree.find("{0}{1}".format(xml_path, image_xml_path)).text

        if not validators.url(self._media_image_url):
            self._media_image_url = None
github insightfinder / InsightAgent / common / proxy_reportMetrics.py View on Github external
def send_http_request(url, type_l, data, succ_message="Request successful!", fail_message="Request Failed"):
    try:
        if validators.url(url):
            if type_l == "get":
                response = requests.get(url, data)
            else:
                response = requests.post(url, data)

            if response.status_code == 200:
                logger.info(succ_message)
                return True
            logger.info(fail_message)
            return False
        else:
            logger.info("Url not correct : " + url)
    except Exception:
        logger.warning(fail_message)
    return True
github Druidmaciek / CourseDownloader / gui.py View on Github external
"",
                                   "Download location is not set", wx.OK | wx.ICON_QUESTION)
            result = dlg.ShowModal()
            dlg.Destroy()
            return
        text_url = self.t1.GetValue()
        # Validate url
        if not url(text_url):
            self.t1.SetValue('')
            dlg = wx.MessageDialog(self,
                                   "This is not a correctly formatted URL.",
                                   "Enter an url.", wx.OK)
            result = dlg.ShowModal()
            dlg.Destroy()
            return
        if url(text_url):
            dlg = wx.MessageDialog(self,
                                   "Do you really want to download the course from {}?".format(text_url),
                                   "Confirm Download?", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
            result = dlg.ShowModal()
            dlg.Destroy()
            if result == wx.ID_OK:

                site = text_url[text_url.find('.') + 1:]
                site = site[:site.find('.') + 1]
                sites = {'lynda.': 'Lynda', 'pluralsight.': 'Pluralsight',
                         'skillshare.': 'Skillshare', 'udemy.': 'Udemy'}
                sleep(1)
                username, pwd = self.reader.load_login(sites[site])
                if self.notLoggedMessage(username, pwd, sites[site]):
                    self.username, self.pwd = username, pwd
                else:
github DingGuodong / LinuxBashShellScriptForOps / functions / net / tcp / http / pyUrlValidator.py View on Github external
def is_url_valid_am1(url):  # 'am' is short for 'alternative method'
    """
    http://validators.readthedocs.io/en/latest/
    Python has all kinds of validation tools, but every one of them requires defining a schema. I 
    wanted to create a simple validation library where validating a simple value does not require 
    defining a form or a schema.
    """
    import validators
    if validators.url(url):
        return True
    else:
        return False