3

My code looks something like this:

import requests
s = requests.Session()
r = s.get(a, verify=False)
r = s.get(b, verify=False)
r = s.get(c, verify=False)
r = s.get(d, verify=False)
r = s.get(e, verify=False)
r = s.get(f, verify=False)
r = s.get(g, headers={"a":"b"}, verify=False)
r = s.post(h, data={"a","b"},verify=False)

How can I avoid having to explicitly write verify=False all the time?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • somewhat related: http://stackoverflow.com/questions/16626789/functools-partial-on-class-method – timgeb May 18 '17 at 14:37

2 Answers2

7

In the case of python requests, you can make the SSL verify flag last the lifetime of that session by doing

s.verify = False

More generally when a function accepts named=value type parameters the first thing to do is to inspect the method signature to see if the default value is perhaps what you want it to be. If it isn't the next thing is to see if the value be persisted as above (which python requests allows to do).

The third option is to create a simple wrapper which passes suitable values for all parameters

def my_get(s, url):
    s.get(url, verify=False)

called as

my_get(s, url)

Or you can get really ambitious and monkey patch the class from the library. But monkey patching can sometimes lead to unexpected side effects so it's best avoided unless as a very last resort.

References:
the documentation for the verify attribute of the Session class.
Using Optional and named arguments.

Community
  • 1
  • 1
e4c5
  • 52,766
  • 11
  • 101
  • 134
  • Your answer text is duplicated. –  May 18 '17 at 14:48
  • oh thanks. there was an edit while I was editing and lead to a conflict I think. – e4c5 May 18 '17 at 14:49
  • I guess the conflict was caused when I added the link to the documentation. –  May 18 '17 at 14:50
  • Do you really want the documentation link so far away from the the part of the answer to which it applies? –  May 18 '17 at 14:51
4

easily can be done using partial

get_unverified = partial(s.get, verify=False)
post_unverified = partial(s.post, verify=False)
r = get_unverified(a)
r = get_unverified(b)
r = get_unverified(c)
r = get_unverified(d)
r = get_unverified(e)
r = get_unverified(f)
r = get_unverified(g, headers={"a":"b"})
r = post_unverified(h, data={"a","b"})
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • Note that this is not optimal if you want all instances of `Session` to act like that. Check out http://stackoverflow.com/questions/16626789/functools-partial-on-class-method – timgeb May 20 '17 at 03:31