2012-08-22 44 views
1

我只是想知道在Django中是否有一種方法來檢測一堆文本中的URL,然後自動縮短它們。我知道我可以使用urlize來檢測網址,但我不確定我是否可以使用可能會有點或縮短鏈接的東西。Django中的URL檢測和縮短

而且用javascript而不是python來完成這個任務會更好嗎?如果是這種情況,我該怎麼辦?

回答

5

bit.ly的,如果你只是想縮短網址,它很簡單:

首先創建一個帳戶,然後訪問http://bitly.com/a/your_api_key讓你的API密鑰。

發送到API的shorten method的請求,結果是你的短網址:

from urllib import urlencode 
from urllib2 import urlopen 

ACCESS_KEY = 'blahblah' 
long_url = 'http://www.example.com/foo/bar/zoo/hello/' 
endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt' 
req = urlencode(endpoint.format(ACCESS_KEY, long_url)) 
short_url = urlopen(req).read() 

可以換行成一個模板標籤:

@register.simple_tag 
def bitlyfy(the_url): 
    endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt' 
    req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url)) 
    return urlopen(req).read() 

然後在你的模板:

{% bitlyfy "http://www.google.com" %}

注:在標籤位置參數是Django的1.4

的功能如果你想bit.ly API的所有功能,通過在dev.bitly.com/get_started.html閱讀文檔開始,然後下載官方python client

+2

但是如果我有一段由用戶輸入的文本,並且段落中有一些URL,該怎麼辦。所以我想要自動檢測URL,然後縮短。會做點什麼呢? – sankaet

+0

不,您必須修改模板標籤 - 或者編寫模板上下文處理器 - 以搜索文本;確定鏈接,然後通過bit.ly縮短它們。您可以使用[urlize標記]的來源(https://github.com/django/django/blob/master/django/utils/html.py#L171)獲取「在文本中搜索URL」功能。 –

+0

哦,好吧,這很有道理:)非常感謝你! – sankaet

0

如果你想使用Bitly API的模板標籤應該變成:

from django import template from django.conf import settings 

import bitly_api import sys import os 

register = template.Library() 

BITLY_ACCESS_TOKEN="blahhhh" 

@register.simple_tag def bitlyfy(the_url): 
    bitly = bitly_api.Connection(access_token=BITLY_ACCESS_TOKEN) 
    data = bitly.shorten(the_url) 
    return data['url'] 

有一件事我不能在我的模板管理,但:

{% bitlyfy request.get_full_path %} 
{% bitlyfy {{request.get_full_path}} %} 

無論這些作品,不知道如何解決它。 歡迎任何幫助!

0
If you are using bit.ly then the best code to shorten url is: 

import urllib 
import urllib2 
import json 


link = "http://www.example.com/foo/bar/zoo/hello/" 
values = {'access_token' : BITLY_ACCESS_TOKEN, 
      'longUrl'  : link} 
url = "https://api-ssl.bitly.com/v3/shorten" 

data = urllib.urlencode(values) 
req = urllib2.Request(url,data) 
response = (urllib2.urlopen(req).read()).replace('\/', '/') 
bitly_url = (json.loads(response))['data']['url'] 
return bitly_url