2012-04-29 22 views
0

我正在使用Python和Django框架。當我想使用超鏈接時,我不應該手動編寫完整的URL?我必須使用一些函數返回域名,並手動連接到它的路徑。那麼,我怎樣才能得到域名呢?
像:

http://www.domain.com/path/to/file.ext

對於這一點,我想寫:

"http://"+somefunction()+"/path/to/file.ext" 

是否存在的$_SERVER['HTTP_URI']在Python等效。

+0

HTTP_HOST或HTTP_URI? – Gumbo

+0

@ramesh kumar這也可能取決於您的Apache/Nginx HTTP配置。 –

回答

0

對於您的需求Django還提供Sites framefork

>>> from django.contrib.sites.models import Site 
>>> Site.objects.get_current().domain 
'example.com' 
>>> 'http://%s/path/to/file.ext' % Site.objects.get_current().domain 
'http://example.com/path/to/file.ext' 
2

對於當前請求的原裝主機,你可以使用request.get_host()或直接訪問request['HTTP_HOST']

0

沒有直接回答你的問題,但Django有很多處理URL構造的方法,所以你不需要硬編碼的東西。

裏面Python代碼:

from django.core.urlresolvers import reverse 
from django.http import HttpResponseRedirect 

def my_redir_view(request): 
    return HttpResponseRedirect(reverse('another_view')) 

內模板:

<a href="{% url 'logout' %}">Logout</a> 

構建絕對URL(關於在需要它們的相對罕見的情況下):

redirect_uri = request.build_absolute_uri(reverse('openid_auth')) 

一般你不想做手動的URL構建 - 上面的方法是你的朋友。