我正在学习 Django,所以我设置了一个非常简单的表单/视图/url 示例
- Django 版本 1.5.1
- MATLAB 版本 R2012A
表格.py
from django import forms
import json
class json_input(forms.Form):
jsonfield = forms.CharField(max_length=1024)
def clean_jsonfield(self):
jdata = self.cleaned_data['jsonfield']
try:
json_data = json.loads(jdata)
except:
raise forms.ValidationError("Invalid data in jsonfield")
return jdata
视图.py
from django.http import HttpResponse
from rds.forms import json_input
def testpost(request):
if request.method == 'GET':
form = json_input(request.GET)
if form.is_valid():
return HttpResponse('Were Good Get',mimetype='text/plain')
elif request.method == 'POST':
form = json_input(request.POST)
if form.is_valid():
return HttpResponse('Were Good Post',mimetype='text/plain')
else:
return HttpResponse('Not GET or POST.',mimetype='text/plain')
此视图映射到urls.py中的 url
url(r'^test2$','rds.views.testpost'),
因此,当我跳入本地机器 django 上的 python manage.py shell 时,我可以发出以下命令并获得预期的响应:
>>> from django.test.client import Client
>>> c = Client()
>>> r = c.post('/test2',{'jsonfield': '{"value":100}'})
>>> print r
Content-Type: text/plain
Were Good Post
>>> r = c.get('/test2',{'jsonfield': '{"value":100}'})
>>> print r
Content-Type: text/plain
Were Good Get
但是,当我在外部机器上跳转到 MATLAB 并发出以下命令时。(注意从 MATLAB 执行此操作是项目要求)
json = '{"value":100}';
% GET METHOD FOR JSON FORM
[gresponse,gstatus]=urlread('http://aq-318ni07.home.ku.edu/django/test2','Get',{'jsonfield' json});
% POST METHOD FOR JSON FORM
[presponse,pstatus]=urlread('http://aq-318ni07.home.ku.edu/django/test2','Post',{'jsonfield' json});
>> gresponse
gresponse =
Were Good Get
>> presponse
presponse =
''
我四处寻找解决方案,但真的找不到任何东西。我已经发现它可能是 CSRF 的一个问题(我仍在弄清楚)。任何提示或想法将不胜感激。
谢谢你。
编辑:
Django是通过Apache暴露的,这里是配置。
################################################
# Django WSGI Config
################################################
WSGIScriptAlias /django /var/django/cdp/cdp/wsgi.py
WSGIPythonPath /var/django/cdp
<Directory /var/django/cdp/cdp>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
################################################