كيفية جعل Python Urllib2 اتبع إعادة التوجيه والحفاظ على طريقة ما بعد

StackOverflow https://stackoverflow.com/questions/1258428

  •  12-09-2019
  •  | 
  •  

سؤال

أنا أستخدم URLLIB2 لنشر البيانات إلى نموذج. المشكلة هي أن النموذج يرد مع إعادة توجيه 302. وفق بيثون HTTPREDIRECTHERLER. سيتخذ معالج إعادة التوجيه الطلب وتحويله من المنشور للحصول على 301 أو 302. أود الحفاظ على طريقة النشر والبيانات التي تم تمريرها إلى المفتاح. لقد قمت بإجراء محاولة غير ناجحة في مخصص HTTPREDIRECTHANDERLER من خلال إضافة بيانات فقط = req.get_data () إلى الطلب الجديد.

أنا متأكد من أن هذا قد تم من قبل لذلك اعتقدت أنني سأراقب.

ملاحظة: هذا يشبه هذا المشنور و هذا لكنني لا أريد منع إعادة التوجيه، أريد فقط الاحتفاظ ببيانات البريد.

هنا هو بلدي httpredirecthrectherler لا يعمل

class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
    """Return a Request or None in response to a redirect.

    This is called by the http_error_30x methods when a
    redirection response is received.  If a redirection should
    take place, return a new Request to allow http_error_30x to
    perform the redirect.  Otherwise, raise HTTPError if no-one
    else should try to handle this url.  Return None if you can't
    but another Handler might.
    """
    m = req.get_method()
    if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
        or code in (301, 302, 303) and m == "POST"):
        # Strictly (according to RFC 2616), 301 or 302 in response
        # to a POST MUST NOT cause a redirection without confirmation
        # from the user (of urllib2, in this case).  In practice,
        # essentially all clients do redirect in this case, so we
        # do the same.
        # be conciliant with URIs containing a space
        newurl = newurl.replace(' ', '%20')
        return Request(newurl,
                       headers=req.headers,
                       data=req.get_data(),
                       origin_req_host=req.get_origin_req_host(),
                       unverifiable=True)
    else:
        raise HTTPError(req.get_full_url(), code, msg, headers, fp)
هل كانت مفيدة؟

المحلول

هذا هو في الواقع شيء سيء حقا للقيام بمزيد من الفكر في ذلك. على سبيل المثال، إذا قمت بتقديم نموذج لhttp://example.com/add. (مع بيانات النشر لإضافة عنصر) والاستجابة تم إعادة توجيه 302 إلى http://example.com/add. وأنا نشر نفس البيانات التي نشرتها في المرة الأولى التي سأنتهي فيها في حلقة لا حصر لها. لست متأكدا لماذا لم أفكر في هذا من قبل. سأترك السؤال هنا مجرد تحذير لأي شخص آخر يفكر في القيام بذلك.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top