File: falcon_hello_file.py

package info (click to toggle)
python-pyinstrument 5.1.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,624 kB
  • sloc: python: 6,713; ansic: 897; makefile: 46; sh: 26; javascript: 18
file content (41 lines) | stat: -rw-r--r-- 1,022 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import time
from datetime import datetime

from pyinstrument import Profiler

try:
    import falcon

    PROFILING = True  # Use environment variable for setting it
except ImportError:
    print("This example requires falcon.")
    print("Install using `pip install falcon`.")
    exit(1)


class ProfilerMiddleware:
    filename = "pyinstrument-profile"

    def __init__(self, interval=0.01):
        self.profiler = Profiler(interval=interval)

    def process_request(self, req, resp):
        self.profiler.start()

    def process_response(self, req, resp, resource, req_succeeded):
        self.profiler.stop()
        filename = f"{self.filename}-{datetime.now().strftime('%m%d%Y-%H%M%S')}.html"
        with open(filename, "w") as file:
            file.write(self.profiler.output_html())


class HelloResource:
    def on_get(self, req, resp):
        time.sleep(1)
        resp.media = "hello"


app = falcon.App()
if PROFILING:
    app.add_middleware(ProfilerMiddleware())
app.add_route("/", HelloResource())