-
Notifications
You must be signed in to change notification settings - Fork 2
/
requests_template.py
76 lines (50 loc) · 2.27 KB
/
requests_template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
### Pedro Adao, 2017
# This file has most of the examples one needs to use requests.
import requests
SERVER=''
#### GET REQUESTS
params = {'field1' : 'value1', 'field2' : 'value2'}
headers = {'user-agent': 'my-app/0.0.1', 'Content-Type': 'application/json'}
r = requests.get(SERVER, params=params, headers=headers)
#### POST REQUESTS
data = {'field1' : 'value1', 'field2' : 'value2'}
headers = {'user-agent': 'my-app/0.0.1', 'Content-Type': 'application/json'}
r = requests.post(SERVER, data=data, headers=headers)
#### PUT REQUESTS
params = {'field1' : 'value1', 'field2' : 'value2'}
data = {'field1' : 'value1', 'field2' : 'value2'}
headers = {'user-agent': 'my-app/0.0.1', 'Content-Type': 'application/json'}
r = requests.put(SERVER, params=payload, data=data, headers=headers)
#### ANSWERS
print 'status : ', r.status_code
print 'headers : ', r.headers
print 'cookies : ', r.cookies
print 'html : ', r.text
##### AUTHENTICATION
params = {'field1' : 'value1', 'field2' : 'value2'}
headers = {'user-agent': 'my-app/0.0.1', 'Content-Type': 'application/json'}
user ='XXX'
passwd = 'YYY'
r = requests.get(SERVER, params=params, headers=headers, auth=(user, passwd)) ### Same for other methods
##### COOKIES
#### Extract Cookie values
cookie_value = r.cookies['field']
#### Update and send new cookie values
data = {'field1' : 'value1', 'field2' : 'value2'}
cookies = {'field1' : 'value1', 'field2' : 'value2'}
r = requests.get(SERVER, data=data, cookies=cookies) ### Same for other methods
##### WITH SESSIONS
# start session
session = requests.session()
params = {'field1' : 'value1', 'field2' : 'value2'}
r = session.get(SERVER, params=params) ### Same for other methods
all_cookies = requests.utils.dict_from_cookiejar(session.cookies)
# update and resend cookies
session.cookies.set('field', 'new_value', domain='domain_of_cookie', path='path_of_cookie')
r = session.get(SERVER, params=params) ### Same for other methods
##### WITH SOCKS PROXY WE SET UP VIA
# ssh -D 4444 -i <private key file path> -p <port> <user>@<ipaddress>
proxies = {'http': "socks5://localhost:4444"}
params = {'field1' : 'value1', 'field2' : 'value2'}
headers = {'user-agent': 'my-app/0.0.1', 'Content-Type': 'application/json'}
r = requests.get(SERVER, params=params, headers=headers, proxies=proxies)