This repository was archived by the owner on Nov 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
3. Filters
Fatih Kılıç edited this page May 5, 2019
·
10 revisions
Filters helps you to modify headers, JSON, data, auth and literally anything passed to request.
-
_filter_request: Runs before request -
_filter_response: Runs after request
An empty dictionary is passing to functions.
Also in _filter_response, response argument passing additionally.
Setting one time password as header
from anyapi import AnyAPI
import pyotp
totp = pyotp.TOTP('base32secret3232')
def set_one_time_password_as_header(keyword_arguments):
# Since dictionaries are mutable you don't have to return any value
keyword_arguments['headers']['otp'] = totp.now()
api = AnyAPI('https://httpbin.org')
api._filter_request.append(set_one_time_password_as_header)
print(api.anything.endpoint.GET().json())
# output
{
'args': {},
'data': '',
'files': {},
'form': {},
'headers': {
'Accept-Encoding': 'identity',
'Connection': 'close',
'Host': 'httpbin.org',
'Otp': '492039' # <----------
},
'json': None,
'method': 'GET',
'origin': 'XX.XX.XX.XX',
'url': 'https://httpbin.org/anything/endpoint'
}Converting response to JSON after every request
from anyapi import AnyAPI
def convert_response_to_json(keyword_arguments, response):
return response.json()
api = AnyAPI('https://httpbin.org')
api._filter_response.append(convert_response_to_json)
# api._filter_response.append(lambda _, response: response.json())
print(api.anything.endpoint.GET()) # Notice that we didn't call json() here
# output
{
'args': {},
'data': '',
'files': {},
'form': {},
'headers': {
'Accept-Encoding': 'identity',
'Connection': 'close',
'Host': 'httpbin.org',
},
'json': None,
'method': 'GET',
'origin': 'XX.XX.XX.XX',
'url': 'https://httpbin.org/anything/endpoint'
}