經過幾個小時的閱讀手冊和其他幫助,最後我得到了我的nginx + uwsgi1.9 + django1.6 + python3.3服務器。wsgi請求對象中的不同環境
但現在我有問題(在我的理解東西的MB問題) - 如何從請求獲取POST數據?我的意思是如何正確地得到它。
在Django視圖的代碼:
def info(request):
print(request)
return HttpResponse(request)
請求到服務器:
http://127.0.0.1:8000/info/
{
"test":"test"
}
和有趣的部分 - 輸出在uwsgi日誌(POST和GET http://stardict.sourceforge.net/Dictionaries.php下載):
<WSGIRequest
path:/info/,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{},
META:{'CONTENT_LENGTH': '24',
'CONTENT_TYPE': 'application/json',
'CSRF_COOKIE': 'upJxA8TWO0nhKACr0dfU46Qyu0DzzUTR',
'DOCUMENT_ROOT': '/usr/share/nginx/html',
'HTTP_ACCEPT': '*/*',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_CONTENT_LENGTH': '24',
'HTTP_CONTENT_TYPE': 'application/json',
'HTTP_COOKIE': '',
'HTTP_HOST': '127.0.0.1:8000',
'HTTP_ORIGIN': 'chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo',
'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
'PATH_INFO': '/info/',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '53315',
'REQUEST_METHOD': 'POST',
'REQUEST_URI': '/info/',
'SCRIPT_NAME': '',
'SERVER_NAME': 'django',
'SERVER_PORT': '8000',
'SERVER_PROTOCOL': 'HTTP/1.1',
'uwsgi.node': b'',
'uwsgi.version': b'1.9.18.2',
'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='UTF-8'>,
'wsgi.file_wrapper': <built-in function uwsgi_sendfile>,
'wsgi.input': <uwsgi._Input object at 0x7fa4ec6b8ee8>,
'wsgi.multiprocess': True,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)}>
和響應(與請求到服務器相同):
{
"test":"test"
}
我做錯了什麼?
request.POST
and
request.POSt.dict()
返回空的字典。
所以問題是如何在代碼中獲取POST數據以及爲什麼當我使用環境時它看起來如此不同?
UPD: return HttpResponse(str(request)) - 返回WSGIRequest對象而不是POST數據給我。但仍然不知道如何在代碼中獲取POST數據。
UPD2: uwsgi配置:
[uwsgi]
module = mysite.wsgi
master = true
processes = 5
socket = :8001
daemonize = /var/log/uwsgi/mysite.log
touch-reload = /tmp/uwsgi-touch
post-buffering = 1
UPD3: 版本的軟件:
Python 3.3.2
Django 1.6.2
uWSGI 1.9.18.2
UPD4:
最終代碼:
if request.method == "POST":
if request.META["CONTENT_TYPE"] == "application/json":
result = json.loads(request.body.decode())
else: result = request.POST.dict()
return HttpResponse(json.dumps(result), content_type="application/json")
這就是我真正想要的。 當我將數據發送到服務器
POST
Content-Type: application/x-www-form-urlencoded
a=1
或:
POST
Content-Type: application/json
{"a":"1"}
我看到相同的響應(和代碼變量):
Content-Type: application/json
{"a": "1"}
是的,它的json。我以爲它只是字符串或QueryDict對象。但爲什麼print()和HttpResponse()的結果有差異?爲什麼它不是同一個WSGIRequest或POST對象? - 亞歷克斯T 31分鐘前 –
不知道我按照你的問題... –
呃...我的意思是爲什麼我看到HttpResponse(請求)和打印(請求)之間的不同結果? –