Skip to content

Commit

Permalink
Turn on profiling when FLASK_PROFILE=True (#451)
Browse files Browse the repository at this point in the history
I am finding myself having to profile the application from time-to-time
to manage performance, so I think it makes sense to have the ability to
just add the profiling middleware using an environment variable flag.
  • Loading branch information
esheehan-gsl committed Nov 27, 2023
1 parent f3e2780 commit 9125ae5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
23 changes: 23 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,29 @@ npm run lint
npm run format
```

## Profiling

If you need to do some performance profiling you can run the debug server with
`FLASK_PROFILE=True`. You’ll need to first create a directory for the profile
files:

```
mkdir -p tmp/profiler
FLASK_PROFILE=True poetry run flask run --debug
```

There are multiple ways you can view the `.prof` files generated by the
profiling middleware. One easy way to view them is with snakeviz.

```
poetry run pip install snakeviz
poetry run snakeviz tmp/profiler/<endpoint>.prof
```

That first line installs snakeviz in your virtual env (without adding it as a
dependency to the project) and the second will load a performance profile into
your default browser for you to view.

## Coding Style

### Python
Expand Down
11 changes: 11 additions & 0 deletions src/unified_graphics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ def create_app(config: Optional[Mapping[str, Any]] = None):
app.config.from_prefixed_env()
app.config.from_mapping(config)

if app.debug and app.config.get("PROFILE", "False") == "True":
from werkzeug.middleware.profiler import ProfilerMiddleware

app.wsgi_app = ProfilerMiddleware( # type: ignore
app.wsgi_app,
restrictions=[30],
stream=None, # Disable stdout
profile_dir="tmp/profiler",
filename_format="{method}-{path}-{time:.0f}-{elapsed:.0f}ms.prof",
)

models.db.init_app(app)

app.register_blueprint(routes.bp)
Expand Down

0 comments on commit 9125ae5

Please sign in to comment.