How to use the requests.session function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Neboer / ipgw-py-manager / main.py View on Github external
setting_file_location = os.path.join(os.getenv("HOME"), ".ipgw-py-manager", "settings.json")
try:
    with open(setting_file_location, "r") as file:
        settings = json.load(file)
except FileNotFoundError:
    print("first time to use, please install configure file to user dictionary by running install.py.")
flags_sum = args.login + args.logout_all + (args.uid is not None)
if flags_sum == 0:
    if args.config:
        os.system(args.config + " " + setting_file_location)
        exit(0)

if flags_sum > 1:
    print("error, multi-action is not allowed")

global_session = requests.session()
global_session.max_redirects = 2
cookie_is_set = False
if args.nocookie or args.recookie or (args.username is not None):
    read_settings_into_session(settings, global_session, False)
else:
    read_settings_into_session(settings, global_session, True)
    cookie_is_set = True

if args.login:
    whole_process(args.username, global_session, settings, True)

if args.uid:
    if Device.logout_sid(args.uid, global_session):
        print("logout {} successful".format(args.uid))
    else:
        print("logout {} error".format(args.uid))
github paulwinex / houdini_install_script / houdini_install.py View on Github external
return is_admin


# define OS
if os.name == 'nt':
    category = 'win'
    if not windows_is_admin():
        print 'Run this script as administrator'
        sys.exit()
elif os.name == 'posix':
    category = 'linux'
else:
    raise Exception('This OS not supported')

# create client
client = requests.session()
# Retrieve the CSRF token first
URL = 'https://www.sidefx.com/login/'
print 'Login on %s ...' % URL
client.get(URL)  # sets cookie
csrftoken = client.cookies['csrftoken']
# create login data
login_data = dict(username=username, password=password, csrfmiddlewaretoken=csrftoken, next='/')
# login
r = client.post(URL, data=login_data, headers=dict(Referer=URL))

# goto daily builds page
print 'Get last build version...'
page = client.get('http://www.sidefx.com/download/daily-builds/')

# parse page
s = BeautifulSoup(page.content, 'html.parser')
github packit-service / ogr / ogr / services / pagure / service.py View on Github external
def __init__(
        self,
        token: str = None,
        instance_url: str = "https://src.fedoraproject.org",
        read_only: bool = False,
        insecure: bool = False,
        **_,
    ) -> None:
        super().__init__()
        self.instance_url = instance_url
        self._token = token
        self.read_only = read_only

        self.session = requests.session()

        adapter = requests.adapters.HTTPAdapter(max_retries=5)

        self.insecure = insecure
        if self.insecure:
            self.session.mount("http://", adapter)
        else:
            self.session.mount("https://", adapter)

        self.header = {"Authorization": "token " + self._token} if self._token else {}
github blackboard / BBDN-REST-DEMO_Python / demo / course.py View on Github external
def getCourse(self, token):
        print('[Course:getCourse()] token: ' + token)
        #"Authorization: Bearer $token"
        authStr = 'Bearer ' + token
        print('[Course:getCourses] authStr: ' + authStr)
        session = requests.session()
        session.mount('https://', Tls1Adapter()) # remove for production
        print("[Course:getCourse()] GET Request URL: https://" + self.target_url + self.course_Path + COURSEEXTERNALID)

        r = session.get("https://" + self.target_url + self.course_Path+COURSEEXTERNALID, headers={'Authorization':authStr},  verify=False)

        print("[Course:getCourse()] STATUS CODE: " + str(r.status_code) )
        print("[Course:getCourse()] RESPONSE:")
        if r.text:
            res = json.loads(r.text)
            print(json.dumps(res,indent=4, separators=(',', ': ')))
        else:
            print("NONE")
        done = False
github pantsbuild / pants / contrib / go / src / python / pants / contrib / go / subsystems / archive_retriever.py View on Github external
def _session(self):
    session = requests.session()
    # Override default http adapters with a retriable one.
    retriable_http_adapter = requests.adapters.HTTPAdapter(max_retries=self.get_options().retries)
    session.mount("http://", retriable_http_adapter)
    session.mount("https://", retriable_http_adapter)
    return session
github TestInABox / stackInABox / stackinabox / util / requests_mock / core.py View on Github external
def __init__(self):
        # Keep track of all the original functions that will
        # get replaced during a context operation
        self.__replacements = {
            'requests.request': requests.request,
            'requests.get': requests.get,
            'requests.options': requests.options,
            'requests.head': requests.head,
            'requests.post': requests.post,
            'requests.put': requests.put,
            'requests.patch': requests.patch,
            'requests.delete': requests.delete,
            'requests.session': requests.session,
            'requests.Session': requests.Session,
            'requests.sessions.Session': requests.sessions.Session
        }
github Ascotbe / Medusa / Php / PhpstudyPhpmyadminDefaultpwd.py View on Github external
port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    global resp
    global resp2
    try:
        payload_url = scheme+"://"+url+ ':' + str(port)+payload
        headers = {
            'Accept-Encoding': 'gzip, deflate',
            'Accept': '*/*',
            "Content-Type": "application/x-www-form-urlencoded",
            'User-Agent': RandomAgent,
        }
        s = requests.session()
        if ProxyIp!=None:
            proxies = {
                # "http": "http://" + str(ProxyIps) , # 使用代理前面一定要加http://或者https://
                "http": "http://" + str(ProxyIp)
            }
            resp = s.post(payload_url, data=post_data, headers=headers, proxies=proxies, timeout=5, verify=False)
            resp2 = s.get(payload_url, headers=headers, proxies=proxies, timeout=5, verify=False)
        elif ProxyIp==None:
            resp = s.post(payload_url, data=post_data,headers=headers, timeout=5, verify=False)
            resp2 = s.get(payload_url, headers=headers, timeout=5, verify=False)
        con = resp.text
        con2 = resp2.text
        if con2.lower().find('navigation.php')!=-1 and con.lower().find('frame_navigation')!=-1:
            Medusa = "{}存在phpstudy_phpmyadmin默认密码漏洞 \r\n漏洞详情:\r\nPayload:{}\r\nPost:{}\r\n".format(url, payload_url,post_data)
            _t = VulnerabilityInfo(Medusa)
            web = ClassCongregation.VulnerabilityDetails(_t.info)
github rembo10 / headphones / lib / pygazelle / api.py View on Github external
def __init__(self, username=None, password=None, url=None):
        self.session = requests.session()
        self.session.headers = self.default_headers
        self.username = username
        self.password = password
        self.authkey = None
        self.passkey = None
        self.userid = None
        self.logged_in_user = None
        self.default_timeout = 30
        self.cached_users = {}
        self.cached_artists = {}
        self.cached_tags = {}
        self.cached_torrent_groups = {}
        self.cached_torrents = {}
        self.cached_requests = {}
        self.cached_categories = {}
        self.site = url + "/"
github iofu728 / spider / proxy / getproxy.py View on Github external
verify_code = verify_num[0] * verify_num[1]
            error = False
        if error:
            echo("0|error", "Error", operation)
        if not os.path.exists("%spassage" % data_dir):
            echo("0|warning", "gather passage not exist!!!")
            return
        with codecs.open("%spassage" % data_dir, "r", encoding="utf-8") as f:
            passage = [index[:-1] for index in f.readlines()]
        data = {
            "Username": passage[0],
            "Password": passage[1],
            "Captcha": str(verify_code),
        }
        time.sleep(2.163)
        r = requests.session()
        r.cookies = cj.LWPCookieJar()
        login_req = r.post(login_url, headers=headers, data=data, verify=False)