如何从一个django服务器发送请求到另一个服务器

时间:2012-08-25 05:14:17

标签: django

我有一个django问题。我想发送来自浏览器或业务逻辑的数据 在我的django服务器上到另一个django服务器或只是相同的服务器但不同的端口,来处理请求。我能怎么做?我试图使用套接字,但似乎没有用。

Following is my code:
accept the client's request:
def im(request):
    userp = None
    try:
        userp = UserProfile.objects.get(user = request.user)
    except:
        pass
    if not userp:
        return HttpResponse("error")
    print '111'
    if request.method == "GET":
        import json
        msg = json.loads(request.GET.get('msg'))
        try: 
            msg['from_id'] = userp.id
            if msg.get('type', '') == 'sync': #页面同步消息
                msg['to_id'] = userp.id
            push_msg(msg)
            return HttpResponse("success")
        except:
            return HttpResponse("error")
        #return HttpResponseRedirect("http://127.0.0.1:9000/on_message")
    return HttpResponse("error")

helper.py:push_msg:
def push_msg(msg):
    print '111'
    params = str(msg)
    headers = {"Content-type":"application/x-www-form-urlencoded", "Accept":"text/plain"}
    conn = httplib.HTTPConnection("http://127.0.0.1:9000/push_msg/")
    conn.request("POST", "/cgi-bin/query", params, headers)

url(r'^push_msg/$', 'chat.events.on_message')
events.py:on_message
def on_message(request):
    msg = request.POST.get('msg')
    msg = eval(msg)
    try:
        print 'handle messages'
        from_id = int(msg['from_id'])
        to_id = int(msg['to_id'])
        user_to = UserProfile.objects.get(id = msg['to_id'])
        django_socketio.broadcast_channel(msg, user_to.channel)
        if msg.get('type', '') == 'chat':
            ct = Chat.objects.send_msg(from_id=from_id,to_id=to_id,content=data['content'],type=1)
            ct.read = 1
            ct.save()
    except:
        pass 

2 个答案:

答案 0 :(得分:2)

使用python请求模块执行此请求具有更多功能,然后使用httplib2并且它非常易于使用http://docs.python-requests.org/

答案 1 :(得分:0)

我已经使用httplib2来完成类似的事情。从httplib2文档中尝试:

import httplib2
import urllib
data = {'name': 'fred', 'address': '123 shady lane'}
body = urllib.urlencode(data)
h = httplib2.Http()
resp, content = h.request("http://example.com", method="POST", body=body)

然后,您应该能够处理第二台django服务器中的 POST ,并将相应的结果返回给第一台django服务器。