Package: auraxium
AuraxiumAuraxium is an object-oriented, pure-Python wrapper for thePlanetSide 2API.It provides a simple object model that can be used by players and outfits without requiring deep knowledge of the API and its idiosyncrasies.Clean, Pythonic APIAsynchronous endpoints to keep apps responsive during high API loadLow-level interface for more optimised, custom queriesSupport for the real-time event streaming service (ESS)User-configurable caching systemFully type annotatedThe documentation for this project is hosted atRead the Docs.Table of ContentsOverviewGetting StartedBoilerplate CodeUsageRetrieving DataEvent StreamingTechnical DetailsObject HierarchyCachingNetwork ConnectionsObject Model AlternativesContributingOverviewTheCensus APIused by PlanetSide 2 is powerful, but its design also carries a steep learning curve that makes a lot of basic API interactions rather tedious.Auraxium streamlines this by hiding the game-agnostic queries behind an object model specific to PlanetSide 2. Whenever data is accessed that is not currently loaded, the library dynamically generates and performs the necessary queries in the background before resuming execution.All queries that may incur network traffic and latency are asynchronous, which keeps multi-user applications - such as Discord bots - responsive.Getting StartedAll API interactions are performed through theauraxium.Clientobject. It is the main endpoint used to interact with the API and contains a few essential references, like the current event loop, the connection pool, or the unique service ID used to identify your app.Regarding service IDs:You can use the default value ofs:examplefor testing, but you may run into rate limiting issues if your app generates more than ~10 queries a minute.You can apply for your custom service IDhere; the process is free, and you usually hear back within a few hours.Some of these references are also required for any queries carried out behind the scenes, so the client object is also handed around behind the scenes; be mindful when updating them as this may cause issues with ongoing background queries.Boilerplate codeThe aforementionedauraxium.Clientobject must be closed using theauraxium.Client.close()method before it is destroyed to avoid issues.Alternatively, you can use the asynchronous context manager interface to automatically close it when leaving the block:importauraxiumasyncwithauraxium.Client()asclient:# Your code hereSince Auraxium is an asynchronous library, we also need to wrap our code in a coroutine to be able to use theasynckeyword.This gives us the following snippet:importasyncioimportauraxiumasyncdefmain():asyncwithauraxium.Client()asclient:# Your code hereasyncio.run(main())With that, the stage is set for some actual code.UsageThe game-specific object representations for PlanetSide 2 can be found in theauraxium.ps2sub module. Common ones includeps2.Character,ps2.Outfit, orps2.Item.Note:The original data used to build a given object representation is always available via that object's.dataattribute, which will be a type-hinted,named tuple.Retrieving DataTheauraxium.Clientclass exposes several methods used to access the REST API data, likeClient.get(), used to return a single match, orClient.find(), used to return a list of matching entries.It also provides some utility methods, likeClient.get_by_id()andClient.get_by_name(). They behave much like the more generalClient.get()but are cached to provide better performance for common lookups.This means that repeatedly accessing an object through.get_by_id()will only generate network traffic once, after which it is retrieved from cache (refer to theCachingsection for more information).Here is the above boilerplate code again, this time with a simple script that prints various character properties:importasyncioimportauraxiumfromauraxiumimportps2asyncdefmain():asyncwithauraxium.Client()asclient:char=awaitclient.get_by_name(ps2.Character,'auroram')print(char.name)print(char.data.prestige_level)# NOTE: Any methods that might incur network traffic are asynchronous.# If the data type has been cached locally, no network communication# is required.# This will only generate a request once per faction, as the faction# data type is cached forever by default.print(awaitchar.faction())# The online status is never cached as it is bound to change at any# moment.print(awaitchar.is_online())asyncio.run(main())Event StreamingIn addition to the REST interface wrapped by Auraxium's object model, PlanetSide 2 also exposes an event stream that can be used to react to in-game events in next to real time.This can be used to track outfit member performance, implement your own stat tracker, or monitor server population.The Auraxium client supports this endpoint through a trigger-action system.TriggersTo receive data through the event stream, you must define a trigger. A trigger is made up of three things:One or moreeventsthat tells it to wake upAny number ofconditionsthat decide whether to run or notAnactionthat will be run if the conditions are metEventsThe event type definitions are available in theauraxium.eventnamespace.ConditionsTrigger conditions can be attached to a trigger to limit what events it will respond to, in addition to the event type.This is useful if you have a commonly encountered event (likeevent.DEATH) and would like your action to only run if the event data matches some other requirement (for example "the killing player must be part of my outfit").ActionsThe trigger's action is a method or function that will be run when the event fires and all conditions evaluate to True.If the action is a coroutine according toinspect.iscoroutinefunction(), it will be awaited.The only argument passed to the function set as the trigger action is the event received:asyncdefexample_action(event:Event)->None:"""Example function to showcase the signature used for actions.Keep in mind that this could also be a regular function (i.e. onedefined without the "async" keyword)."""# Do stuff hereRegistering TriggersThe easiest way to register a trigger to the client is via theauraxium.event.EventClient.trigger()decorator. It takes the event/s to listen for as the arguments and creates a trigger using the decorated function as the trigger action.Important:Keep in mind that the websocket connection will be continuously looping, waiting for new events to come in.This means that usingauraxium.event.EventClient()as a context manager may cause issues since the context manager will close the connection when the context manager is exited.importasynciofromauraxiumimportevent,ps2asyncdefmain():# NOTE: Depending on player activity, this script will likely exceed the# ~6 requests per minute and IP address limit for the default service ID.client=event.EventClient(service_id='s:example')@client.trigger(event.BattleRankUp)asyncdefprint_levelup(evt):char=awaitclient.get_by_id(ps2.Character,evt.character_id)# NOTE: This value is likely different from char.data.battle_rank as# the REST API tends to lag by a few minutes.new_battle_rank=evt.battle_rankprint(f'{awaitchar.name_long()}has reached BR{new_battle_rank}!')loop=asyncio.new_event_loop()loop.create_task(main())loop.run_forever()Technical DetailsThe following section contains more detailed implementation details for those who want to know; it is safe to ignore if you are only getting started.Object HierarchyAll classes in the Auraxium object model inherit fromPs2Object. It defines the API table and ID field to use for generic queries and implements methods like.get()or.find().Cache ObjectsCached objects are based off theCachedclass, which introduces a class-specific cache for matching instances before falling back to the regular implementation.It also adds methods for updating the class cache settings at runtime.See theCachingsection for details on the caching system.Named ObjectsNamed objects are based off theNamedclass and always cached. This base class guarantees a.name] attribute and allows the use of the.get_by_name()method, which is also cached.This caching strategy is almost identical to the one used for IDs, except that it uses a string constructed of the lower-case name and locale identifier to store objects (e.g.'en_sunderer').CachingAuraxium uses timed least-recently-used (TLRU) caches for its objects.They have a size constraint (i.e. how many objects may be cached at any given time), as well as a maximum age per item (referred to as TTU, "time-to-use"). The TTU is used to ensure frequently used items are updated occasionally and not too far out of date.When new items are added to the cache, it first removes any expired items (i.e.time_added - now > ttu).
It then removes as many least-recently-used items as necessary to accommodate the new elements.The LRU side of things is implemented via ancollections.OrderedDict; every time an item is retrieved from the cache (and is not expired), it is moved back to the start of the dictionary, the last items of the dictionary are then chopped off as needed.Network ConnectionsFor as long as it is active, theauraxium.Clientobject will always have aaiohttp.ClientSessionrunning in case the REST API must be accessed.The websocket connection, which is required for event streaming, is only active when there are triggers registered and active.If the last trigger is removed, the websocket connection is quietly closed after a delay. If a new trigger is added, it will automatically be recreated in the background.Object Model AlternativesFor some users or applications, Auraxium's object model may be a bad fit, like for highly nested, complex queries or for users that are already familiar with the Census API.Here are a few Python alternatives for these cases:The URL generator used by Auraxium to generate the queries for the object model can also be used on its own.This still requiressomeunderstanding of the Census API data model but takes away the syntactic pitfalls involved.It only generates queries, so you will have to pick your own flavour of HTTP library (likerequestsoraiohttp) to make the queries."""Usage example for the auraxium.census module."""fromauraxiumimportcensusquery=census.Query('character',service_id='s:example')query.add_term('name.first_lower','auroram')query.limit(20)join=query.create_join('characters_online_status')url=str(query.url())print(url)# https://census.daybreakgames.com/s:example/get/ps2:v2/character?c:limit=20&c:join=characters_online_statusRefer to thecensus module documentationfor details.For an even simpler syntax, you can check outspascou/ps2-census, which was inspired by an earlier version of Auraxium.It too sticks closely to the original Census API, but also provides methods for retrieving the queried data.It also features a query factory system that allows creation of common queries from templates."""Usage example for spascou's ps2-census module."""importps2_censusasps2query=ps2.Query(ps2.Collection.CHARACTER,service_id='s:example')query.filter('name.first_lower','auroram')query.limit(20)query.join(ps2.Join(ps2.Collection.CHARACTERS_ONLINE_STATUS))print(query.get())# {'character_list': [...], 'returned': 1}Refer to theps2-census documentationfor details.ContributingIf you have found a bug or would like to suggest a new feature or change, feel free to get in touch via therepository issues.Please check outCONTRIBUTING.mdbefore opening any pull requests for details.