本文整理汇总了Python中models.Url.save方法的典型用法代码示例。如果您正苦于以下问题:Python Url.save方法的具体用法?Python Url.save怎么用?Python Url.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Url
的用法示例。
在下文中一共展示了Url.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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: pagina
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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)))
示例3: barra
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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")
示例4: shortener
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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)
示例5: make_url_model
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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
示例6: test_mock_generation
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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])
示例7: main
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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)
示例8: shortenUrl
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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)})))
示例9: index
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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,
})
示例10: report_url
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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: test_create_two_urls_with_same_tag
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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])
示例12: import_urls_from_delicious
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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
示例13: post
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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)
示例14: test_slug_shortening_failure
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
def test_slug_shortening_failure(self):
"""
When a slug cannot be generated, SlugCollision is raised
"""
u = Url(url='http://lab.tmp.br/%s/index.html' % MOCK_MARK)
u.save()
slug = u.slug
while len(slug) < MAX_SLUG:
uu = Url(url='http://another.lab.tmp.br/%s/index%s.html' % (MOCK_MARK, len(slug)))
uu.save()
slug = uu.slug
uuu = Url(url='http://last.lab.tmp.br/%s/index%s.html' % (MOCK_MARK, len(slug)))
self.assertRaises(SlugCollision, uuu.save)
示例15: test_add_url_with_tags
# 需要导入模块: from models import Url [as 别名]
# 或者: from models.Url import save [as 别名]
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")