Package: platformshconfig
Platform.sh Config Reader (Python)This library provides a streamlined and easy to use way to interact with a Platform.sh environment. It offers utility methods to access routes and relationships more cleanly than reading the raw environment variables yourself.This library requires Python 3.5 or later.InstallpipinstallplatformshconfigUsage ExampleExample:importsysimportpysolrfromplatformshconfigimportConfigconfig=Config()ifnotconfig.is_valid_platform():sys.exit("Not in a Platform.sh Environment.")credentials=config.credentials('solr')formatted=config.formatted_credentials('solr','pysolr')conn=pysolr.Solr(formatted)# Do stuff with the conn here.API ReferenceCreate a config objectfromplatformshconfigimportConfigconfig=Config()configis now aConfigobject that provides access to the Platform.sh environment.Theis_valid_platform()method returnsTrueif the code is running in a context that has Platform.sh environment variables defined.  If it returnsFalsethen most other functions will throw exceptions if used.Inspect the environmentThe following methods returnTrueorFalseto help determine in what context the code is running:config.in_build()config.in_runtime()config.on_dedicated()config.on_production()Note:Platform.sh will no longer refer to its99.99% uptime SLA productas "Enterprise", but rather as "Dedicated". Configuration Reader libraries have in turn been updated to include anon_dedicatedmethod to replaceon_enterprise. For nowon_enterpriseremains available. It now calls the new method and no breaking changes have been introduced.It is recommended that you update your projects to useon_dedicatedas soon as possible, ason_enterprisewill be removed in a future version of this library.Read environment variablesThe following magic properties return the corresponding environment variable value.  See thePlatform.sh documentationfor a description of each.The following are available both in Build and at Runtime:config.applicationNameconfig.appDirconfig.projectconfig.treeIDconfig.projectEntropyThe following are available only ifin_runtime()returnedTrue:config.branchcondig.documentRootconfig.smtpHostconfig.environmentconfig.socketconfig.portReading service credentialsPlatform.sh servicesare defined in aservices.yamlfile, and exposed to an application by listing arelationshipto that service in the application's.platform.app.yamlfile.  User, password, host, etc. information is then exposed to the running application in thePLATFORM_RELATIONSHIPSenvironment variable, which is a base64-encoded JSON string.  The following method allows easier access to credential information than decoding the environment variable yourself.creds=config.credentials('database')The return value ofcredentials()is a dictionary matching the relationship JSON object, which includes the appropriate user, password, host, database name, and other pertinent information.  See theService documentationfor your service for the exact structure and meaning of each property.  In most cases that information can be passed directly to whatever other client library is being used to connect to the service.Formatting service credentialsIn some cases the library being used to connect to a service wants its credentials formatted in a specific way; it could be a DSN string of some sort or it needs certain values concatenated to the database name, etc.  For those cases you can use "Credential Formatters".  A Credential Formatter is anycallable(function, anonymous function, object method, etc.) that takes a credentials array and returns any type, since the library may want different types.Credential Formatters can be registered on the configuration object, and a few are included out of the box.  That allows 3rd party libraries to ship their own formatters that can be easily integrated into theConfigobject to allow easier use.defformat_my_service(credentials):return"some string based on 'credentials'."# Call this in setupconfig.register_formatter('my_service',format_my_service)# Then call this method to get the formatted versionformatted=config.formatted_credentials('database','my_service')The first parameter is the name of a relationship defined in.platform.app.yaml.  The second is a formatter that was previously registered withregister_formatter().  If either the service or formatter is missing an exception will be thrown.  The type offormattedwill depend on the formatter function and can be safely passed directly to the client library.Three formatters are included out of the box:pymongoreturns a DSN appropriate for usingpymongoto connect to MongoDB. Note thatpymongowill still need the username and password from the credentials dictionary passed as separate parameters.pysolrreturns a DSN appropriate for usingpysolrto connect to Apache Solr.postgresql_dsnreturns a DSN appropriate for postgresql connection.Reading Platform.sh variablesPlatform.sh allows you to define arbitrary variables that may be available at build time, runtime, or both.  They are stored in thePLATFORM_VARIABLESenvironment variable, which is a base64-encoded JSON string.The following two methods allow access to those values from your code without having to bother decoding the values yourself:config.variables()This method returns a dictionary of all variables defined.  Usually this method is not necessary andconfig.variable()is preferred.config.variable("foo","default")This method looks for the "foo" variable.  If found, it is returned.  If not, the optional second parameter is returned as a default.Reading RoutesRouteson Platform.sh define how a project will handle incoming requests; that primarily means what application container will serve the request, but it also includes cache configuration, TLS settings, etc.  Routes may also have an optional ID, which is the preferred way to access them.config.get_route("main")Theget_route()method takes a single string for the route ID ("main" in this case) and returns the corresponding route array.  If the route is not found it will throw an exception.To access all routes, or to search for a route that has no ID, theroutes()method returns an dictionary of routes keyed by their URL.  That mirrors the structure of thePLATFORM_ROUTESenvironment variable.If called in the build phase an exception is thrown.Changelog[2.4.0] - 2021-02-03AddedGitHub actions for tests (quality-assurance.yaml) and publishing to pypi (pypi-publish.yaml).Changednamed variableprefixon constructor renamed tovar_prefix.RemovedCircleCI action config.[2.3.1] - 2019-11-04AddedCHANGELOGadded.on_dedicatedmethod that determines if the current environment is a Platform.sh Dedicated environment. Replaces deprecatedon_enterprisemethod.ChangedDeprecateson_enterprisemethod - which is for now made to wrap around the addedon_dedicatedmethod.on_enterprisewill be removedin a future release, so update your projects to useon_dedicatedinstead as soon as possible.[2.3.0] - 2019-09-19Addedget_primary_routemethod for accessing routes marked "primary" inroutes.yaml.get_upstream_routesmethod returns an object map that includes only those routes that point to a valid upstream.[2.2.3] - 2019-04-30ChangedRemoves guard onvariables()method.[2.2.2] - 2019-04-29ChangedRefactors dynamic property access to be more permissive.[2.2.1] - 2019-04-25ChangedMore permissive check for relationships.[2.2.0] - 2019-04-24Addedpostgresql_dsncredential formatter; returns a DSN appropriate for PostgreSQL connection.[2.1.1] - 2019-03-22ChangedFixes build issues inhas_relationship()androutes()methods.[2.1.0] - 2019-03-22Addedhas_relationshipmethod to determine if a relationship is defined, and thus has credentials available.ChangedFixesroutesmethod.[2.0.4] - 2019-03-06AddedCircleCI configuration