我需要在同一个项目下从一个Django应用程序向另一个应用程序发送POST请求。请求到达,但没有POST数据。
为什么?以及如何正确发送POST数据?
发件人部分,app 1视图:
def get_project_data(request):
if request.method == "POST":
if request.is_ajax():
response = etl_post('get_data', [request.user.project.id], request.POST)
def etl_post(path, identifiers=None, post_data=None):
def date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError
json_data = json.dumps(post_data, default=date_handler) if post_data else None
return _request(path, identifiers, json_data)
def _request(path, identifiers=None, post_data=None, method=None):
data = None
try:
url = urlparse.urljoin(settings.ETL_WEB_API_URL, path)
if identifiers is not None:
for o in identifiers:
url += "/" + str(o)
if post_data:
url += "/"
request = urllib2.Request(url, data=post_data)
request.add_header("Content-Type", "application/json")
request.add_header("X-ETL-Authorization", settings.ETL_WEB_API_KEY)
if method:
request.get_method = lambda: method
result = urllib2.urlopen(request)
data_str = result.read()
if result.getcode() == 200:
data = json.loads(data_str)
else:
logger.error("Unexpected response %s" % result)
except Exception as e:
logger.exception(e.message)
return data
另外,我尝试result = urllib2.urlopen(request, data=post_data)
,但没有成功。
post_data
示例:
{"project_id": "nYhRTAmGkkHSlLr8BfPR", "project_name": "rocket-launch", "salt": "805b2892c16369275eerec4dd401f5f", ...}
(Pdb) type(post_data)
<type 'str'>
接收方部分,应用2视图:
@csrf_exempt
def get_project_data(request, trust_id):
if request.method == 'POST':
pdb.set_trace()
收到的消息:
(Pdb) request
<WSGIRequest: POST '/pipeline/get_project_data/2/'>
(Pdb) request.POST
<QueryDict: {}>
答案 0 :(得分:1)
您正在发送JSON,而不是表单编码数据。这可以在request.body
找到,而不是request.POST
。
我必须说,如果这两个应用程序在同一个项目中,那么在它们之间发送数据要比通过发出HTTP请求更容易。