2012-08-25 2 views
3

장고 문제가 있습니다. 내 장고 서버에있는 브라우저 또는 비즈니스 로직 의 데이터를 다른 장고 서버 또는 다른 서버로 보내려는 요청을 처리하려고합니다. 어떻게해야합니까? 내가 소켓을 사용하여 달성하려했지만 아무런 문제가없는 것 같습니다.하나의 장고 서버에서 다른 서버로 요청을 보내는 방법

 
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을 처리하고 첫 번째 장고 서버에 적절한 결과를 반환 할 수 있어야한다. 이 요청을 할

+0

감사를 사용하는 것은 매우 쉽습니다. 사실, 위 요청을 처리하는 서버는 django socketio (cmd : runserver_socketio)에 의해 실행되고, 원래 서버는 일반적인 요청을 처리하는 데 사용되는 'runserver'또는 'runfcgi'명령 줄에 의해 실행됩니다. 즉, socketio 서버가 인스턴트 메시징을 처리하기를 원하지만 요청은 브라우저의 모든 요청을 받아들이는 다른 서버에 의해 전달됩니다. 그리고 브라우저가 socketio 서버에 연결되어 있고 서버가 브라우저에 직접 응답을 보내길 원합니다. 이전에 비슷한 문제를 처리 했습니까? 감사합니다. 회신을 기다리십시오. – liao

+0

나는 이전에 장고 소켓오를 사용한 적이 없다. 필자는 지역 테스트를 위해 다른 포트 또는 아파치가있는 runserver만을 사용했습니다. – smang

+0

또 다른 질문은 "url (r '^ push_msg/$', 'chat.events.on_message') URL에 문제가 있습니까? – liao

2

사용 파이썬 요청 모듈은 다음 httplib2을 더 많은 기능을 가지고 있으며 나는 당신의 방법을 시도 할 것이다! http://docs.python-requests.org/

+0

답장을 보내 주셔서 감사합니다. – liao

관련 문제