-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathexample-fetch.py
62 lines (49 loc) · 1.94 KB
/
example-fetch.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
#!/usr/bin/env python3
import getopt
import http.cookiejar
import sys
import urllib.parse
import urllib.request
from http.cookies import SimpleCookie
from json import loads as json_loads
from os import environ
from dotenv import load_dotenv, dotenv_values
load_dotenv()
env = dotenv_values()
_headers = {"Referer": f"{env['BASE_PROTOCOL']}{env['BASE_URL']}"}
class UrllibClient:
"""Simple HTTP Session Client, keeps cookies."""
def __init__(self):
self.cookie_jar = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie_jar))
urllib.request.install_opener(self.opener)
def get(self, url, headers={}):
request = urllib.request.Request(url, headers=headers)
return self._request(request)
def post(self, url, data=None, headers={}):
postdata = urllib.parse.urlencode(data).encode()
request = urllib.request.Request(url, postdata, headers)
return self._request(request)
def _request(self, request):
response = self.opener.open(request)
response.status_code = response.getcode()
response.data = response.read().decode('utf-8')
return response
client, cookie = UrllibClient(), SimpleCookie()
cookie.load(vars(client.get(f"{env['BASE_PROTOCOL']}{env['BASE_URL']}"))['headers']['Set-Cookie'])
csrftoken = cookie['csrftoken'].value
## First, create
payload = {
'csrfmiddlewaretoken': csrftoken,
'text': 'test',
'metadata' : 'OPTION_DISABLE_VIEWS = true',
}
result_create = json_loads(client.post(f"{env['BASE_PROTOCOL']}{env['BASE_URL']}" + '/api/new', payload, headers=_headers).data)
print(result_create)
## Then, fetch
payload = {
'csrfmiddlewaretoken': csrftoken,
'edit_code' : result_create['edit_code'],
}
result_fetch = client.post(f"{env['BASE_PROTOCOL']}{env['BASE_URL']}" + f"/api/fetch/{result_create['url_short']}", payload, headers=_headers).data
print(result_fetch)