2012-08-25 80 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

相關問題