【问题标题】:URL detection and shortening in DjangoDjango中的URL检测和缩短
【发布时间】:2012-08-22 05:58:19
【问题描述】:

我只是想知道 Django 中是否有一种方法可以从一堆文本中检测 URL,然后自动缩短它们。我知道我可以使用 urlize 来检测 url,但我不确定是否可以使用 bitly 或其他东西来缩短链接。

用javascript而不是python来完成这个任务会更好吗?如果是这样的话,我该怎么办?

【问题讨论】:

    标签: javascript python django


    【解决方案1】:

    对于 bit.ly,如果你只是想缩短 URL,它非常简单:

    首先创建一个帐户,然后访问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

    【讨论】:

    • 但是如果我有一整段由用户输入的文本,并且该段落中有一些 URL,该怎么办。所以我希望自动检测到 URL,然后缩短。 bit.ly 会做这一切吗?
    • 不,你必须修改你的模板标签——或者可能写一个模板上下文处理器——来搜索文本;识别链接,然后通过 bit.ly 缩短它们。您可以使用urlize tag 的来源获得“搜索文本中的 URL”功能。
    • 您好,很抱歉再次打扰您,但我尝试为 bitly 编写自定义模板标签,但似乎不起作用。我已经更详细地定义了问题here
    【解决方案2】:

    如果你想使用 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}} %}
    

    这些都不起作用,不知道如何解决它。 欢迎任何帮助!

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-30
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        相关资源
        最近更新 更多