当前位置: 首页>>代码示例>>Python>>正文


Python validators.url函数代码示例

本文整理汇总了Python中validators.url函数的典型用法代码示例。如果您正苦于以下问题:Python url函数的具体用法?Python url怎么用?Python url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了url函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _hyperlink_conversion

    def _hyperlink_conversion(self, ignoretext):

        if not self.has_selection:
            self.inline_call('square_brackets', nomove=True, text="Link text")
            return self.inline_call('parentheses', text="http://www.example.com")


        text = self.cursor.selectedText()
        is_email = validators.email(text)
        is_url = validators.url(text)

        if is_url:
            self.inline_call('square_brackets', text=text)
            return self.inline._call('parentheses', text=text)
        elif is_email:
            self.inline_call('square_brackets', text=text)
            return self.inline_call('parentheses', text='mailto:' + text)
        
        url_from_partial = 'http://' + text
        if validators.url(url_from_partial):
            self.inline_call('square_brackets')
            self.inline_call('parentheses', text=url_from_partial)
        else:
            self.inline_call('square_brackets', nomove=True)
            self.inline_call('parentheses', text="http://www.example.com")
开发者ID:fizzbucket,项目名称:aced,代码行数:25,代码来源:textformatting.py

示例2: put_article

def put_article():
    '''
    Add new article for a user.
    '''
    username = request.headers.get('x-koala-username')
    apikey = request.headers.get('x-koala-key')
    user = locate_user(username, apikey)

    reqjson = request.get_json()

    result = validators.url(reqjson['url'])
    if not result:
        # try again but with http://
        result = validators.url('http://' + reqjson['url'])
        if not result:
            logging.info("Bad URL: %s" % reqjson['url'])
            abort(400)
        else:
            reqjson['url'] = 'http://' + reqjson['url']

    title = reqjson.get('title', reqjson['url'])
    url = reqjson['url']
    date = str(datetime.now())
    read = False
    favorite = False
    owner = user.id

    article = Article.create(title=title, url=url, date=date, read=read, favorite=favorite, owner=owner)

    return jsonify({'id': article.id}), 201
开发者ID:bostrt,项目名称:koala,代码行数:30,代码来源:koala.py

示例3: test_stackoverflow

    def test_stackoverflow(self):
        """
        This function is used to test stackoverflow function
        which returns user name, description, tags and links.

        ...If url is valid

        https://stackoverflow.com/users/7690738/ashish-cherian

        returns username, description, tags and links

        ...If url is empty

        raise ValueError("unknown url type: %r" % self.full_url)

        ValueError: unknown url type: ''

        ...If an invalid url is given

        raise URLError(err)

        urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

        :return: if test is ok or not
        """
        #validating url

        self.assertTrue(validators.url(self.url1))
        self.assertTrue(validators.url(self.url2))

        #checking if url is a stackoverflow url or not

        self.assertTrue("https://stackoverflow.com/users" in self.url1)
        self.assertTrue("https://stackoverflow.com/users" in self.url2)

        #checking connection to url

        self.assertEqual(urllib.request.urlopen(self.url1).getcode(), 200)
        self.assertEqual(urllib.request.urlopen(self.url2).getcode(), 200)

        #checking if url is not empty

        self.assertNotEqual(self.url1, "")
        self.assertNotEqual(self.url2, "")

        #checking for timeout error

        self.assertTrue(requests.get(self.url1, timeout=10.0))
        self.assertTrue(requests.get(self.url1, timeout=10.0))

        #checking username and description are not empty

        self.assertNotEqual(self.user1, "")
        self.assertNotEqual(self.description1, "")
        self.assertNotEqual(self.user2, "")
        self.assertNotEqual(self.description2, "")
开发者ID:vishnu2981997,项目名称:Stackoverflow-Extractor,代码行数:56,代码来源:teststack_overflow_extractor.py

示例4: create_server

	def create_server(self,request):
		user = request.user
		url = str(self.cleaned_data.get('server'))
		serverS=Server.objects.filter(url=url)
		if serverS:
			self.add_error('server','Url already exist')
		else:
			if validators.url('https://'+url) or validators.url('http://'+url):
				server = Server.objects.create(url=url,user=user)
				server.save()
			else:
				self.add_error('server','Incorrect url')
开发者ID:firedbm,项目名称:Ping_server,代码行数:12,代码来源:forms.py

示例5: is_valid_url

 def is_valid_url(self, url):
     if validators.url(url):
         return True
     else:
         if url[:8] == "https://":
             if validators.url("http://%s" % (url[8:])):
                 return True
             else:
                 return False
         else:
             if validators.url("http://%s" % (url)):
                 return [True, "http://"]
开发者ID:ProjectRadium,项目名称:smartchain-verify-web,代码行数:12,代码来源:core.py

示例6: index

def index():
	if request.method == "POST":
		if 'username' in session:
			url = request.form["url"]
			links = db.links
			if not validators.url(url):
				url = "http://" + url
			if not validators.url(url):
			    return render('form.html', error='URL is incorrect')
			else:
				existing_url = links.find_one({'url': url})
				if not existing_url:
					current_time = str(datetime.now())

					print current_time
					print url

					cur_user = db.users.find_one({'name': session['username']})

					html = None

					try:
						html = urllib2.urlopen(url)
						html = html.read()
						soup = bf(html)
						title = url
						try:
							title = soup.find('title').text
						except Exception:
							pass
						
						db.links.insert({
							'url': url, 
							'title': title,
							'author': cur_user['name'],
							'author_id': cur_user['_id'],
							'current_time': current_time,
							'votes': 1
							})

						return render('form.html', error="New item is added")

					except Exception:
						return render('form.html', error="URL is incorrect")

				else:
					return render('form.html', error="URL already exists")
		else:
			flash('Please log in')
			redirect(url_for('login'))

	return render('form.html')
开发者ID:abzaloid,项目名称:silteme,代码行数:52,代码来源:project.py

示例7: validate_result

def validate_result(current, default, type):
    """
    Validates the data, whether it needs to be url, twitter, linkedin link etc.
    """
    if current is None:
        current = ""
    if default is None:
        default = ""
    if type == "URL" and validators.url(current, require_tld=True) and not validators.url(default, require_tld=True):
        return current
    if type == "EMAIL" and validators.email(current) and not validators.email(default):
        return current
    return default
开发者ID:aviaryan,项目名称:open-event-scraper,代码行数:13,代码来源:scraper.py

示例8: validated_redirect_uri

def validated_redirect_uri(uri_param):
    if uri_param is None:
        raise BadRequest("Missing required redirect URI")

    try:
        validators.url(uri_param)
    except:
        raise BadRequest("Malformed redirect URI")

    parsed = urlparse(uri_param)
    if parsed.scheme not in ['http', 'https']:
        raise BadRequest("Redirect URI must be http or https")

    return parsed
开发者ID:tdeck,项目名称:civid_web,代码行数:14,代码来源:civid.py

示例9: ddos_server

    def ddos_server(self, url, timeout=30):
	if self.ddos_process is not None:
	    logging.debug("communicate with siege")
	    stdout,stderr = self.ddos_process.communicate()
            logging.debug("siege stdout: %s"%stdout)
	    logging.debug("siege stderr: %s"%stderr)

        if url is not None and validators.url(url):
	    cmdstr = "timeout -k {longerTimeout}s {longerTimeout}s siege -c 100 -t {timeout} {url}"\
		.format(longerTimeout=timeout+2, timeout=timeout, url=url)
            logging.debug(cmdstr)
            self.ddos_process = subprocess.Popen(shlex.split(cmdstr))
        else:
            logging.warning("Neither ip nor url where supplied, DDOS failed")
            logging.debug("validators.url(%s) == %s"%(url, validators.url(str(url))))
开发者ID:icehawk1,项目名称:GameoverZeus,代码行数:15,代码来源:BotCommands.py

示例10: url

def url(vdomain):

	if validators.url(vdomain):

		return vdomain
	else:
		return False
开发者ID:eldoroshi,项目名称:project,代码行数:7,代码来源:api.py

示例11: link_data

    def link_data(request):
        if validators.url(request.data_values):
            request.data_values = str(request.data_values)
        else:
            request.data_values = '#'

        return request
开发者ID:Ecotrust,项目名称:F2S-MOI,代码行数:7,代码来源:models.py

示例12: home_addEntry

def home_addEntry():
    longUrl = request.form['longURl']
    if not validators.url(longUrl):
        return render_template("bad_input.html", title=cfg['general']['title'])
    short = logic.addEntry(longUrl, logic.connect(cfg['general']['sqlite_location']))
    current_url = cfg['web_paths']['shortened'] + short
    return render_template("shortened.html", url=current_url, short=short, title=cfg['general']['title'])
开发者ID:sublinus,项目名称:ShortyUrl,代码行数:7,代码来源:app.py

示例13: urlLinkSpecified

def urlLinkSpecified(request):
	if request.method == 'POST':
		url = request.POST.get("url")
		if validators.url(url):
			start_time = time.time()
			response = requests.get(url)
			maintype= response.headers['Content-Type'].split(';')[0].lower()
			if maintype not in ('image/png', 'image/jpeg', 'image/gif'):
				print("a")
				return HttpResponse(json.dumps({'data':"Url is not of image type",'url':"/home/ubuntu/DjangoWithCNN/myproject/media/blank_person.png"}))
			else:
				img = Image.open(StringIO(response.content))		
				FileName = str(uuid.uuid1())+".png"
				Pathname = "/home/ubuntu/DjangoWithCNN/myproject/media/"+FileName
				width, height = img.size
				if width > 600:
					basewidth = 400
					wpercent = (basewidth/float(img.size[0]))
					hsize = int((float(img.size[1])*float(wpercent)))
					img = img.resize((basewidth,hsize), Image.ANTIALIAS)
				img.save(Pathname)
				print("--- %s seconds ---" % (time.time() - start_time))
				result = main(Pathname)
				print(result)
				return HttpResponse(result)
		else:
			return HttpResponse(json.dumps({'data':"Invalid URL",'url':"/home/ubuntu/myproject/media/blank_person.png"}))
开发者ID:LamUong,项目名称:DjangoWithCNN,代码行数:27,代码来源:views.py

示例14: add_url

def add_url():
    if not session.get('logged_in'):
        abort(401)

    url = request.form['url']
    # validate URL
    if not url:
        flash("URL cannot be empty")
        return redirect(url_for('show_urls'))
    if not validators.url(url):
        flash("URL is invalid, valid one starts with 'http://' or 'https://'")
        return redirect(url_for('show_urls'))

    # insert record
    insert = 'INSERT INTO urls (url) VALUES (?)'
    cur = g.db.cursor()
    cur.execute(insert, [url])
    g.db.commit()

    # get the last record id and encoded
    last_id = cur.lastrowid
    short_url = ShortUrl.encode(last_id)

    # update the record again with short_url
    update = 'UPDATE %s SET %s="%s" WHERE id=%s' \
                % (TABLE, _COL2, short_url, last_id)
    cur.execute(update)
    g.db.commit()
    cur.close()

    flash("Tiny URL was successfully created: " + request.host_url + 'o/' + short_url)
    return redirect(url_for('show_urls'))
开发者ID:soundless,项目名称:tinyurl,代码行数:32,代码来源:main.py

示例15: verify_config

def verify_config(owner, sample_config, config, current_key=None):
    """Verify that config corresponds to sample_config"""
    import validators

    def raise_exception(message):
        raise ValueError('in {} config {}\nsample:   {}\nprovided: {}'.format(owner, message, sorted(sample_config.items()), sorted(config.items())))

    if isinstance(sample_config, list):
        if not len(config):
            raise_exception('empty_list')
        for element in config:
            verify_config(owner=owner, sample_config=sample_config[0], config=element, current_key=current_key)
    elif isinstance(sample_config, dict):
        for sample_key, sample_value in sample_config.items():
            if sample_key not in config:
                raise_exception('key "{}" is not provided'.format(sample_key))
            if config[sample_key] is None:
                raise_exception('Value of "{}" is empty'.format(sample_key))
            verify_config(owner=owner, sample_config=sample_value, config=config[sample_key], current_key=sample_key)
    else:
        # from this point config and sample_config start to be simple values
        if type(sample_config) is str:
            if sample_config.startswith('http') and validators.url(config) is not True:
                raise_exception('Key "{}" do not contain valid url: {}'.format(current_key, config))
            elif sample_config.startswith('email') and not validators.email(config):
                raise_exception('Key "{}" do not contain valid email: {}'.format(current_key, config))
            elif sample_config.startswith('ipv4') and not validators.ipv4(config):
                raise_exception('Key "{}" do not contain valid IPv4: {}'.format(current_key, config))
            elif sample_config.startswith('int'):
                try:
                    int(config)
                except ValueError:
                    raise_exception('Key "{}" do not contain valid int number: {}'.format(current_key, config))
        elif type(sample_config) is bool and type(config) is not bool:
            raise_exception('Key "{}" must be bool: {}'.format(current_key, config))
开发者ID:CiscoSystems,项目名称:os-sqe,代码行数:35,代码来源:config_verificator.py


注:本文中的validators.url函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。