def test_app_expired_header_etag(self, urlopen_mock): @httmock.all_requests def check_etag(url, request): self.assertEqual( request.headers.get('If-None-Match'), '"esipyetag"') return httmock.response( headers={ 'Expires': make_expire_time_str(), 'Etag': '"esipyetag"' }, status_code=304) cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) self.assertEqual(len(cache._dict), 0) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(len(cache._dict), 1) cache.get( app.esi_meta_cache_key )[1]['expires'] = make_expired_time_str() cached_app = cache.get(app.esi_meta_cache_key)[0] with httmock.HTTMock(check_etag): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) esiapp = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(cached_app, esiapp.app) urlopen_mock.return_value.close()
def test_app_http_error_retry_fail(self, urlopen_mock): urlopen_mock.side_effect = HTTPError("http://mock.test", 500, "HTTP 500 whatever", None, None) with httmock.HTTMock(*_swagger_spec_mock_): with self.assertRaises(APIException): self.app = EsiApp(cache_prefix='esipy_test') self.assertEqual(urlopen_mock.call_count, 3)
def test_app_valid_header_etag(self, urlopen_mock): @httmock.all_requests def fail_if_request(url, request): self.fail('Cached data is not supposed to do requests') cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') with httmock.HTTMock(fail_if_request): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value.close()
def do_security(): global client global app print("security: Authenticating") #Retrieve the tokens from the film with open("tokens.txt", "rb") as fp: tokens_file = pickle.load(fp) fp.close() esi_app = EsiApp(cache=cache, cache_time=0, headers=headers) app = esi_app.get_latest_swagger security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) client = EsiClient(retry_requests=True, headers=headers, security=security) security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': tokens_file['refresh_token'] }) tokens = security.refresh() api_info = security.verify() print("security: Authenticated for " + str(api_info['Scopes']))
def download_from_esi(killmails): cache = FileCache(path=os.path.join(ROOT_DIR, 'cache/esipy_swagger')) esi_app = EsiApp(cache=cache, cache_time=60 * 60 * 24) app = esi_app.get_latest_swagger client = EsiClient( retry_requests=True, # set to retry on http 5xx error (default False) headers={'User-Agent': 'Something CCP can use to contact you and that define your app'}, raw_body_only=True, # default False, set to True to never parse response and only return raw JSON string content. ) operations = [] for killmail in killmails: operations.append( app.op['get_killmails_killmail_id_killmail_hash']( killmail_hash=killmail['zkb']['hash'], killmail_id=killmail['killmail_id'] ) ) results = client.multi_request(operations) full_killmails = [] for result in results: full_killmails.append(json.loads(result[1].raw)) return full_killmails
def __init__(self, token_file): #Retrieve the tokens from the file with open(token_file, "rb") as fp: tokens_file = pickle.load(fp) fp.close() esi_app = EsiApp(cache=cache, cache_time=0, headers=headers) self.app = esi_app.get_latest_swagger self.security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) self.client = EsiClient(retry_requests=True, headers=headers, security=self.security) self.security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': tokens_file['refresh_token'] }) tokens = self.security.refresh() api_info = self.security.verify() self.character_id = api_info['CharacterID'] self.name = api_info['CharacterName'] #print (str(api_info)) print("security: " + self.name + " authenticated for " + str(api_info['Scopes']))
def _start(self): self.cache = FileCache(path=self.cache_path) self.esi_app = EsiApp(cache=self.cache, cache_prefix=self.prefix) self.app = self.esi_app.get_latest_swagger self.security = EsiSecurity( app=self.app, redirect_uri='http://localhost/oauth-callback', # This doesnt matter headers={ 'User-Agent': 'Discord bot by Prozn: https://github.com/prozn/dankcord' }, client_id=self.client_id, secret_key=self.secret_key, ) self.esi = EsiClient( retry_requests= False, # set to retry on http 5xx error (default False) headers={ 'User-Agent': 'Discord bot by Prozn: https://github.com/prozn/dankcord' }, security=self.security) self.security.update_token({ 'access_token': '', # leave this empty 'expires_in': -1, # seconds until expiry, so we force refresh anyway 'refresh_token': self.refresh_token }) self.security.refresh()
def test_app_invalid_cache_value(self, urlopen_mock): cache = DictCache() cache.set(self.app.esi_meta_cache_key, 'somerandomvalue') urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): EsiApp(cache_prefix='esipy_test', cache=cache) self.assertNotEqual(cache.get(self.app.esi_meta_cache_key), 'somerandomvalue')
def test_app_op_attribute(self, urlopen_mock): self.assertTrue(self.app.op) self.assertEqual(self.app.op['verify'].url, '//esi.evetech.net/verify/') urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): app = EsiApp(cache_prefix='esipy_test', cache_time=-1) self.assertEqual(app.expire, 86400)
def initEsiApp(cls): if cls._initializing is None: cls._initializing = True cls.esiapp = EsiApp(cache=file_cache, cache_time=None, cache_prefix='pyfa{0}-esipy-'.format( config.version)) cls.esi_v1 = cls.esiapp.get_v1_swagger cls.esi_v4 = cls.esiapp.get_v4_swagger cls._initializing = False
def get_esi_app(): """ EsiApp is used to get operations for Eve Swagger Interface """ if 'esi_app' in cache: return cache.get('esi_app') else: esi_app = EsiApp(cache_time=86400).get_latest_swagger cache.set('esi_app', esi_app, timeout=86400) return esi_app
def __init__(self, config, *args, **kwargs): self.config = config intents = discord.Intents.default() intents.members = True intents.presences = True app = EsiApp() self.esi_app = app.get_latest_swagger self.description = "A discord.py bot to do some stuff." self.token = config['bot']['token'] self.prefix = config['bot']['prefix'] self.started = datetime.datetime.utcnow() self.logger = get_logger(__name__) super().__init__(command_prefix=self.prefix, description=self.description, pm_help=None, activity=discord.Activity( name=config['bot']['status'], type=discord.ActivityType.playing), status=discord.Status.idle, intents=intents, *args, **kwargs) self.loop.create_task(Tortoise.init( config=settings.TORTOISE_ORM)) # Connect to the database. # Load extensions try: self.load_extension(f'cogs.core.cog') except Exception as e: self.logger.fatal("Core cog failed to load. Exception:") self.logger.fatal(e) print( "Core cog could not be loaded. Please check the logs for more information." ) exit(1) for extension in self.config['bot']['extensions']: try: self.load_extension(f'cogs.{extension}.cog') except Exception as e: self.logger.critical(f"{extension} failed to load. Exception:") self.logger.critical(e) print( f"{extension} failed to load. Check logs for more details." ) else: self.logger.info(f'{extension} loaded.') print(f"{extension} loaded successfully.")
def test_app_getattr_no_cache(self, urlopen_mock): urlopen_mock.return_value = open('test/resources/meta_swagger.json') app_nocache = EsiApp(cache=None, cache_prefix=self.ESI_CACHE_PREFIX) urlopen_mock.return_value = open('test/resources/swagger.json') self.assertIsNone( app_nocache.cache.get(self.app.esi_meta_cache_key, None) ) appv1 = app_nocache.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertIsNone(app_nocache.cache.get(self.ESI_V1_CACHE_KEY, None))
def test_app_expired_header_no_etag(self, urlopen_mock): cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1 = app.get_v1_swagger cache.get(self.ESI_V1_CACHE_KEY)[1]['Expires'] = None urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1_uncached = app.get_v1_swagger self.assertNotEqual(appv1, appv1_uncached)
def test_app_getattr_no_cache(self, urlopen_mock): with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app_nocache = EsiApp(cache=None, cache_prefix=self.ESI_CACHE_PREFIX) urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) self.assertIsNone( app_nocache.cache.get(self.app.esi_meta_cache_key, None)) appv1 = app_nocache.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertIsNone( app_nocache.cache.get(self.ESI_V1_CACHE_KEY, None))
def __init__(self): self.esi_app = EsiApp() self.app = self.esi_app.get_latest_swagger self.client = EsiClient( retry_requests= True, # set to retry on http 5xx error (default False) headers={ 'User-Agent': 'Something CCP can use to contact you and that define your app' }, raw_body_only= False, # default False, set to True to never parse response and only return raw JSON string content. )
def test_app_http_error_retry_ok(self, urlopen_mock): http_error = HTTPError("http://mock.test", 500, "HTTP 500 whatever", None, None) # this will make the function raise exception / return the value # in this given order side_effect_results = [ http_error, http_error, open(TestEsiApp.ESI_META_SWAGGER) ] urlopen_mock.side_effect = side_effect_results with httmock.HTTMock(*_swagger_spec_mock_): EsiApp(cache_prefix='esipy_test') self.assertEqual(urlopen_mock.call_count, 3)
def do_security(tokens_file, scopes): esi_app = EsiApp(cache=cache, cache_time=0) app = esi_app.get_latest_swagger security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers=headers) client = EsiClient(retry_requests=True, headers=headers, security=security) print("Open link in browser and authorize") print(security.get_auth_uri(scopes=scopes)) code = input("Enter in code:\n") tokens = security.auth(code) print(tokens) print("\n Writing tokens to " + str(tokens_file)) with open(tokens_file, 'wb') as fp: pickle.dump(tokens, fp) fp.close()
def _load_esi(): loaded = False count = 0 while not loaded: if count < MAX_RETRY: count += 1 try: esi_app = EsiApp().get_latest_swagger esi_client = EsiClient(retry_requests=True, headers={'User-Agent': USER_AGENT}, raw_body_only=True) loaded = True return esi_app, esi_client except HTTPError: logger.warning('Loading swagger failed ' + str(count) + '/' + str(MAX_RETRY) + ', retrying...') time.sleep(0.5) pass else: raise ConnectionError( 'Error loading swagger. Please restart the bot.')
def setup_esi(app_id, app_secret, refresh_token, cache=DictCache()): """Set up the ESI client Args: app_id (string): SSO Application ID from CCP app_secret (string): SSO Application Secret from CCP refresh_token (string): SSO refresh token cache (False, optional): esipy.cache instance Returns: tuple: esi app definition, esi client >>> setup_esi(CONFIG['SSO_APP_ID'], CONFIG['SSO_APP_KEY'], ... CONFIG['SSO_REFRESH_TOKEN'], cache) # doctest: +ELLIPSIS (<pyswagger.core.App object ...>, <esipy.client.EsiClient object ...>) """ esi_meta = EsiApp(cache=cache) esi = esi_meta.get_latest_swagger esi_security = EsiSecurity( redirect_uri='http://localhost', client_id=app_id, secret_key=app_secret, headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'}) esi_security.update_token({ 'access_token': '', 'expires_in': -1, 'refresh_token': refresh_token }) esi_client = EsiClient( retry_requests=True, headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'}, raw_body_only=False, security=esi_security, cache=cache) return (esi, esi_client, esi_security)
import datetime import pytz import asyncio from aiohttp import ClientSession import time utc = pytz.timezone('UTC') # Define PostgresSQL client connection = database.create_connection("killmails", "postgres", cfg.db_password, "127.0.0.1", "5432") connection.autocommit = True cursor = connection.cursor() # Define ESI client esi_app = EsiApp() app = esi_app.get_latest_swagger client = EsiClient( retry_requests=True, # set to retry on http 5xx error (default False) headers={'User-Agent': cfg.agent}, raw_body_only= False, # default False, set to True to never parse response and only return raw JSON string content. ) # Start by getting the json file for the kills on the given dates headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36' } print("Downloading json files of killmails")
cached = cache.get(_hash(key)) return cached if cached is not None else default def invalidate(self, key): cache.delete(_hash(key)) lbcache = LbCache() transport_adapter = HTTPAdapter( pool_connections=20, pool_maxsize=300, ) # ESI objects to be imported esiapp = EsiApp(cache=lbcache, cache_time=0, datasource=config.ESI_DATASOURCE) esisecurity = EsiSecurity( app=esiapp.get_latest_swagger, redirect_uri="%s%s" % ( config.ESI_REDIRECT_DOMAIN, '/sso/callback', ), client_id=config.ESI_CLIENT_ID, secret_key=config.ESI_SECRET_KEY, ) esiclient = EsiClient(security=esisecurity, transport_adapter=transport_adapter, cache=lbcache, headers={'User-Agent': config.ESI_USER_AGENT}) # register observers
def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): self.app = EsiApp(cache_prefix='esipy_test')
class TestEsiApp(unittest.TestCase): ESI_CACHE_PREFIX = 'esipy_test' ESI_V1_CACHE_KEY = '%s:app://esi.evetech.net/v1/swagger.json' % ( ESI_CACHE_PREFIX ) ESI_META_SWAGGER = 'test/resources/meta_swagger.json' ESI_V1_SWAGGER = 'test/resources/swagger.json' @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): self.app = EsiApp(cache_prefix='esipy_test') @mock.patch('six.moves.urllib.request.urlopen') def test_app_op_attribute(self, urlopen_mock): self.assertTrue(self.app.op) self.assertEqual( self.app.op['verify'].url, '//esi.evetech.net/verify/' ) urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): app = EsiApp(cache_prefix='esipy_test', cache_time=-1) self.assertEqual(app.expire, 86400) def test_app_getattr_fail(self): with self.assertRaises(AttributeError): self.app.doesnotexist with self.assertRaises(AttributeError): self.app.verify @mock.patch('six.moves.urllib.request.urlopen') def test_app_invalid_cache_value(self, urlopen_mock): cache = DictCache() cache.set(self.app.esi_meta_cache_key, 'somerandomvalue') urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): EsiApp(cache_prefix='esipy_test', cache=cache) self.assertNotEqual( cache.get(self.app.esi_meta_cache_key), 'somerandomvalue' ) @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_and_cache(self, urlopen_mock): with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertEqual(len(self.app.cache._dict), 1) appv1 = self.app.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertEqual( self.app.cache.get(self.ESI_V1_CACHE_KEY)[0], appv1 ) appv1_bis = self.app.get_v1_swagger self.assertEqual(appv1, appv1_bis) self.app.clear_cached_endpoints() self.assertIsNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertIsNone(self.app.cache.get(self.ESI_V1_CACHE_KEY, None)) urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) self.app.op self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_no_cache(self, urlopen_mock): with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app_nocache = EsiApp( cache=None, cache_prefix=self.ESI_CACHE_PREFIX) urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) self.assertIsNone( app_nocache.cache.get(self.app.esi_meta_cache_key, None) ) appv1 = app_nocache.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertIsNone( app_nocache.cache.get(self.ESI_V1_CACHE_KEY, None)) @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_etag(self, urlopen_mock): @httmock.all_requests def check_etag(url, request): self.assertEqual( request.headers.get('If-None-Match'), '"esipyetag"') return httmock.response( headers={ 'Expires': make_expire_time_str(), 'Etag': '"esipyetag"' }, status_code=304) cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) self.assertEqual(len(cache._dict), 0) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(len(cache._dict), 1) cache.get( app.esi_meta_cache_key )[1]['expires'] = make_expired_time_str() cached_app = cache.get(app.esi_meta_cache_key)[0] with httmock.HTTMock(check_etag): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) esiapp = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(cached_app, esiapp.app) urlopen_mock.return_value.close() @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_no_etag(self, urlopen_mock): cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1 = app.get_v1_swagger cache.get(self.ESI_V1_CACHE_KEY)[1]['Expires'] = None urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1_uncached = app.get_v1_swagger self.assertNotEqual(appv1, appv1_uncached) @mock.patch('six.moves.urllib.request.urlopen') def test_app_valid_header_etag(self, urlopen_mock): @httmock.all_requests def fail_if_request(url, request): self.fail('Cached data is not supposed to do requests') cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') with httmock.HTTMock(fail_if_request): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value.close()
from esipy import EsiApp from esipy import EsiSecurity from esipy import EsiClient import KIN3_common import KIN3_Esi auth_key_file = open('./esi_auth_key.txt', 'r') auth_key_lines = auth_key_file.readlines() redirect_uri = auth_key_lines[0].strip() client_id = auth_key_lines[1].strip() secret_key = auth_key_lines[2].strip() app_latest = EsiApp().get_latest_swagger print(f'{KIN3_common.timestamp()} : EsiApp latest loaded') # app_v1 = EsiApp().get_v1_swagger # print(f'{KIN3_common.timestamp()} : EsiApp v1 loaded') app_v2 = EsiApp().get_v2_swagger print(f'{KIN3_common.timestamp()} : EsiApp v2 loaded') security = EsiSecurity(redirect_uri=redirect_uri, client_id=client_id, secret_key=secret_key, headers={'User-Agent': 'something'}) print(f'{KIN3_common.timestamp()} : EsiSecurity loaded') client = EsiClient(security=security, retry_requests=True, headers={'User-Agent': 'something'}, header={'User-Agent': 'something'})
import json import os import sys # ----------------------------------------------------------------------- # Args # ----------------------------------------------------------------------- parser = argparse.ArgumentParser(description='Check for Profitable Insurance Frauds') parser.add_argument('--region', action="store", dest='reg_name', default=10000002, help="Qouted Region Name ie: 'the forge'") parser.add_argument('--list-regions', action="store", dest='list_regions', default=None, help="List all regions") args = parser.parse_args() # ----------------------------------------------------------------------- # ESIPY Init # ----------------------------------------------------------------------- esiapp = EsiApp().get_latest_swagger # ----------------------------------------------------------------------- # ESICLIENT Init # ----------------------------------------------------------------------- esiclient = EsiClient( headers={'User-Agent': config.ESI_USER_AGENT} ) # ----------------------------------------------------------------------- # Pull down market data by region # ----------------------------------------------------------------------- def get_market_data(cache, r_id): try: market = esiapp.op['get_markets_region_id_orders']( region_id = r_id,
class TestEsiApp(unittest.TestCase): ESI_CACHE_PREFIX = 'esipy_test' ESI_V1_CACHE_KEY = '%s:app://esi.evetech.net/v1/swagger.json' % ( ESI_CACHE_PREFIX ) @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open('test/resources/meta_swagger.json') self.app = EsiApp(cache_time=None, cache_prefix='esipy_test') def test_app_op_attribute(self): self.assertTrue(self.app.op) self.assertEqual( self.app.op['verify'].url, '//esi.evetech.net/verify/' ) def test_app_getattr_fail(self): with self.assertRaises(AttributeError): self.app.doesnotexist with self.assertRaises(AttributeError): self.app.verify @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_and_cache(self, urlopen_mock): urlopen_mock.return_value = open('test/resources/swagger.json') self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertEqual(len(self.app.cache._dict), 1) appv1 = self.app.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertEqual(self.app.cache.get(self.ESI_V1_CACHE_KEY), appv1) appv1_bis = self.app.get_v1_swagger self.assertEqual(appv1, appv1_bis) self.app.clear_cached_endpoints() self.assertIsNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertIsNone(self.app.cache.get(self.ESI_V1_CACHE_KEY, None)) urlopen_mock.return_value = open('test/resources/meta_swagger.json') self.app.op self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_no_cache(self, urlopen_mock): urlopen_mock.return_value = open('test/resources/meta_swagger.json') app_nocache = EsiApp(cache=None, cache_prefix=self.ESI_CACHE_PREFIX) urlopen_mock.return_value = open('test/resources/swagger.json') self.assertIsNone( app_nocache.cache.get(self.app.esi_meta_cache_key, None) ) appv1 = app_nocache.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertIsNone(app_nocache.cache.get(self.ESI_V1_CACHE_KEY, None))
def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open('test/resources/meta_swagger.json') self.app = EsiApp(cache_time=None, cache_prefix='esipy_test')
import json import os from esipy import EsiApp, EsiClient from Core import _config from Core.bot import logger from esipy.cache import FileCache meta_app = EsiApp() esiapp = meta_app.get_latest_swagger esiclient = EsiClient( retry_requests=True, cache=FileCache(path=os.path.join(os.path.dirname(__file__), '.webcache')), headers={'User-Agent': _config.ESI_USER_AGENT}, raw_body_only=True) # TODO Log warning headers. Not sure how to access the header. Googled around a bit, but couldn't find anything solid def get_id(name, category): """ Get the id of something :param name: name of something :param category: ESI category the something is part of :return: either a json object containing the something id or None """ if len(name) > 2: response = search(name, category, True)
from esipy import EsiSecurity from esipy.events import AFTER_TOKEN_REFRESH from requests.adapters import HTTPAdapter import config from lazyblacksmith.extension.cache import LBCACHE from .esipy_observers import token_update_observer TRANSPORT_ADAPTER = HTTPAdapter( pool_connections=20, pool_maxsize=300, ) # ESI objects to be imported esiapp = EsiApp(cache=LBCACHE, cache_time=21600, datasource=config.ESI_DATASOURCE) esisecurity = EsiSecurity(app=esiapp.get_latest_swagger, redirect_uri="%s%s" % ( config.ESI_REDIRECT_DOMAIN, '/sso/callback', ), client_id=config.ESI_CLIENT_ID, secret_key=config.ESI_SECRET_KEY, headers={'User-Agent': config.ESI_USER_AGENT}) esiclient = EsiClient(security=esisecurity, transport_adapter=TRANSPORT_ADAPTER, cache=LBCACHE, headers={'User-Agent': config.ESI_USER_AGENT}, retry_requests=True)