2012-08-25 82 views
3

我有一个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 

回答

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) 

然后,您应该能够处理POST在你的第二个Django的服务器,以及相应的结果返回给第一个Django服务器。

+0

谢谢!我会尝试自己的行为。实际上,处理上述请求的服务器由django socketio(cmd:runserver_socketio)运行,原始服务器由用于处理常见请求的'runserver'或'runfcgi'命令行运行。也就是说,我希望socketio服务器处理即时消息,但请求由另一台接受来自浏览器的请求的服务器传递。并且,浏览器连接到socketio服务器,并且我希望服务器直接向浏览器发送响应。你以前处理过类似的问题吗?谢谢,期待您的回复。 – liao

+0

我从来没有用过django socketio。我只使用runserver与不同的端口或apache进行本地测试。 – smang

+0

另一个问题,url“url(r'^ push_msg/$','chat.events.on_message')”有问题吗? – liao

相关问题