DEV Community

CodingShower
CodingShower

Posted on

4 3

Profiling Flask Apps

When you're working on Flask apps, at some point one of your routes could get slow in terms of performance (returning response to the client).

The best way to approach such problems (slow programs) is to use a profiler to analyse which parts of your code is slowing down the application.

In Flask we can use the Werkzeug Profiler Middleware to implement profiling in our Flask apps. It is super simple!

from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(...)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app)
Enter fullscreen mode Exit fullscreen mode

That's it! Now when you make a request to one of your endpoints, in your console log, you'll notice stats getting dumped.

----------------------------------------
PATH: '/search'
         7508936 function calls (7492431 primitive calls) in 3.824 seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.701    0.701    2.152    2.152 ...
   101132    0.485    0.000    0.485    0.000 ...
   166457    0.351    0.000    1.258    0.000 ...
  1440656    0.226    0.000    0.347    0.000 ...
5048/4702    0.165    0.000    0.327    0.000 ...
       ...

----------------------------------------
Enter fullscreen mode Exit fullscreen mode
  • If you'd like to learn more about configuring the profiler, head over to this article.
  • If you'd like to learn more about using a statistical profiler, head over to this article.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay