K
K
KPEBETKA2014-02-22 22:18:29
Python
KPEBETKA, 2014-02-22 22:18:29

Python::Requests. What is the best way to change cookie values ​​before sending a request?

The code works in principle, but what I don't like is that for such a simple action it takes as many as eight lines of code.
Can I compress it into a couple of lines?

value = 'ABCDEFG'
s = requests.Session()

s.get('https://server.ru')

aaa_cookie_val1 = {"name": 'val1', "value": value, "domain":' .aaa.server.ru',}
aaa_cookie_val2 = {"name": 'val2', "value": value, "domain": '.aaa.server.ru',}
bbb_cookie_val1 = {"name": 'val1', "value": value, "domain": '.bbb.server.ru',}
bbb_cookie_val2 = {"name": 'val2', "value": value, "domain": '.bbb.server.ru',}

s.cookies.set(**aaa_cookie_val1)
s.cookies.set(**aaa_cookie_val2)
s.cookies.set(**bbb_cookie_val1)
s.cookies.set(**bbb_cookie_val2)

s.get('https://server.ru/login?login=%s&password=%s' % (login, password))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
throughtheether, 2014-02-22
@KPEBETKA

Regardless of setting cookie values ​​(can't think of domains/values ​​to test out of the box):

value='ABCDEFG'
vals=['val1','val2']
domains=['.aaa','.bbb']
import itertools
for val,domain in itertools.product(vals,domains):
    cookie_val={"name": val, "value": value, "domain":"%s.server.ru"%domain,}
    print cookie_val

Displays
{'domain': '.aaa.server.ru', 'name': 'val1', 'value': 'ABCDEFG'}
{'domain': '.bbb.server.ru', 'name': 'val1', 'value': 'ABCDEFG'}
{'domain': '.aaa.server.ru', 'name': 'val2', 'value': 'ABCDEFG'}
{'domain': '.bbb.server.ru', 'name': 'val2', 'value': 'ABCDEFG'}

You just have to replace print in the loop body with s.cookies.set(**cookie_val)and call outside the loop
s.get('https://server.ru/login?login=%s&password=%s' % (login, password))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question