在 Django 中製作一個 URL 縮短器應用程式


在本文中,我們來看看如何在 Django 中製作一個 URL 縮短器應用程式。這是一個簡單的應用程式,它將把一個長 URL 轉換成一個短 URL。我們將會使用一個 Python 庫來實現這個功能,而不是任何 Django 專用庫,因此你可以在任何 Python 專案中使用此程式碼。

首先,建立一個 Django 專案和一個應用程式。進行一些基本設定,如在 settings.py 中包含應用程式的 URL 和在 INSTALLED_APPS 中包含應用程式。

示例

安裝 pyshorteners 模組 −

pip install pyshorteners

在應用程式的 urls.py 中 −

from django.urls import path
from .views import url_shortner

urlpatterns = [
   path('', url_shortner.as_view(), name="url-shortner"),
]

在這裡,我們在 home url 上設定檢視集作為檢視。

現在在 views.py 中 −

from django.shortcuts import render
import pyshorteners
from django.views import View

class url_shortner(View):
   def post(self, request):
      long_url = 'url' in request.POST and request.POST['url']
      pys = pyshorteners.Shortener()
      short_url = pys.tinyurl.short(long_url)
      return render(request,'urlShortner.html', context={'short_url':short_url,'long_url':long_url})

   def get(self, request):
      return render(request,'urlShortner.html')

在這裡,我們使用兩個請求處理函式建立了一個檢視,get 處理程式將呈現前端 html,而post 處理程式將獲取長 URL,並使用短 URL 重新呈現我們的前端。

在應用程式目錄中建立一個 templates 資料夾,並在其中新增 urlShortner.html,然後編寫此內容 −

<!DOCTYPE html>
<html>
   <head>
      <title>Url Shortner</title>
   </head>
   <body>
      <div >
         <h1 >URL Shortner Application</h1>
         <form method="POST">{% csrf_token %}
            <input type="url" name="url" placeholder="Enter the link here" required>
            <button >Shorten URL</button>
         </form>
      </div>
      </div>
      {% if short_url %}
      <div>
         <h3>Your shortened URL /h3>
         <div>
            <input type="url" id="short_url" value={{short_url}}> <button name="short-url">Copy URL</button> <small id="copied" class="px-5"></small>
         </div>
         <br>
         <span><b>Long URL: </b></span> <a href="{{long_url}}">{{long_url}}</a>
      </div>
      {%endif%}
   </body>
</html>

這是前端,它將獲取長 URL 併發送請求,然後它返回短 URL。

輸出

更新於: 2021-08-26

335 次瀏覽

職業生涯助你邁出第一步

完成課程,獲得認證

開始使用
廣告