缩短链接重定向

时间:2018-08-24 11:31:02

标签: python django url

我正在django上做链接缩短器。我不知道如何将缩短的URL重定向到原始URL。 例如,我有一个链接127.0.0.1:8000/ZY9J3y,需要它才能将我转移到facebook.com。问题是我应该在我的url.py中添加些什么,以便将这样的链接重定向到原始链接?

2 个答案:

答案 0 :(得分:0)

您可以直接在urls.py中配置重定向:

urls.py

from django.views.generic import RedirectView

urlpatterns = [
    path('ZY9J3y/', RedirectView.as_view(url='https://www.facebook.com'))
]

或者按照评论中的建议,您可以使用视图来找出重新定向到的位置:

urls.py

urlpatterns = [
    path('<str:query>', views.my_view)
]

views.py

from django.shortcuts import redirect

def my_view(request, query):
    if query == 'ZY9J3y':
        return redirect('https://www.facebook.com')
    raise Http404('Page does not exist') 

答案 1 :(得分:0)

您可能要为此使用特定模型:

models.py

class Redirection(models.Model):
    shortened = models.CharField("Shortened URL", max_length=50)
    url = models.URLField("Url", help_text='Your shortened URI will be computed')

    class Meta:
        verbose_name = "Redirection"
        verbose_name_plural = "Redirections"

    def save(self, *args, **kwargs):
        if not self.shortened:
            self.shortened = self.computed_hash
        super(Redirection, self).save(*args, **kwargs)

    @property
    def computed_hash(self):
        return your_hashing_algo(self.url)

urls.py

from .views import redirect

urlpatterns = [
    path('(?P<surl>[a-zA-Z0-9_-]+)/', redirect)
]

最后, views.py

from django.views.decorators.cache import cache_page
from django.shortcuts import (get_object_or_404, redirect)
from .models import Redirection

@cache_page(3600)
def redirect(request, surl):
    url = get_object_or_404(Redirection,shortened=surl)
    return redirect(url)

您可以轻松地对其进行调整,以使模型具有寿命,重定向计数器(不过请注意缓存!)