Python Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
      • Flask
      • Django
    • Create your agent
    • Troubleshooting
    • Migrating legacy agents
      • Pre-requisites
      • Recommendations
      • Migration steps
      • Code transformations
        • API Charts
        • Live Queries
        • Smart Charts
        • Route overrides
        • Smart Actions
        • Smart Fields
        • Smart Relationships
        • Smart Segments
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • SQLAlchemy
      • Django
        • Polymorphic relationships
    • Write your own
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Widgets in Forms
      • Dynamic Forms
      • Form layout customization
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Integration with Flask settings
  • Mandatory variables
  • Optional variables

Was this helpful?

  1. Getting started

Create your agent

This is the official documentation of the forestadmin-agent-django and forestadmin-agent-flask Python agents.

Integration with Flask settings

Settings can be integrate to flask configuration mechanism. A rename operation is apply removing "FOREST_" and setting the parameter name in lowercase. This is done by the FlaskAgent.parse_config(app) method. For example:

from forestadmin.flask_agent.agent import parse_flask_config

app.config["FOREST_ENV_SECRET"] = "env_secret"
assert parse_flask_config(app) == {"env_secret": "env_secret"}

You can also give a dictionary of settings to the create_agent method as second parameter, so the parse_flask_config will not be called

app = Flask(__name__)

agent = create_agent(app, {
    # Mandatory options (those will be provided during onboarding)
    "env_secret": os.environ.get("ENV_SECRET"),
    "auth_secret": os.environ.get("AUTH_SECRET"),
    "is_production": os.environ.get("IS_PRODUCTION"),

    # Optional variables
    "customize_error_message": ...,
    "forest_server_url": ...,
    "logger": ...,
    "logger_level": ...,
    "permissions_cache_duration_in_seconds": ...,
    "prefix": ...,
    "schema_path": ...,
})

Mandatory variables

All mandatory variables are provided as environment variables during onboarding.

Your agent cannot be started without them, and no default values are provided.

auth_secret (string, no default)

This variable contains a random secret token which is used to sign authentication tokens used in request between your users and your agent.

It is generated during onboarding, but never leaves your browser, and is not saved on our side.

Never share it to anybody, as that would allow attackers to impersonate your users on your agent!

env_secret (string, no default)

This variable contains a random secret token which is used to authenticate requests between your agent and our servers.

Unlike the auth_secret, it is stored in our database, so it can be privately shared with Forest Admin employees.

Never share it publicly, as it would allow attackers to impersonate your agent with our servers. That would not cause any data leak, but opens the possibility for attackers to cause denial of service.

is_production (boolean, no default)

In development mode the agent has a few extra behaviors (when using is_production=False))

  • At startup, the agent will print the URL of all mounted charts

  • At startup, the agent will update the .forestadmin-schema.json.

  • When exceptions are thrown, a report will be printed to stdout.

Optional variables

customize_error_message (function, defaults to None)

When unexpected errors are raised in the agent code during a request, the error will be logged (using options["logger"]), but in the admin-panel, the final user will get a default message 'Unexpected error'.

This is done as to:

  • Prevent error message from leaking internal information about the agent (credentials, ...).

  • Prevent technical/cryptic error messages to show in the frontend.

This behavior can be customized.

def error_message_customizer(error:Exception):
    if isinstance(error, sqlalchemy.exc.OperationalError):
      return (
          'Failed to connect to the database, ' +
          'contact John at 06 12 34 56 78 and tell him to reboot the server'
      )
    return (
        'Unexpected error, ' +
        'contact Jane at 06 87 65 43 21 and tell her to get it fixed.'
    )

create_agent(app, {
    #...
    "customize_error_message": error_message_customizer
})

server_url (string, defaults to 'https://api.forestadmin.com')

It allows to specify the URL at which Forest Admin servers can be reached.

create_agent(app, {
    # ...
    "server_url": 'https://api.forestadmin.com',
})

logger (function) and logger_level (string, defaults to )logging.INFO

You may want to have control of the logger which is used by Forest Admin.

This configuration key allows to format and route logs to a logging service, instead of printing them in stdout.

import logging

MY_LOGGER = logging.getLogger("my_custom_forest_logger")

def log_function(log_level: str, message:str):
    getattr(MY_LOGGER, log_level.lower())(message)
    # or
    print(f"{log_level}: {message}")

create_agent(app, {
    #...
    # Valid values are logging.(DEBUG|INFO|WARNING|ERROR)
    "logger_level": logging.INFO,
    "logger": log_function
})
import logging

forest_logger = logging.getLogger("forestadmin")
for handler in forest_logger.handlers:
    forest_logger.removeHandler(handler)

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)

forest_logger.addHandler(handler)
forest_logger.setLevel(logging.DEBUG)
# ...

permissions_cache_duration_in_seconds (number, defaults to 15 minutes)

Those permissions are enforced both in the frontend, and in your agent.

This configuration variable allows to customize how often the agent should ask the server to provide the permissions table.

create_agent(app, {
    # ...
    "permissions_cache_duration_in_seconds": 15 * 60,
})

prefix (string, default to empty string)

This variable adds a prefix to the url at which routes are locally mounted on your application. It is mostly used for customers which wish to mount multiple agent instances on the same Node.js process (for setups using multiple Forest Admin projects).

Note that this variable has no influence on the base URL that will be used by your users to reach the agent: it is determined only by the application URL provided during onboarding and deployment.

This is done so that customers using reverse proxies can implement their routing table as they see fit.

Desired Local URLs
Desired Public URLs
How to configure your agent

http://localhost:3000/forest

https://api.company.com/forest

prefix = '' agentUrl = 'https://api.company.com'

http://localhost:3000/forest

https://www.company.com/api/forest

prefix = '' agentUrl = 'https://www.company.com/api'

http://localhost:3000/prefix/forest

https://api.company.com/prefix/forest

prefix = 'prefix' agentUrl = 'https://api.company.com/prefix'

http://localhost:3000/local-prefix/forest

https://api.company.com/public-prefix/forest

prefix = 'local-prefix' agentUrl = 'https://api.company.com/public-prefix'

create_agent(app, {
    # ...
    "prefix": "/api",
})

schema_path (string, defaults to '.forestadmin-schema.json')

This variable allows to choose where the .forestadmin-schema.json file should be written in development, and read from in production.

With Flask agent, the default path is computed as : os.path.join(self._app.root_path, ".forestadmin-schema.json")

This allows to:

  • Improve git repository organisation

  • Work around read only folders (for instance, if developing using a read only docker volume).

  • Have flexibility when using custom builds in production (code minification, ...)

create_agent(app, {
    # ...
    "schema_path": '/volumes/fa-agent-configuration/schema.json',
})
PreviousDjangoNextTroubleshooting

Last updated 8 months ago

Was this helpful?

This variable should be used only for customers using .

If logger is not specified, the agent will log using "forestadmin" logger of . You can customize it as you wish.

Forest Admin administrators can .

the self-hosted version of Forest Admin ↗
logging module ↗
restrict operations which final users can perform ↗
Application URL during onboarding