login to my web2py website with python 3 requests

121 views
Skip to first unread message

lucas

unread,
Mar 26, 2021, 2:54:04 AM3/26/21
to web2py-users
I'm trying to login to my own web2py website using requests in python 3.9.2.  I can't seem to do it.  my code is below.  may you please review and let me know what I'm overlooking?  thank you in advance, Lucas

cookie = MozillaCookieJar('cookies')
if os.path.exists('cookies'):
    cookie.load(ignore_discard=True, ignore_expires=True)
session = requests.Session()
session.cookies = cookie
BS = BeautifulSoup(response.text, 'lxml')
data = { 'email':"mye...@rutgers.edu", 'password':"password", 'remember_me':"on" }
for i, e in enumerate(BS.select('input[name]')):
    print(i, e)
    if (e['name'][0] == '_'):
        data[e['name']] = e['value']
import random, string
from requests_toolbelt import MultipartEncoder
boundary = '----WebKitFormBoundary' + ''.join(random.sample(string.ascii_letters + string.digits, 16))
m = MultipartEncoder(fields=data, boundary=boundary)
print(data)
headers = {
    'Origin': "https://website.org",
    'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'Connection': 'keep-alive',
    'User-Agent': user_agent,
    'Content-Type': m.content_type
}
print(m)
print(headers)
print(response.url, response.history)
print()
print(response.status_code, response.encoding, response.headers, "...\n", response.text)
cookie.save()

lucas

unread,
Mar 26, 2021, 5:30:37 AM3/26/21
to web2py-users
I found my error.  on the lines where I have "response = requests.get(..." and "response = requests.post(...", I should have "response = session.get(..." and "response = session.post(..." so that web2py can set and get the cookie data and the site headers through the session.  I am able to login now under python and it is working great.  thank you again in advance and I love web2py and python.  Lucas

黄祥

unread,
Apr 1, 2021, 10:28:07 PM4/1/21
to web2py-users
same, but use requests.cookie instead
e.g.
import requests
import json
import os
import random, string
from bs4 import BeautifulSoup
from requests_toolbelt import MultipartEncoder

cookie = requests.cookies.RequestsCookieJar()
if os.path.exists('cookies'):
    cookie.load(ignore_discard=True, ignore_expires=True)

session = requests.Session()
session.cookies = cookie


data = { 'username':"user0", 'password':"password", 'remember_me':"on" }
print(data)

BS = BeautifulSoup(response.text, 'html.parser')
for i, e in enumerate(BS.select('input[name]')):
    print(i, e)
    if (e['name'][0] == '_'):
        data[e['name']] = e['value']

m = MultipartEncoder(fields=data)
print(m)

headers = {
    'Content-Type': m.content_type
}
print(headers)

print(response.url)

print(response.url)
Reply all
Reply to author
Forward
0 new messages