2013-10-11 23 views
0

我想通过django模板来缩短url的位置。我写了下面的模板标签代码,但是我得到了下面的错误:似乎无法想象它整天!ValueError:Django中未知的url类型

ValueError: unkown url type:unknown url type: https%3A//api- ssl.bitly.com/v3/shorten%3Faccess_token%3DR_b622c9b2d53899697d6a78c088895f20%26longUrl%3Dhttp%3A//www.google.com%26format%3Dtxt 




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

模板

{% bitlys 'http://www.manman.com' %} 

回答

1

,你可能只需要引用long_url,而不是整个字符串

endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt' 
req = endpoint.format(settings.ACCESS_KEY, urllib.quote(long_url)) 
return urlopen(req).read() 
+0

下你说的话后,我把REQ = urllib.quote(endpoint.format (long_url)),我得到错误“元组索引超出范围” – picomon

+0

我认为需要包含访问密钥?因为它缩短了网址。请进一步解释你的真正含义。 – picomon

+0

你不应该编码URL的协议部分。这就是为什么“api-ssl.bitly.com”;看起来像“https%3A // api-ssl.bitly.com” 'endpoint ='https://api-ssl.bitly.com/v3/shorten?access_token=%s&longUrl=%s&format=txt'%( settings.ACCESS_KEY,urllib.quote(long_url)) return urlopen(endpoint).read()' – toad013