質問

I want to use an instance of mechanize as a session variable in django because it has cookies. (Building some web app that parses data of a website with login)

        browser = mechanize.Browser()

        browser.open('https://www.somewebsite.html')
        browser.select_form(nr=0)
        browser.form['j_username'] = 'test'
        browser.form['j_password'] = 'test'

        browser.submit() #now browser has cookies in this instance

        request.session['browser'] = browser   #this doesn't work

So that didn't work, so I tried using a cookiejar so that I could put that as session variable but I guess it leads to the same problem that I am trying to put an object as session variable...

        cj = cookielib.LWPCookieJar()
        browser.set_cookiejar(cj)
        #some code here

        request.session['cj'] = cj #doesn't work again

What would be a way to do this? I'm bit clueless :/

役に立ちましたか?

解決

Django uses Pickling to serialize objects into session values. My guess is that the mechanize Browser object has not implemented the Pickle serialization protocol, and thus cannot be converted into a valid string that can be loaded back into a Python object.

I think your best bet is probably to extract the cookies from the Browser session and convert them into a string, save them to your user's session, and re-instantiate a Browser object with those saved cookie values (if mechanize allows that). Good luck!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top