32

Jsonを出力してDjangoでRESTApiを作成しようとしています。ターミナルでcurlを使用してPOSTリクエストを行うと、問題が発生します。私が得るエラーは

このURLをPOST経由で呼び出しましたが、URLがスラッシュで終わっておらず、APPEND_SLASHが設定されています。Djangoは、POSTデータを維持している間はスラッシュURLにリダイレクトできません。フォームを127.0.0.1:8000/add/(末尾のスラッシュに注意)を指すように変更するか、Django設定でAPPEND_SLASH=Falseを設定します。

私のurl.pyは

    from django.conf.urls.defaults import patterns, include, url
import search

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',

    url(r'^query/$', 'search.views.query'),
    url(r'^add/$','search.views.add'),
)

そして私の見解は

# Create your views here.
from django.http import HttpResponse
from django.template import Context,loader
import memcache
import json

def query(request):
    data=['a','b']

    mc=memcache.Client(['127.0.0.1:11221'],debug=0)
    mc.set("d",data);

    val=mc.get("d")

    return HttpResponse("MEMCACHE: %s<br/>ORIGINAL: %s" % (json.dumps(val),json.dumps(data)) )

def add(request):
    #s=""
    #for data in request.POST:
    #   s="%s,%s" % (s,data)
    s=request.POST['b']
    return HttpResponse("%s" % s)

私はそれがJsonを与えていないことを知っていますが、ターミナルでPOSTリクエストを行うときに上記の問題が発生しています

curl http://127.0.0.1:8000/add/ -d b=2 >> output.html

でも、私はdjangoを初めて使用します。

4

8 に答える 8

52

まず、リクエストをhttp://127.0.0.1/add/notに送信していることを確認してくださいhttp://127.0.0.1/add

@csrf_exempt第 2 に、 cURL から適切なトークンを送信していないため、デコレータを追加してビューを csrf 処理から除外することもできます。

于 2012-03-16T20:43:48.880 に答える
43

For URL consistency, Django has a setting called APPEND_SLASH, that always appends a slash to the end of the URL if it wasn't sent that way to begin with. This ensures that /my/awesome/url/ is always served from that URL instead of both /my/awesome/url and /my/awesome/url/.

However, Django does this by automatically redirecting the version without the slash at the end to the one with the slash at the end. Redirects don't carry the state of the request with them, so when that happens your POST data is dropped.

All you need to do is ensure that when you send your POST, you send it to the version with the slash at the end.

于 2012-03-16T14:24:08.333 に答える
1

Html でアクションを変更します。私の場合はうまくいきました。

<form action="{% url 'add' %}" method="post">
    {% csrf_token %}
    ...
</form>
于 2020-05-04T11:09:51.947 に答える