Python requests adapt hyper.contrib.HTTP20Adapter without using Session object

Viewed 142

I'm writing a project which is getting credentials from site, then login to site, do some action etc. But I have a few issue

When I use this code, I got UnknownProtocol('HTTP/2') error:

from requests import get

def get_credentials(proxy, url):
    c = get(url, proxies={"http": proxy, "https": proxy}, verify=False)

    cookie = {}

    cookie_helper = c.cookies.get_dict()
    csrf_token = c.text.split('name="csrf_token" value="')[1].split('">')[0]
    
    cookie["session"] = cookie_helper["session"]
    
    return csrf_token, cookie

So I used hyper.contrib.HTTP20Adapter and solved the issue with that code:

from requests import Session
from hyper.contrib import HTTP20Adapter

def get_credentials(proxy, url):
    s = Session()
    s.mount('url', HTTP20Adapter())
    c = s.get(url, proxies={"http": proxy, "https": proxy}, verify=False)

    cookie = {}

    cookie_helper = c.cookies.get_dict()
    csrf_token = c.text.split('name="csrf_token" value="')[1].split('">')[0]
    
    cookie["session"] = cookie_helper["session"]
    
    return csrf_token, cookie

This time HTTP/2 issue solved but I got key error (cookie) because of request has been sent with Session object and because of that, there is not any cookie returned. Also I used directly hyper module but at this time, requests sending directly (can not add proxy configuration)

Also I need to do solution for that function too:

def return_logged_in_response(username, password, csrf_token, cookie, proxy, url):
    response = post(url, cookies=cookie, data={"csrf_token": csrf_token, "password": password,  "username": username}, proxies={"http": proxy, "https": proxy}, verify=False)
    
    return response   

So, I need your help about writing this function


EDIT

I used directly return session object like that:

from requests import Session
from hyper.contrib import HTTP20Adapter

def get_credentials(proxy, url):
    s = Session()
    s.mount(url, HTTP20Adapter())
    c = s.get(url, proxies={"http": proxy, "https": proxy}, verify=False)

    csrf_token = c.text.split('name="csrf_token" value="')[1].split('">')[0]
    
    return csrf_token, s

But this time directly ignoring proxies parameter and request not sending correctly (giving 400 bad request). Also tried this but still ignoring proxy parameter:

from requests import Session
from hyper.contrib import HTTP20Adapter

def get_credentials(proxy, url):
    s = Session()

    s.mount(url, HTTP20Adapter())
    s.proxies.update({'http': proxy, 'https': proxy })

    c = s.get(url, proxies={"http": proxy, "https": proxy}, verify=False)
    csrf_token = c.text.split('name="csrf_token" value="')[1].split('">')[0]
    
    return csrf_token, s
0 Answers
Related