Skip to content

Commit

Permalink
fix: add csrf token in JSON request (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
SharzyL authored Sep 10, 2021
1 parent 83d52d7 commit 8d3905d
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
err404 = '\r\n\r\n\r\n<script type="text/javascript">\r\n\tlocation.href="/";\r\n</script>'


def get_xsrf_token():
cookie_obj = cookie._cookies.get('learn.tsinghua.edu.cn', dict()).get('/', dict()).get('XSRF-TOKEN', None)
return cookie_obj.value if cookie_obj else None

def open_page(uri, values={}):
post_data = urllib.parse.urlencode(values).encode() if values else None
request = urllib.request.Request(uri if uri.startswith('http') else url + uri, post_data, headers)
Expand All @@ -38,6 +42,12 @@ def get_page(uri, values={}):


def get_json(uri, values={}):
xsrf_token = get_xsrf_token()
if xsrf_token:
if '?' not in uri:
uri = uri + f'?_csrf={xsrf_token}'
else:
uri = uri + f'&_csrf={xsrf_token}'
try:
page = get_page(uri, values)
result = json.loads(page)
Expand Down

0 comments on commit 8d3905d

Please sign in to comment.