缩短的链接redi

2024-10-01 02:18:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做django的链接缩短器。我想知道我怎么能重定向到原来的网址缩短。 例如,我有一个链接127.0.0.1:8000/ZY9J3y,我需要它将我转移到facebook.com。问题是我应该在我的url.py中添加什么才能将这样的链接重定向到它们原来的位置??你知道吗


Tags: djangopycomurlfacebook链接重定向网址
2条回答

您可以直接在网址.py地址:

网址.py

from django.views.generic import RedirectView

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

或者如评论中所建议的,您可以使用视图来确定要重新定向到的位置:

网址.py

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

视图.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') 

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

型号.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)

网址.py

from .views import redirect

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

最后,视图.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)

你可以很容易地调整它,给模型一个寿命,重定向计数器(注意缓存!)你知道吗

相关问题 更多 >