2021-12-06 12:43:34 -08:00
import ssl
from typing import Dict , Union
import attr
@attr.s ( auto_attribs = True )
class Client :
""" A class for keeping track of data related to the API """
2021-12-14 18:39:22 -08:00
base_url : str = attr . ib ( default = " https://api.kittycad.io " )
2021-12-06 12:43:34 -08:00
cookies : Dict [ str , str ] = attr . ib ( factory = dict , kw_only = True )
headers : Dict [ str , str ] = attr . ib ( factory = dict , kw_only = True )
timeout : float = attr . ib ( 5.0 , kw_only = True )
verify_ssl : Union [ str , bool , ssl . SSLContext ] = attr . ib ( True , kw_only = True )
def get_headers ( self ) - > Dict [ str , str ] :
""" Get headers to be used in all endpoints """
return { * * self . headers }
def with_headers ( self , headers : Dict [ str , str ] ) - > " Client " :
""" Get a new client matching this one with additional headers """
return attr . evolve ( self , headers = { * * self . headers , * * headers } )
def get_cookies ( self ) - > Dict [ str , str ] :
return { * * self . cookies }
def with_cookies ( self , cookies : Dict [ str , str ] ) - > " Client " :
""" Get a new client matching this one with additional cookies """
return attr . evolve ( self , cookies = { * * self . cookies , * * cookies } )
def get_timeout ( self ) - > float :
return self . timeout
def with_timeout ( self , timeout : float ) - > " Client " :
""" Get a new client matching this one with a new timeout (in seconds) """
return attr . evolve ( self , timeout = timeout )
@attr.s ( auto_attribs = True )
class AuthenticatedClient ( Client ) :
""" A Client which has been authenticated for use on secured endpoints """
2021-12-15 01:51:26 -08:00
token : str = attr . ib ( kw_only = True )
2021-12-06 12:43:34 -08:00
def get_headers ( self ) - > Dict [ str , str ] :
""" Get headers to be used in authenticated endpoints """
return { " Authorization " : f " Bearer { self . token } " , * * self . headers }
2021-12-15 06:32:32 -08:00
@attr.s ( auto_attribs = True )
class AuthenticatedClientFromEnv ( Client ) :
""" A Client which has been authenticated for use on secured endpoints that uses the KITTYCAD_API_TOKEN environment variable for the authentication token. """
token : str = attr . ib ( default = os . getenv ( ' KITTYCAD_API_TOKEN ' ) )
def get_headers ( self ) - > Dict [ str , str ] :
""" Get headers to be used in authenticated endpoints """
return { " Authorization " : f " Bearer { self . token } " , * * self . headers }