11

Piston を使用して Django に REST サポートを提供しようとしています。提供されたドキュメントに従ってハンドラーを実装しました。問題は、リソースを「読み取り」および「削除」できるが、「作成」または「更新」できないことです。関連する API にアクセスするたびに、400 Bad request エラーが発生します。

この一般的に入手可能なコード スニペットを使用して、csrf の Resource クラスを拡張しました。

class CsrfExemptResource(Resource):
    """A Custom Resource that is csrf exempt"""
    def __init__(self, handler, authentication=None):
        super(CsrfExemptResource, self).__init__(handler, authentication)
        self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)

私のクラス (コード スニペット) は次のようになります。

user_resource = CsrfExemptResource(User)

class User(BaseHandler):
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')

    @require_extended
    def create(self, request):
        email = request.GET['email']
        password = request.GET['password']
        phoneNumber = request.GET['phoneNumber']
        firstName = request.GET['firstName']
        lastName = request.GET['lastName']
        self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
        return rc.CREATED

POST 操作を使用して create メソッドを機能させる方法を教えてください。

4

7 に答える 7

10

これは、ExtJSがヘッダーのcontent-typeに「charset=UTF-8」を入れているという事実をPistonが気に入らないために発生しています。

ミドルウェアを追加してコンテンツタイプをもう少しPythonに適したものにすることで簡単に修正できます。アプリケーションのベースディレクトリに、middleware.pyというファイルを作成します。

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if request.META['CONTENT_TYPE'] == 'application/x-www-form-urlencoded; charset=UTF-8':
            request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        return None

次に、このミドルウェアをsettings.pyに含めるだけです。

MIDDLEWARE_CLASSES = (
    'appname.middleware.ContentTypeMiddleware',
)
于 2011-03-25T00:58:27.390 に答える
7

提案されたソリューションはまだ機能しませんでした(django 1.2.3 /ピストン0.2.2)ので、joekrellソリューションを微調整し、これが最終的に機能します(POSTとPUTのみを使用していますが、おそらく他の動詞をリストに追加できます)::

class ContentTypeMiddleware(object):

def process_request(self, request):

    if request.method in ('POST', 'PUT'):
        # dont break the multi-part headers !
        if not 'boundary=' in request.META['CONTENT_TYPE']:
            del request.META['CONTENT_TYPE']

と:

MIDDLEWARE_CLASSES = (
'appname.middleware.ContentTypeMiddleware',
)

私は副作用に気づいていませんが、それが防弾であることを約束することはできません。

于 2011-04-09T09:40:23.623 に答える
4

他の人が言ったことのいくつかを組み合わせて、任意のコンテンツ タイプ、たとえば json のサポートを追加しました...

class ContentTypeMiddleware(object):
    def process_request(self, request):
        if request.method in ('POST', 'PUT') and request.META['CONTENT_TYPE'].count(";") > 0:
            request.META['CONTENT_TYPE'] = [c.strip() for c in request.META['CONTENT_TYPE'].split(";") ][0]
        return None
于 2011-08-24T14:32:40.147 に答える
4

エリックのソリューションが最もうまく機能すると思いましたが、管理者に保存するときに問題が発生しました。他の誰かがそれに遭遇した場合、この調整はそれを修正するようです:

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if request.method in ('POST') and not 'boundary=' in request.META['CONTENT_TYPE']:
            request.META['CONTENT_TYPE'] = [c.strip() for c in request.META['CONTENT_TYPE'].split(";") ][0]
        return None
于 2011-10-05T16:13:34.410 に答える
1

utils.py で、これを変更します。

def content_type(self):
    """
    Returns the content type of the request in all cases where it is
    different than a submitted form - application/x-www-form-urlencoded
    """
    type_formencoded = "application/x-www-form-urlencoded"

    ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)

    if ctype.strip().lower().find(type_formencoded) >= 0:
        return None

    return ctype

https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type

于 2011-01-21T19:04:06.390 に答える
1

これは、微調整した後、私のために働いた解決策です:

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if 'charset=UTF-8' in request.META['CONTENT_TYPE']:
            request.META['CONTENT_TYPE'] = request.META['CONTENT_TYPE'].replace('; charset=UTF-8','')
        return None
于 2013-10-23T12:58:58.337 に答える