【发布时间】:2011-01-14 02:49:37
【问题描述】:
django web 应用需要对外部 url 进行 ajax 调用。在开发中,我直接从 django 服务,所以我有一个跨域问题。为ajax调用编写代理的django方式是什么?
【问题讨论】:
django web 应用需要对外部 url 进行 ajax 调用。在开发中,我直接从 django 服务,所以我有一个跨域问题。为ajax调用编写代理的django方式是什么?
【问题讨论】:
这是 Django 的一个非常简单的代理实现。
from django.http import HttpResponse
import mimetypes
import urllib2
def proxy_to(request, path, target_url):
url = '%s%s' % (target_url, path)
if request.META.has_key('QUERY_STRING'):
url += '?' + request.META['QUERY_STRING']
try:
proxied_request = urllib2.urlopen(url)
status_code = proxied_request.code
mimetype = proxied_request.headers.typeheader or mimetypes.guess_type(url)
content = proxied_request.read()
except urllib2.HTTPError as e:
return HttpResponse(e.msg, status=e.code, mimetype='text/plain')
else:
return HttpResponse(content, status=status_code, mimetype=mimetype)
这会将来自 PROXY_PATH+path 的请求代理到 TARGET_URL+path。 通过将这样的 URL 模式添加到 urls.py 来启用和配置代理:
url(r'^PROXY_PATH/(?P<path>.*)$', proxy_to, {'target_url': 'TARGET_URL'}),
例如:
url(r'^images/(?P<path>.*)$', proxy_to, {'target_url': 'http://imageserver.com/'}),
将向 http://localhost:8000/images/logo.png 发出请求,获取并返回 http://imageserver.com/logo.png 中的文件 em>。
查询字符串被转发,而 HTTP 标头(如 cookie 和 POST 数据)则不被转发(如果需要,很容易添加)。
注意:这主要用于开发用途。在生产环境中处理代理的正确方法是使用 HTTP 服务器(例如 Apache 或 Nginx)。
【讨论】:
我在尝试自己回答时遇到了这个问题,并找到了这个 Django 应用程序:
http://httpproxy.yvandermeer.net/
...对于我需要的东西来说有点重量级(录制和播放,需要一个同步数据库来添加模型内容)。但是你可以在它的通用代理视图中看到它使用的代码,它基于httplib2:
http://bitbucket.org/yvandermeer/django-http-proxy/src/1776d5732113/httpproxy/views.py
【讨论】:
【讨论】: