• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Url类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: index

def index():
    if request.method == 'POST':
        thing = request.form.get('url')
        if thing:
            if '://' not in thing:
                thing = 'http://' + thing

            # Verify the URL
            parsed = urlparse(thing)
            if parsed.scheme not in ('http', 'https'):
                return "I only take HTTP or HTTPS URLs, dummy"

            urlhash = hashlib.sha1(thing).hexdigest()
            try:
                url = Url.get(Url.url_hash == urlhash)
            except:
                url = Url()
                url.url = thing
                url.url_hash = urlhash
                url.created = datetime.datetime.now()
                url.save()

                # hokay. got us an ID, let's make a key.
                url.key = base36_encode(url.id)
                url.save()

            return render_template('added.html', short_url="http://{0}/{1}".format(request.headers['host'], url.key))
        else:
            return "You didn't give me shit"
    else:
        return render_template('index.html')
开发者ID:nickpegg,项目名称:shrtnr,代码行数:31,代码来源:shrtnr.py


示例2: test_mock_generation

 def test_mock_generation(self):
     """
     Tests that a mock slug is properly generated
     """
     u1 = Url(url='http://lab.tmp.br/%s/index.html' % MOCK_MARK)
     u1.save()
     self.assertEqual(u1.slug, MOCK_MARK[:MIN_SLUG])
开发者ID:hugutux,项目名称:propython,代码行数:7,代码来源:tests.py


示例3: shortenUrl

def shortenUrl(request):
	if request.method == "GET":
		t = get_template("index.html")
		return HttpResponse(t.render())
	if request.method == "POST":
		url = request.POST.get("urlToShorten","")
		if url == "":
			return HttpResponseRedirect("/")
		try:
			if not ("http://" in url) or not ("https://" in url):
				url="http://"+url
			val(url)
		except ValidationError,e:
			t = get_template("invalid.html")
			return HttpResponse(t.render())

		url = url.replace("http://","")
		url = url.replace("https://","")
		QS = Url.objects.all().filter(actualUrl=url)
		if(len(QS)>0):
			UrlObject = QS[0]
			t = get_template("shortened.html")
			return HttpResponse(t.render(Context({"actual_url":url, "shortened_url":dehydrate(UrlObject.id)})))	

		mUrl = Url()
		
		mUrl.actualUrl = url
		mUrl.save()
		# mUrl.shortenedUrl = shorten(url)
		t = get_template("shortened.html")

		return HttpResponse(t.render(Context({"actual_url":url, "shortened_url":dehydrate(mUrl.id)})))
开发者ID:deepaksattiraju249,项目名称:urlShortener,代码行数:32,代码来源:views.py


示例4: main

def main(request):
    host = request.META['HTTP_HOST']

    if request.method == "GET":
        output = ("<form action='/' method='POST'>\n"
                + "Introduce your url:"
                + "<input type='text' name='url'/></br>\n"
                + "<input type='submit' value='Submit' "
                + "/></form>\n<br>\n<br>"
                + str(Url.objects.values_list()))

    elif request.method == "POST":
        urlname = urllib.unquote(request.body.split("=")[1])
        if (not urlname.startswith("http://") 
                and not urlname.startswith("https://")):
            urlname = "http://" + urlname

        try:
            urlname = Url.objects.get(url=urlname).url
        except Url.DoesNotExist:
            new_entry = Url(url=urlname)
            new_entry.save()

        urlnum = Url.objects.get(url=urlname).id
        output = ("You introduced: " + str(urlname) + "</br>\n"
                + "The abbreviation is: /" + str(urlnum) + "</br>\n"
                + "<meta http-equiv='Refresh' content='2;"
                + "url=http://" + host + "'>")
    else:
        return HttpResponseForbidden("Method not allowed")

    return HttpResponse(output)
开发者ID:jperaltar,项目名称:X-Serv-18.2-Practica2,代码行数:32,代码来源:views.py


示例5: create

def create():
    """Create a short URL and return a JSON response."""
    full_url = request.args.get('url')

    if not full_url:
        return Response(json.dumps({'success': False,
                                    'message': 'No "url" parameter specified'}),
                        mimetype='application/json')

    # Validate full_url
    parsed_url = urlparse(full_url)
    if parsed_url.scheme == '':
        return Response(json.dumps({'success': False,
                                    'message': 'No URL scheme specified'}),
                        mimetype='application/json')

    # Insert URL into db and generate a short url
    short_url = Url(full_url)
    db.session.add(short_url)
    db.session.commit()  # Get autoincrement id
    short_url.short_url = base36encode(short_url.id)
    db.session.commit()

    # Get host to display short url (this won't work with https)
    host = 'http://' + request.headers.get('Host', 'localhost')

    return Response(json.dumps({'success': True,
                                'url': full_url,
                                'short_url': '%s/%s' % (host, short_url.short_url)}),
                        mimetype='application/json')
开发者ID:druska,项目名称:shorturls,代码行数:30,代码来源:app.py


示例6: make_url_model

def make_url_model(url, site): 
	""" This should on occur once per newly created URL, the linked count is set to zero if it
		is a new site added to database
	"""
	now = datetime.now()
	base_url = 'http://links.ep.io/'
	url_model = Url()
	url_model.url = url
	url_short  = url
	try: 
		domain = Domain.objects.get(site=site)
		domain.linked_count += 1
		domain.date_updated = now
		domain.save()
	except:
		domain = Domain(site=site, linked_count=1, date_updated= now)
		domain.save()
	url_model.site = domain
	url_model.date_time_created = datetime.now()
	url_model.linked_count = 1
	url_model.save()
	url_model.url_shortened = base_url + encode_62(url_model.pk)
	print url_model.url_shortened
	url_model.save()
	return url_model
开发者ID:myusuf3,项目名称:links,代码行数:25,代码来源:views.py


示例7: pagina

def pagina(request):
    if request.method == "GET":
        template = get_template("pagina.html")
        lista_url = Url.objects.all()
        for url in lista_url:
            lista_url = "<li><a href=/" + str(url.id) + ">" + url.original_url + "</a>"
    elif request.method == "POST" or request.method == 'PUT':
        url = request.POST.get('url')
        url = acortarUrl(url)
        try:
            url_encontrada = Url.objects.get(original_url = url)
        except Url.DoesNotExist:
            urls=Url(original_url = url)
            urls.save()
            url_encontrada = Url.objects.get(original_url = url)
        return HttpResponse(str(url_encontrada.id))
    lista_url = Url.objects.all()
    respuesta = "<ol>"
    for elemento in lista_url:
        respuesta += '<li><a href ="'+ str(elemento.original_url) + '">'
        respuesta += str(elemento.original_url) + '</a>' + " = " + '<a href="'+ str(elemento.id) +'">' +  str(elemento.id) + '</a>'
    respuesta += "</ol>"
    template = get_template("pagina.html")
    cont = {'contenido': respuesta,}
    return HttpResponse(template.render(Context(cont)))
开发者ID:lauratrabas,项目名称:X-Serv-18.2-Practica2,代码行数:25,代码来源:views.py


示例8: shortener

def shortener(request):
    if request.method == "GET":
        urlDb = Url.objects.all()
        urlDic = ""
        for url in urlDb:
            urlDic +=  "URL " + str(url.url) + " Shortened URL " + str(url.id) + "<br/>"

        resp = "<body><html> <form id= shortUrl method= post> \
                <fieldset><legend>URL shortener</legend><label> Url</label> \
                <input id= campo1 name= Url type= text /></label> \
                <input id= campo2 name= pressbutton type= submit value= Shorten URL/> \
                </fieldset> </form> <p> URL Dictionary </p>" \
                + urlDic + "</body></html>"
       
    elif request.method == "POST":
        url = request.body.split("=")
        url = url[1].split("&")
        url = url[0]
        try:
            url = Url.objects.get(url = url)
        except Url.DoesNotExist:
            new = Url(url = url)
            new.save()
        urlId = str(Url.objects.get(url = url).id) 
        resp = "<html><body>URL " + url + " Shortened URL \
                <a href= http://" + url + ">" + urlId + "</a> \
                </body></html>"

    return HttpResponse(resp)
开发者ID:victortm,项目名称:X-Serv-18.2-Practica2,代码行数:29,代码来源:views.py


示例9: barra

def barra(request):
    formul = '<br><form action="" method="POST" accept-charset="UTF-8">' + \
        'URL para acortar: <input type="text" name="url">' + \
        '<input type="submit" value="Acorta!"></form><hr>'
    srvHost = str(request.META["SERVER_NAME"])
    srvPort = str(request.META["SERVER_PORT"])

    if request.method == "GET":
        urlshtml = ""
        urls = Url.objects.all()
        for url in urls:
            urlshtml += formatUrlHtml(url, srvHost, srvPort)
        return HttpResponse(formul + urlshtml)
    elif request.method == "POST":
        longUrl = request.POST.get("url", "")
        if longUrl == "":
            salida = "Incorrect post or empty url"
        else:
            if not longUrl.startswith("http://") and \
                    not longUrl.startswith("https://"):
                longUrl = "http://" + longUrl
            try:
                newUrl = Url.objects.get(long_url=longUrl)
            except Url.DoesNotExist:
                newUrl = Url(long_url=longUrl)
                newUrl.save()
            salida = formatUrlHtml(newUrl, srvHost, srvPort)
        return HttpResponse(salida)
    else:
        return HttpResponseNotAllowed("Method not allowed in this server")
开发者ID:jjmerchante,项目名称:X-Serv-18.2-Practica2,代码行数:30,代码来源:views.py


示例10: report_url

def report_url(request):
  if request.method == 'POST':
    url = request.POST['url']
    try:
      newUrl = Url(url=url)
      newUrl.save()
    except Exception:
      return HttpResponse("ERROR")
    return HttpResponse("SUCCESS")
开发者ID:EricSchles,项目名称:Reporting,代码行数:9,代码来源:views.py


示例11: import_urls_from_delicious

def import_urls_from_delicious(login, password, opener=default_opener):
    bookmarks = opener(login, password)

    ret = []
    for href, tags, title, desc, time in bookmarks:
        url = Url(url=href)
        url.save()
        ret.append(url)

    return ret
开发者ID:osantana,项目名称:curso-tdd,代码行数:10,代码来源:utils.py


示例12: test_create_two_urls_with_same_tag

    def test_create_two_urls_with_same_tag(self):
        url1 = Url(url="http://example.com/1", title="My Title")
        url1.save()
        url1.add_tags_from_string("tag1")

        url2 = Url(url="http://example.com/2", title="My Title")
        url2.save()
        url2.add_tags_from_string("tag1")

        self.assertEquals(url1.tags.all()[0], url2.tags.all()[0])
开发者ID:osantana,项目名称:curso-tdd,代码行数:10,代码来源:tests.py


示例13: index

def index(request, tag=None):
    if tag:
        tag_model = get_object_or_404(Tag, name=tag)
        urls = tag_model.url_set.all()
    else:
        urls = Url.objects.all()

    if request.method == "POST":
        form = UrlForm(request.POST)
        if form.is_valid():
            url_data = form.cleaned_data['url']
            title = form.cleaned_data['title']
            tags = form.cleaned_data['tags']
            try:
                url = Url(url=url_data, title=title)
                url.fill_title()
                url.save()
                url.add_tags_from_string(tags)
                if tag:
                    url.add_tag(tag)
            except IntegrityError:
                pass
            return HttpResponseRedirect(request.path)
    else:
        form = UrlForm()

    return render_to_response("index.html", {
            'urls': urls,
            'form': form,
        })
开发者ID:osantana,项目名称:curso-tdd,代码行数:30,代码来源:views.py


示例14: post

    def post(self, request):
        """
        Saves a new URL to the db. Accepts a long url and a possible slug as post parameters.

        * If the long url can't be validated then error 404 is returned.
        * If the requested slug has already been taken, then a new slug will be generated and
            returned on success.
        * If there is not a requested slug, then one will be generated and returned on success.
        * If there is not a requested slug and the requested URL already has a slug generated,
            then the previous slug is returned.

        :Return: Saved slug
        """
        # Make sure the slug is url safe.
        requested_slug = request.POST.get('requested_slug', None)
        if requested_slug:
            requested_slug = urllib.quote(requested_slug)
        requested_url = request.POST.get('requested_url', None)

        # Validate the requested url.
        if not requested_url.startswith('http://') and not requested_url.startswith('https://'):
            requested_url = 'http://%s' % requested_url
        try:
            validator = URLValidator()
            validator(requested_url)
        except:
            return Http404('URL Invalid')

        # Find the proper slug for this url.
        if slug_available(requested_slug):
            slug = requested_slug
        else:
            # If a slug was requested and it was taken, maybe it was taken by this url before.
            # If that is the case, then we should return that one to the user. Otherwise, try
            # to find a different slug already made for this url. If unable to find a slug
            # prevously created for this url, then make a new one.
            try:
                try:
                    existing = Url.objects.get(url=requested_url, slug=requested_slug)
                except:
                    existing = Url.objects.filter(url=requested_url)[0]
                # We already have a record in the db, so we can just return now without creating.
                return HttpResponse(existing.slug)
            except:
                slug = generate_slug(4)
        # Save the new shortened url to the db.
        shortened_url = Url(
                url=requested_url,
                slug=slug
            )
        shortened_url.save()
        # Return the saved slug to the user so they can copy and use it.
        return HttpResponse(slug)
开发者ID:joelsaupe,项目名称:url_shrtnr,代码行数:53,代码来源:views.py


示例15: test_get_url_with_no_title

    def test_get_url_with_no_title(self):
        response = self.mocker.mock()
        response.read()
        self.mocker.result("foo.zip")

        urlopen = self.mocker.replace("urllib.urlopen")
        urlopen("http://example.com/foo.zip")
        self.mocker.result(response)
        self.mocker.replay()

        url = Url(url="http://example.com/foo.zip")
        url.fill_title()
        self.assertEquals(url.title, "")
开发者ID:osantana,项目名称:curso-tdd,代码行数:13,代码来源:tests.py


示例16: processPost

def processPost(url):
    if url == "":
        return HttpResponseBadRequest("ERROR: EMPTY POST")
    elif not url.startswith("http://") and not url.startswith("https://"):
        url = "http://" + url
    try:
        newUrl = Url.objects.get(longUrl=url)
    except Url.DoesNotExist:
        newUrl = Url(longUrl=url)
        newUrl.save()
    response = "<p>url real: <a href=" + url + ">" + url + "</a></p>"
    response += "<p>url acortada: <a href=" + str(newUrl.id) + ">" +\
                str(newUrl.id) + "</a></p>"
    return HttpResponse(response)
开发者ID:reysam93,项目名称:X-Serv-18.2-Practica2,代码行数:14,代码来源:views.py


示例17: test_add_url_with_tags

    def test_add_url_with_tags(self):
        url = Url(url="http://example.com", title="My Title")
        url.save()

        url.add_tags_from_string("tag1, tag2 ,tag3 , tag4,tag5,,,")

        tags = url.tags.order_by("name")

        self.assertEquals(len(tags), 5)
        self.assertEquals(tags[0].name, "tag1")
        self.assertEquals(tags[1].name, "tag2")
        self.assertEquals(tags[2].name, "tag3")
        self.assertEquals(tags[3].name, "tag4")
        self.assertEquals(tags[4].name, "tag5")
开发者ID:osantana,项目名称:curso-tdd,代码行数:14,代码来源:tests.py


示例18: savebookmark

def savebookmark(TitleF,UrlF,DescriptionF,TagF,PrivateF,UserF):
    TitleF = unicode(TitleF)
    UrlF = unicode(UrlF)
    DescriptionF = unicode(DescriptionF)
    Tagf = unicode(TagF)
    try :
        UrlB = Url.objects.get(url=UrlF)
    except :
        UrlB = Url(url=UrlF)
    UrlB.save()

    try :
        TitleB = Title.objects.get(title=TitleF)
    except :
        TitleB = Title(title=TitleF)
    TitleB.save();
    try :
        DescriptionB = Description.objects.get(description=DescriptionF)
    except :
        DescriptionB = Description(description=DescriptionF)
    DescriptionB.save()
    try :
        PrivateB = Private.objects.get(private= (PrivateF == 'True'))
    except :
        PrivateB = Private(private= (PrivateF == 'True'))
    PrivateB.save()
    try :
        b2 = Bookmark.objects.get(url=UrlB)
        b2.title=TitleB
        b2.description=DescriptionB
        b2.private=PrivateB
    except :
        b2 = Bookmark(title=TitleB,url=UrlB,description=DescriptionB,private=PrivateB)
        b2.save()
        b2.user.add(UserF)
    b2.save()

    tags = TagF.split(" ")
    tags.sort()
    for t in tags :
        try :
            TagB = Tag.objects.get(tag=t)
        except :
            TagB= Tag(tag=t)
            TagB.save()
            TagB.user.add(UserF)
        TagB.save()
        b2.tag.add(TagB)
    b2.save()
开发者ID:bussiere,项目名称:Satsuki,代码行数:49,代码来源:Script.py


示例19: urlacorta

def urlacorta(request, recurso):

    formulario = ('<form action="" method="POST">Escribir url larga:'
                  + '<input type="text" name="nombre" value="" />'
                  + '<input type="submit" value="Acortar" /></form>')

    if request.method == 'POST':
        cuerpo = request.body.split('=')[1]
        if cuerpo == "":
            return HttpResponseNotFound(formulario + "Url no introducida")

        if cuerpo.find("http%3A%2F%2F") >= 0:
            cuerpo = cuerpo.split('http%3A%2F%2F')[1]

        cuerpo = "http://" + cuerpo
        try:
            newurl = Url.objects.get(url=cuerpo)

        except:
            newurl = Url(url=cuerpo)
            newurl.save()

        return HttpResponse("URL original: " +
                            "<a href=" + cuerpo + ">" + cuerpo + "</a>" +
                            "</br>URL acortada: " +
                            "<a href=" + str(newurl.id) + ">" +
                            "127.0.0.1:8000" + "/" + str(newurl.id) + "</a>" +
                            "</p><a href=" + "http://127.0.0.1:8000" +
                            "> volver </a>""")

    if request.method == 'GET':
        urlList = Url.objects.all()
        if recurso == '':
            return HttpResponse(formulario + "Urls almacenadas:</br>"
                                + printurls())

        else:
            try:
                url = Url.objects.get(id=recurso)
                return HttpResponseRedirect(url.url)

            except:
                return HttpResponseNotFound("<h1>Pagina no encontrada</h1></p>"
                                            + "<a href=" + "http://" +
                                            "127.0.0.1:8000" + ">volver</a>")
    else:
        return ("<h1>404 Not Found</h1></p><a href=" + "http://127.0.0.1:8000"
                + "> volver </a>")
开发者ID:anombela,项目名称:X-Serv-18.2-Practica2,代码行数:48,代码来源:views.py


示例20: test_slug_shortening

 def test_slug_shortening(self):
     """
     Tests that a slug is properly generated
     """
     u1 = Url(url='http://lab.tmp.br/%s/index.html' % MOCK_MARK)
     u1.save()
     u2 = Url(url='http://another.lab.tmp.br/%s/index.html' % MOCK_MARK)
     u2.save()
     u3 = Url(url='http://yetanother.lab.tmp.br/%s/index.html' % MOCK_MARK)
     u3.save()
     self.assertEqual(u1.slug, MOCK_MARK[:MIN_SLUG])
     self.assertEqual(u2.slug, MOCK_MARK[:MIN_SLUG+1])
开发者ID:hugutux,项目名称:propython,代码行数:12,代码来源:tests.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.User类代码示例发布时间:2022-05-27
下一篇:
Python models.Tweet类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap