How do I authenticate a urllib2 script in order to access HTTPS web services from a Django site?

前端 未结 2 1403
天命终不由人
天命终不由人 2021-01-03 09:18

everybody. I\'m working on a django/mod_wsgi/apache2 website that serves sensitive information using https for all requests and responses. All views are written to redirect

2条回答
  •  生来不讨喜
    2021-01-03 09:53

    This works on my django setup on https which is inspired by yours. I'm starting to think that the problem is outside this code... Is the server saying anything? I might very well be looking into apache.

    I'm using the following code from my local machine to my server using ssl on nginx, so apache might be the place to look. I suppose one way to narrow it down is to try your script on my login page :) Shoot me an email!

    import urllib
    import urllib2
    import contextlib
    
    
    def login(login_url, username, password):
        """
        Login to site
        """
        cookies = urllib2.HTTPCookieProcessor()
        opener = urllib2.build_opener(cookies)
        urllib2.install_opener(opener)
    
        opener.open(login_url)
    
        try:
            token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0]
        except IndexError:
            return False, "no csrftoken"
    
        params = dict(username=username, password=password, \
            this_is_the_login_form=True,
            csrfmiddlewaretoken=token,
             )
        encoded_params = urllib.urlencode(params)
    
        with contextlib.closing(opener.open(login_url, encoded_params)) as f:
            html = f.read()
    
            print html
            # we're in.
    

提交回复
热议问题