本文整理汇总了Python中models.Url类的典型用法代码示例。如果您正苦于以下问题:Python Url类的具体用法?Python Url怎么用?Python Url使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Url类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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')
示例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])
示例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)})))
示例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)
示例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')
示例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
示例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)))
示例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)
示例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")
示例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")
示例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
示例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])
示例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,
})
示例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)
示例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, "")