Compare commits
327 Commits
0.6
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a13b20bbd6 | ||
|
|
07f85152b5 | ||
|
|
cbac0064df | ||
|
|
58b4dd0290 | ||
|
|
e3ce6eb0a6 | ||
|
|
98c611ade9 | ||
|
|
95b02b5920 | ||
|
|
bd642464f2 | ||
|
|
5671a92e17 | ||
|
|
ad6323994f | ||
|
|
2361256107 | ||
|
|
e7b8136dea | ||
|
|
ccf5ae22c6 | ||
|
|
4e98b183f3 | ||
|
|
5b4f4a0fcd | ||
|
|
6f3eae808f | ||
|
|
ffcb3f58df | ||
|
|
b673c8d82a | ||
|
|
63308c7f49 | ||
|
|
b07b074223 | ||
|
|
e005409ac4 | ||
|
|
969bc454b6 | ||
|
|
e6ac868826 | ||
|
|
76a51dccf6 | ||
|
|
a1b9054479 | ||
|
|
2ea3823ae5 | ||
|
|
02d6beff23 | ||
|
|
2f07e43da0 | ||
|
|
654e80c494 | ||
|
|
877e69dc94 | ||
|
|
44ee4b5e3a | ||
|
|
05104beefc | ||
|
|
c3c3d5ec98 | ||
|
|
a2362ec4dd | ||
|
|
449405e3ba | ||
|
|
9b0b63465a | ||
|
|
6848e5440b | ||
|
|
c0539265ca | ||
|
|
b368ff9004 | ||
|
|
ad9f1c0783 | ||
|
|
314ef64e2e | ||
|
|
d4e1b1856b | ||
|
|
0fbc6210a8 | ||
|
|
7d3a6e3733 | ||
|
|
1f904cfa8c | ||
|
|
6174ae7539 | ||
|
|
193a3ed4f2 | ||
|
|
1c82c2861f | ||
|
|
e529ad95bc | ||
|
|
f4702f45fb | ||
|
|
a2a2b1382c | ||
|
|
a0ccd43e8f | ||
|
|
71b7f6f0ce | ||
|
|
cf69fb7f1e | ||
|
|
1d990e7f52 | ||
|
|
cdcf917044 | ||
|
|
691acc186b | ||
|
|
3573841522 | ||
|
|
879918429e | ||
|
|
4ccb3c9be6 | ||
|
|
128bd5af6f | ||
|
|
dfb101fb18 | ||
|
|
9c9f24a2f2 | ||
|
|
bfd4d8506f | ||
|
|
677bf794aa | ||
|
|
c218bb1084 | ||
|
|
ff3ed47d12 | ||
|
|
4225f7f4ad | ||
|
|
a63f64051b | ||
|
|
bf21647c4b | ||
|
|
818e5f2d62 | ||
|
|
c65c6b94e5 | ||
|
|
0ca1f6b241 | ||
|
|
48de4e4a3c | ||
|
|
b139c60a60 | ||
|
|
05f23436ac | ||
|
|
7012193220 | ||
|
|
7f3defff7c | ||
|
|
969cce532d | ||
|
|
c2804c4917 | ||
|
|
56beb35c36 | ||
|
|
98bf17aa58 | ||
|
|
716f05d953 | ||
|
|
fb28aa9d61 | ||
|
|
efe447fb5f | ||
|
|
9656a2cf33 | ||
|
|
9b63ad1837 | ||
|
|
765f22126e | ||
|
|
d4a8cc963e | ||
|
|
b7f5a725cd | ||
|
|
5bf5e093bb | ||
|
|
719fe02df5 | ||
|
|
f18bcc708a | ||
|
|
95c2b86bcd | ||
|
|
b03a2e6fb3 | ||
|
|
1c39a9ce47 | ||
|
|
8c8b2bb35c | ||
|
|
a2e773124f | ||
|
|
2f8ec9027b | ||
|
|
ab9a41df6a | ||
|
|
2b1e7d9907 | ||
|
|
d0360218fd | ||
|
|
e9fd3072a9 | ||
|
|
1aedfb0e2e | ||
|
|
e6ae9d0288 | ||
|
|
62ce443f8b | ||
|
|
2b8bf9cc44 | ||
|
|
42d859534a | ||
|
|
f959951185 | ||
|
|
e1c8704444 | ||
|
|
8a4cfa5e3c | ||
|
|
51d105afad | ||
|
|
15192f19e0 | ||
|
|
5712e57869 | ||
|
|
9571d06df5 | ||
|
|
3b25e114e9 | ||
|
|
f7ae3fd591 | ||
|
|
ce02d2da3c | ||
|
|
bd346a0fc1 | ||
|
|
ed8243e17e | ||
|
|
02c99a7b64 | ||
|
|
96514793e4 | ||
|
|
ec8cc3a0ba | ||
|
|
e3c8ab0ca2 | ||
|
|
fefb32b04d | ||
|
|
b5a7c032ab | ||
|
|
6af24f5f44 | ||
|
|
b4a197f87f | ||
|
|
15b6fee933 | ||
|
|
9e03576c94 | ||
|
|
bfa48c5a2c | ||
|
|
890fd9c7fb | ||
|
|
42a9651950 | ||
|
|
ff01910f6a | ||
|
|
9cdb04edcb | ||
|
|
f546d4633b | ||
|
|
db07028aa0 | ||
|
|
d44ab40729 | ||
|
|
0d409f54f5 | ||
|
|
708df1c07a | ||
|
|
10186a4202 | ||
|
|
3cd2dceace | ||
|
|
376c3deab3 | ||
|
|
45d3588bb6 | ||
|
|
15e8d77a49 | ||
|
|
4d84f262ae | ||
|
|
db64ce632c | ||
|
|
956d7501ec | ||
|
|
a758a9df7a | ||
|
|
5eea25882c | ||
|
|
e954cd9fae | ||
|
|
03d79be02c | ||
|
|
7f17d2ce57 | ||
|
|
30fba11f36 | ||
|
|
d474a6a689 | ||
|
|
83d398d9d5 | ||
|
|
3929742d9c | ||
|
|
70abd78e55 | ||
|
|
dbea74b626 | ||
|
|
c6102aeb14 | ||
|
|
10c9c1ae5d | ||
|
|
9e600c6e13 | ||
|
|
9b8a8afa97 | ||
|
|
39ac97a7e0 | ||
|
|
a5cb5a709f | ||
|
|
02064c76ed | ||
|
|
d713732807 | ||
|
|
b92391d177 | ||
|
|
4964ae261f | ||
|
|
ad847299c4 | ||
|
|
7ce099c3d0 | ||
|
|
9c7db48362 | ||
|
|
88f15cba35 | ||
|
|
d852042ccb | ||
|
|
5bd2e8a423 | ||
|
|
c27256c00a | ||
|
|
010206298e | ||
|
|
678ec31229 | ||
|
|
23d52703fd | ||
|
|
45b70c952f | ||
|
|
9f2c353e86 | ||
|
|
cfe142b285 | ||
|
|
19a25fd895 | ||
|
|
8dcb97c05a | ||
|
|
b49af327cf | ||
|
|
38ab3a49c1 | ||
|
|
9f901e34ae | ||
|
|
f050a6b0de | ||
|
|
e33f3e1c85 | ||
|
|
02ff95acde | ||
|
|
2436239964 | ||
|
|
18a0030354 | ||
|
|
ee726eece2 | ||
|
|
1cd9ba69d1 | ||
|
|
30a1cd399a | ||
|
|
0524e7f3e9 | ||
|
|
14cd912df7 | ||
|
|
f087311f7c | ||
|
|
61d1fc2678 | ||
|
|
6b2566c01f | ||
|
|
31ea3bce41 | ||
|
|
2d60ea6c8d | ||
|
|
56994a522d | ||
|
|
aa90a9d052 | ||
|
|
32e0aa8ca3 | ||
|
|
e052b005ec | ||
|
|
2f18ac90f9 | ||
|
|
612f93c129 | ||
|
|
c0826c9a31 | ||
|
|
7e2de8f588 | ||
|
|
5aaa7a6634 | ||
|
|
f7feecc751 | ||
|
|
cfe1624730 | ||
|
|
95d7eb977f | ||
|
|
794380fc03 | ||
|
|
5a05620257 | ||
|
|
bebe884615 | ||
|
|
10c03880c7 | ||
|
|
3fcdfc8f83 | ||
|
|
914553ddf5 | ||
|
|
b4fe0b954c | ||
|
|
7557ee6794 | ||
|
|
382c5e7da9 | ||
|
|
6286dadc27 | ||
|
|
81f8e34846 | ||
|
|
79717926a5 | ||
|
|
5084428c9d | ||
|
|
82295aa4aa | ||
|
|
70488fc14a | ||
|
|
4901d68b01 | ||
|
|
d671a849bb | ||
|
|
ffbdf0f563 | ||
|
|
b08fe477b6 | ||
|
|
903ed85f00 | ||
|
|
5710314252 | ||
|
|
277462d822 | ||
|
|
26691d49cd | ||
|
|
bd37db9dc4 | ||
|
|
091c4fa70c | ||
|
|
d5987410d1 | ||
|
|
6d8249160d | ||
|
|
1e046d57f4 | ||
|
|
9e3546b416 | ||
|
|
26034475f2 | ||
|
|
356e6c8268 | ||
|
|
5870fce178 | ||
|
|
855c7ab377 | ||
|
|
ccd8ba66b2 | ||
|
|
093763909f | ||
|
|
115e874a39 | ||
|
|
bd2b65d068 | ||
|
|
b7c39113e7 | ||
|
|
05288daf17 | ||
|
|
79421df5cd | ||
|
|
8d5d37fa0b | ||
|
|
1029b9131b | ||
|
|
3bea63dc8a | ||
|
|
856eb52a95 | ||
|
|
50017f13a7 | ||
|
|
561889738f | ||
|
|
b97e58c1f2 | ||
|
|
0f923475c8 | ||
|
|
43df69ab24 | ||
|
|
3e4cd1ecfa | ||
|
|
cfa5984d3e | ||
|
|
c9c0228a62 | ||
|
|
d87e7fc347 | ||
|
|
80eb747816 | ||
|
|
913c4130b6 | ||
|
|
ffed47e157 | ||
|
|
c7b0b4bf2b | ||
|
|
defbaefb44 | ||
|
|
18414d733b | ||
|
|
83523d6f59 | ||
|
|
97fc95f769 | ||
|
|
484575eb66 | ||
|
|
e34c10d15b | ||
|
|
025a7bebb6 | ||
|
|
bada1ae429 | ||
|
|
b7a67a0486 | ||
|
|
addfb343b0 | ||
|
|
11cb1daadf | ||
|
|
ddeaa2b958 | ||
|
|
9c1d859cfd | ||
|
|
d927012d75 | ||
|
|
72e8e277af | ||
|
|
75bac4e961 | ||
|
|
f84087156a | ||
|
|
56be56de86 | ||
|
|
f6e37be73c | ||
|
|
71bd15a4d6 | ||
|
|
7e8a8e280e | ||
|
|
672fdb59e6 | ||
|
|
b5a6fbe839 | ||
|
|
824f73d9aa | ||
|
|
d8d2fb7a85 | ||
|
|
8a922a2a5c | ||
|
|
ba56f81d19 | ||
|
|
002dea199e | ||
|
|
bb99b48833 | ||
|
|
210dfb48fc | ||
|
|
7e83d45d6c | ||
|
|
6d268ba00b | ||
|
|
e92c102bc9 | ||
|
|
20a302c3b4 | ||
|
|
bdbc570c91 | ||
|
|
17b629742d | ||
|
|
54a18b8cf2 | ||
|
|
a48efe822a | ||
|
|
45ce65c058 | ||
|
|
89fbe2e6b5 | ||
|
|
e5feff5884 | ||
|
|
93008a8e53 | ||
|
|
8bb829e1e4 | ||
|
|
70478ffcc2 | ||
|
|
6f6b1cb47d | ||
|
|
1834443246 | ||
|
|
c3c2714ace | ||
|
|
884451669c | ||
|
|
0bdc3f7e59 | ||
|
|
43b069905d | ||
|
|
d85ce273af | ||
|
|
69d137c2d7 | ||
|
|
7988e5f472 | ||
|
|
1c8465cdd9 | ||
|
|
f59705a7e7 | ||
|
|
d886f5a606 |
13
.editorconfig
Normal file
@@ -0,0 +1,13 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
max_line_length = 88
|
||||
|
||||
[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]
|
||||
indent_size = 2
|
||||
29
.github/ISSUE_TEMPLATE/bug-report.md
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Report a bug in Flask-DebugToolbar (not other projects which depend on Flask-DebugToolbar)
|
||||
---
|
||||
|
||||
<!--
|
||||
This issue tracker is a tool to address bugs in Flask-DebugToolbar itself.
|
||||
Please use GitHub Discussions or the Pallets Discord for questions about your
|
||||
own code.
|
||||
|
||||
Replace this comment with a clear outline of what the bug is.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Describe how to replicate the bug.
|
||||
|
||||
Include a minimal reproducible example that demonstrates the bug.
|
||||
Include the full traceback if there was an exception.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Describe the expected behavior that should have happened but didn't.
|
||||
-->
|
||||
|
||||
Environment:
|
||||
|
||||
- Python version:
|
||||
- Flask-DebugToolbar version:
|
||||
- Flask version:
|
||||
8
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Questions on Discussions
|
||||
url: https://github.com/pallets-eco/flask-debugtoolbar/discussions/
|
||||
about: Ask questions about your own code on the Discussions tab.
|
||||
- name: Questions on Chat
|
||||
url: https://discord.gg/pallets
|
||||
about: Ask questions about your own code on our Discord chat.
|
||||
15
.github/ISSUE_TEMPLATE/feature-request.md
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest a new feature for Flask-DebugToolbar
|
||||
---
|
||||
|
||||
<!--
|
||||
Replace this comment with a description of what the feature should do.
|
||||
Include details such as links to relevant specs or previous discussions.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Replace this comment with an example of the problem which this feature
|
||||
would resolve. Is this problem solvable without changes to Flask-DebugToolbar,
|
||||
such as by subclassing or using an extension?
|
||||
-->
|
||||
18
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- '*'
|
||||
- package-ecosystem: pip
|
||||
directory: /requirements/
|
||||
schedule:
|
||||
interval: monthly
|
||||
groups:
|
||||
python-requirements:
|
||||
patterns:
|
||||
- '*'
|
||||
25
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
<!--
|
||||
Before opening a PR, open a ticket describing the issue or feature the
|
||||
PR will address. An issue is not required for fixing typos in
|
||||
documentation, or other simple non-code changes.
|
||||
|
||||
Replace this comment with a description of the change. Describe how it
|
||||
addresses the linked ticket.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Link to relevant issues or previous PRs, one per line. Use "fixes" to
|
||||
automatically close an issue.
|
||||
|
||||
fixes #<issue number>
|
||||
-->
|
||||
|
||||
<!--
|
||||
Ensure each step in the contributing guide is complete, especially the following:
|
||||
|
||||
- Add tests that demonstrate the correct behavior of the change. Tests
|
||||
should fail without the change.
|
||||
- Add or update relevant docs, in the docs folder and in code.
|
||||
- Add an entry in CHANGES.rst summarizing the change and linking to the issue.
|
||||
- Add `.. versionchanged::` entries in any relevant code docs.
|
||||
-->
|
||||
23
.github/workflows/lock.yaml
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
name: Lock inactive closed issues
|
||||
# Lock closed issues that have not received any further activity for two weeks.
|
||||
# This does not close open issues, only humans may do that. It is easier to
|
||||
# respond to new issues with fresh examples rather than continuing discussions
|
||||
# on old issues.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *'
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
concurrency:
|
||||
group: lock
|
||||
jobs:
|
||||
lock:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1
|
||||
with:
|
||||
issue-inactive-days: 14
|
||||
pr-inactive-days: 14
|
||||
discussion-inactive-days: 14
|
||||
73
.github/workflows/publish.yaml
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
name: Publish
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
hash: ${{ steps.hash.outputs.hash }}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0
|
||||
with:
|
||||
python-version: '3.x'
|
||||
cache: pip
|
||||
cache-dependency-path: requirements*/*.txt
|
||||
- run: pip install -r requirements/build.txt
|
||||
# Use the commit date instead of the current date during the build.
|
||||
- run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV
|
||||
- run: python -m build
|
||||
# Generate hashes used for provenance.
|
||||
- name: generate hash
|
||||
id: hash
|
||||
run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT
|
||||
- uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0
|
||||
with:
|
||||
path: ./dist
|
||||
provenance:
|
||||
needs: [build]
|
||||
permissions:
|
||||
actions: read
|
||||
id-token: write
|
||||
contents: write
|
||||
# Can't pin with hash due to how this workflow works.
|
||||
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0
|
||||
with:
|
||||
base64-subjects: ${{ needs.build.outputs.hash }}
|
||||
create-release:
|
||||
# Upload the sdist, wheels, and provenance to a GitHub release. They remain
|
||||
# available as build artifacts for a while as well.
|
||||
needs: [provenance]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
|
||||
- name: create release
|
||||
run: >
|
||||
gh release create --draft --repo ${{ github.repository }}
|
||||
${{ github.ref_name }}
|
||||
*.intoto.jsonl/* artifact/*
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
publish-pypi:
|
||||
needs: [provenance]
|
||||
# Wait for approval before attempting to upload to PyPI. This allows reviewing the
|
||||
# files in the draft release.
|
||||
environment:
|
||||
name: publish
|
||||
url: https://pypi.org/project/Flask-DebugToolbar/${{ github.ref_name }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
|
||||
- uses: pypa/gh-action-pypi-publish@8a08d616893759ef8e1aa1f2785787c0b97e20d6 # v1.10.0
|
||||
with:
|
||||
repository-url: https://test.pypi.org/legacy/
|
||||
packages-dir: artifact/
|
||||
- uses: pypa/gh-action-pypi-publish@8a08d616893759ef8e1aa1f2785787c0b97e20d6 # v1.10.0
|
||||
with:
|
||||
packages-dir: artifact/
|
||||
55
.github/workflows/tests.yaml
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
name: Tests
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- '*.x'
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- '*.md'
|
||||
- '*.rst'
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- '*.md'
|
||||
- '*.rst'
|
||||
jobs:
|
||||
tests:
|
||||
name: ${{ matrix.name || matrix.python }}
|
||||
runs-on: ${{ matrix.os || 'ubuntu-latest' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- {python: '3.12'}
|
||||
- {python: '3.11'}
|
||||
- {python: '3.10'}
|
||||
- {python: '3.9'}
|
||||
- {python: '3.8'}
|
||||
- {name: Minimal, python: '3.12', tox: minimal}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
allow-prereleases: true
|
||||
cache: pip
|
||||
cache-dependency-path: requirements*/*.txt
|
||||
- run: pip install tox
|
||||
- run: tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }}
|
||||
typing:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0
|
||||
with:
|
||||
python-version: '3.x'
|
||||
cache: pip
|
||||
cache-dependency-path: requirements*/*.txt
|
||||
- name: cache mypy
|
||||
uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2
|
||||
with:
|
||||
path: ./.mypy_cache
|
||||
key: mypy|${{ hashFiles('pyproject.toml') }}
|
||||
- run: pip install tox
|
||||
- run: tox run -e typing
|
||||
12
.gitignore
vendored
@@ -1,4 +1,10 @@
|
||||
*.egg-info
|
||||
*.pyc
|
||||
build/
|
||||
.idea/
|
||||
.vscode/
|
||||
.venv*/
|
||||
venv*/
|
||||
__pycache__/
|
||||
dist/
|
||||
.coverage*
|
||||
htmlcov/
|
||||
.tox/
|
||||
docs/_build/
|
||||
|
||||
21
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
ci:
|
||||
autoupdate_schedule: monthly
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.6.3
|
||||
hooks:
|
||||
- id: ruff
|
||||
- id: ruff-format
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
hooks:
|
||||
- id: check-merge-conflict
|
||||
exclude: "(codemirror|jquery)"
|
||||
- id: debug-statements
|
||||
exclude: "(codemirror|jquery)"
|
||||
- id: fix-byte-order-marker
|
||||
exclude: "(codemirror|jquery)"
|
||||
- id: trailing-whitespace
|
||||
exclude: "(codemirror|jquery)"
|
||||
- id: end-of-file-fixer
|
||||
exclude: "(codemirror|jquery)"
|
||||
13
.readthedocs.yaml
Normal file
@@ -0,0 +1,13 @@
|
||||
version: 2
|
||||
build:
|
||||
os: ubuntu-22.04
|
||||
tools:
|
||||
python: '3.12'
|
||||
python:
|
||||
install:
|
||||
- requirements: requirements/docs.txt
|
||||
- method: pip
|
||||
path: .
|
||||
sphinx:
|
||||
builder: dirhtml
|
||||
fail_on_warning: true
|
||||
@@ -1,24 +1,21 @@
|
||||
Copyright (c) Rob Hudson and individual contributors.
|
||||
All rights reserved.
|
||||
Copyright 2011 Pallets Community Ecosystem
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of Django nor the names of its contributors may be used
|
||||
to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
@@ -1,2 +0,0 @@
|
||||
recursive-include flask_debugtoolbar/templates/ *.html
|
||||
recursive-include flask_debugtoolbar/static/ *
|
||||
12
README
@@ -1,12 +0,0 @@
|
||||
Flask Debug-toolbar
|
||||
|
||||
A port of the django-debug toolbar (github.com/robhudson/django-debug-toolbar)
|
||||
to Flask.
|
||||
|
||||
Usage::
|
||||
|
||||
from flask import Flask
|
||||
from flask_debugtoolbar import DebugToolbarExtension
|
||||
|
||||
app = Flask(__name__)
|
||||
toolbar = DebugToolbarExtension(app)
|
||||
44
README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Flask-DebugToolbar
|
||||
|
||||
A [Flask][] extension that injects debugging information into rendered HTML
|
||||
pages. Presented as a sidebar with configurable panels of information.
|
||||
|
||||
This is a port of the excellent [django-debug-toolbar][ddt].
|
||||
|
||||
[Flask]: https://flask.palletsprojects.com
|
||||
[ddt]: https://github.com/jazzband/django-debug-toolbar/
|
||||
|
||||
|
||||
## Pallets Community Ecosystem
|
||||
|
||||
> [!IMPORTANT]\
|
||||
> This project is part of the Pallets Community Ecosystem. Pallets is the open
|
||||
> source organization that maintains Flask; Pallets-Eco enables community
|
||||
> maintenance of related projects. If you are interested in helping maintain
|
||||
> this project, please reach out on [the Pallets Discord server][discord].
|
||||
|
||||
[discord]: https://discord.gg/pallets
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
Setting up the debug toolbar is simple:
|
||||
|
||||
```python
|
||||
from flask import Flask
|
||||
from flask_debugtoolbar import DebugToolbarExtension
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config["SECRET_KEY"] = "<replace with a secret key>"
|
||||
|
||||
toolbar = DebugToolbarExtension(app)
|
||||
```
|
||||
|
||||
The toolbar will automatically be injected into Jinja templates when debug
|
||||
mode is enabled.
|
||||
|
||||
```
|
||||
$ flask -A my_app run --debug
|
||||
```
|
||||
|
||||

|
||||
BIN
docs/_static/example.gif
vendored
Normal file
|
After Width: | Height: | Size: 156 KiB |
BIN
docs/_static/screenshot-config-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/_static/screenshot-headers-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
docs/_static/screenshot-logger-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
docs/_static/screenshot-profiler-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 51 KiB |
BIN
docs/_static/screenshot-request-vars-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/_static/screenshot-sqlalchemy-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
docs/_static/screenshot-template-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
docs/_static/screenshot-time-panel.png
vendored
Normal file
|
After Width: | Height: | Size: 42 KiB |
39
docs/conf.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import importlib.metadata
|
||||
|
||||
# Project --------------------------------------------------------------
|
||||
|
||||
project = "Flask-DebugToolbar"
|
||||
version = release = importlib.metadata.version("flask-debugtoolbar").partition(".dev")[
|
||||
0
|
||||
]
|
||||
|
||||
# General --------------------------------------------------------------
|
||||
|
||||
default_role = "code"
|
||||
extensions = [
|
||||
"sphinx.ext.autodoc",
|
||||
"sphinx.ext.extlinks",
|
||||
"sphinx.ext.intersphinx",
|
||||
"sphinxcontrib.log_cabinet",
|
||||
"pallets_sphinx_themes",
|
||||
]
|
||||
autodoc_member_order = "bysource"
|
||||
autodoc_typehints = "description"
|
||||
autodoc_preserve_defaults = True
|
||||
extlinks = {
|
||||
"issue": ("https://github.com/pallets-eco/flask-debugtoolbar/issues/%s", "#%s"),
|
||||
"pr": ("https://github.com/pallets-eco/flask-debugtoolbar/pull/%s", "#%s"),
|
||||
}
|
||||
intersphinx_mapping = {
|
||||
"python": ("https://docs.python.org/3/", None),
|
||||
"flasksqlalchemy": ("https://flask-sqlalchemy.palletsprojects.com", None),
|
||||
}
|
||||
|
||||
# HTML -----------------------------------------------------------------
|
||||
|
||||
html_theme = "flask"
|
||||
html_static_path = ["_static"]
|
||||
html_copy_source = False
|
||||
html_show_copyright = False
|
||||
html_use_index = False
|
||||
html_domain_indices = False
|
||||
98
docs/index.rst
Normal file
@@ -0,0 +1,98 @@
|
||||
Flask-DebugToolbar
|
||||
==================
|
||||
|
||||
This extension adds a toolbar overlay to Flask applications containing useful information for debugging.
|
||||
|
||||
.. image:: _static/example.gif
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Installing is simple with `pip`_::
|
||||
|
||||
$ pip install flask-debugtoolbar
|
||||
|
||||
.. _pip: https://pip.pypa.io/
|
||||
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Setting up the debug toolbar is simple::
|
||||
|
||||
from flask import Flask
|
||||
from flask_debugtoolbar import DebugToolbarExtension
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# the toolbar is only enabled in debug mode:
|
||||
app.debug = True
|
||||
|
||||
# set a 'SECRET_KEY' to enable the Flask session cookies
|
||||
app.config['SECRET_KEY'] = '<replace with a secret key>'
|
||||
|
||||
toolbar = DebugToolbarExtension(app)
|
||||
|
||||
|
||||
The toolbar will automatically be injected into HTML responses when debug mode
|
||||
is on. In production, setting ``app.debug = False`` will disable the toolbar.
|
||||
|
||||
This extension also supports the Flask app factory pattern by separately
|
||||
creating the toolbar and later initializing it for an app::
|
||||
|
||||
toolbar = DebugToolbarExtension()
|
||||
# Then later on.
|
||||
app = create_app('the-config.cfg')
|
||||
toolbar.init_app(app)
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
|
||||
The toolbar support several configuration options:
|
||||
|
||||
==================================== ===================================== ==========================
|
||||
Name Description Default
|
||||
==================================== ===================================== ==========================
|
||||
``DEBUG_TB_ENABLED`` Enable the toolbar? ``app.debug``
|
||||
``DEBUG_TB_HOSTS`` Whitelist of hosts to display toolbar any host
|
||||
``DEBUG_TB_ROUTES_HOST`` The host to associate with toolbar ``None``
|
||||
routes (where its assets are served
|
||||
from), or the sentinel value `*` to
|
||||
serve from the same host as the
|
||||
current request (ie any host). This
|
||||
is only required if Flask is
|
||||
configured to use `host_matching`.
|
||||
``DEBUG_TB_INTERCEPT_REDIRECTS`` Should intercept redirects? ``True``
|
||||
``DEBUG_TB_PANELS`` List of module/class names of panels enable all built-in panels
|
||||
``DEBUG_TB_PROFILER_ENABLED`` Enable the profiler on all requests ``False``, user-enabled
|
||||
``DEBUG_TB_TEMPLATE_EDITOR_ENABLED`` Enable the template editor ``False``
|
||||
``DEBUG_TB_PROFILER_DUMP_FILENAME`` Filename of the profiler stats dump, ``None``, no dump will be written
|
||||
can be a ``str`` or a ``callable``
|
||||
==================================== ===================================== ==========================
|
||||
|
||||
To change one of the config options, set it in the Flask app's config like::
|
||||
|
||||
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
|
||||
|
||||
|
||||
Panels
|
||||
------
|
||||
|
||||
.. toctree::
|
||||
|
||||
panels
|
||||
license
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Fork us `on GitHub <https://github.com/pallets-eco/flask-debugtoolbar>`_
|
||||
|
||||
Thanks
|
||||
------
|
||||
|
||||
This was based on the original `django-debug-toolbar`_. Thanks to `Michael van Tellingen`_ for the original development of this Flask extension, and to all the `individual contributors`_.
|
||||
|
||||
.. _django-debug-toolbar: https://github.com/jazzband/django-debug-toolbar
|
||||
.. _Michael van Tellingen: https://github.com/mvantellingen
|
||||
.. _individual contributors: https://github.com/pallets-eco/flask-debugtoolbar/graphs/contributors
|
||||
5
docs/license.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
BSD-3-Clause License
|
||||
====================
|
||||
|
||||
.. literalinclude:: ../LICENSE.txt
|
||||
:language: text
|
||||
110
docs/panels.rst
Normal file
@@ -0,0 +1,110 @@
|
||||
Built-In Panels
|
||||
===============
|
||||
|
||||
Versions
|
||||
--------
|
||||
flask_debugtoolbar.panels.versions.VersionDebugPanel
|
||||
|
||||
Shows the installed Flask version. The expanded view displays all installed packages and their versions as detected by ``setuptools``.
|
||||
|
||||
|
||||
Time
|
||||
----
|
||||
|
||||
flask_debugtoolbar.panels.timer.TimerDebugPanel
|
||||
|
||||
Shows the time taken to process the current request. The expanded view includes the breakdown of CPU time, by user and system, wall clock time, and context switches.
|
||||
|
||||
.. image:: _static/screenshot-time-panel.png
|
||||
|
||||
|
||||
HTTP Headers
|
||||
------------
|
||||
|
||||
flask_debugtoolbar.panels.headers.HeaderDebugPanel
|
||||
|
||||
Displays the HTTP headers for the current request.
|
||||
|
||||
.. image:: _static/screenshot-headers-panel.png
|
||||
|
||||
|
||||
Request Vars
|
||||
------------
|
||||
|
||||
flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel
|
||||
|
||||
Displays details of the Flask request-related variables, including the view function parameters, cookies, session variables, and GET and POST variables.
|
||||
|
||||
.. image:: _static/screenshot-request-vars-panel.png
|
||||
|
||||
|
||||
Config
|
||||
------
|
||||
|
||||
flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel
|
||||
|
||||
Shows the contents of the Flask application's config dict ``app.config``.
|
||||
|
||||
.. image:: _static/screenshot-config-panel.png
|
||||
|
||||
|
||||
Templates
|
||||
---------
|
||||
|
||||
flask_debugtoolbar.panels.template.TemplateDebugPanel
|
||||
|
||||
Shows information about the templates rendered for this request, and the value of the template parameters provided.
|
||||
|
||||
.. image:: _static/screenshot-template-panel.png
|
||||
|
||||
|
||||
SQLAlchemy
|
||||
----------
|
||||
|
||||
flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel
|
||||
|
||||
Shows SQL queries run during the current request.
|
||||
|
||||
.. note:: This panel requires using the `Flask-SQLAlchemy`_ extension in order
|
||||
to record the queries. See the Flask-SQLAlchemy
|
||||
:ref:`flasksqlalchemy:quickstart` section to configure it.
|
||||
|
||||
For additional details on query recording see the
|
||||
:py:func:`~flask_sqlalchemy.get_debug_queries` documentation.
|
||||
|
||||
.. note:: SQL syntax highlighting requires `Pygments`_ to be installed.
|
||||
|
||||
.. image:: _static/screenshot-sqlalchemy-panel.png
|
||||
|
||||
.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/
|
||||
|
||||
.. _Pygments: https://pygments.org/
|
||||
|
||||
|
||||
Logging
|
||||
-------
|
||||
|
||||
flask_debugtoolbar.panels.logger.LoggingPanel
|
||||
|
||||
Displays log messages recorded during the current request.
|
||||
|
||||
.. image:: _static/screenshot-logger-panel.png
|
||||
|
||||
|
||||
Route List
|
||||
----------
|
||||
|
||||
flask_debugtoolbar.panels.route_list.RouteListDebugPanel
|
||||
|
||||
|
||||
Displays the Flask URL routing rules.
|
||||
|
||||
|
||||
Profiler
|
||||
--------
|
||||
|
||||
flask_debugtoolbar.panels.profiler.ProfilerDebugPanel
|
||||
|
||||
Reports profiling data for the current request. Due to the performance overhead, profiling is disabled by default. Click the checkmark to toggle profiling on or off. After enabling the profiler, refresh the page to re-run it with profiling.
|
||||
|
||||
.. image:: _static/screenshot-profiler-panel.png
|
||||
50
example/app.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# Run using: `FLASK_DEBUG=True flask run`
|
||||
|
||||
from flask import Flask
|
||||
from flask import redirect
|
||||
from flask import render_template
|
||||
from flask import url_for
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
from flask_debugtoolbar import DebugToolbarExtension
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = True
|
||||
# app.config['DEBUG_TB_PANELS'] = (
|
||||
# 'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
|
||||
# 'flask_debugtoolbar.panels.logger.LoggingPanel',
|
||||
# 'flask_debugtoolbar.panels.timer.TimerDebugPanel',
|
||||
# )
|
||||
# app.config['DEBUG_TB_HOSTS'] = ('127.0.0.1', '::1' )
|
||||
app.config["SECRET_KEY"] = "asd"
|
||||
app.config["SQLALCHEMY_RECORD_QUERIES"] = True
|
||||
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
|
||||
# This is no longer needed for Flask-SQLAlchemy 3.0+, if you're using 2.X you'll
|
||||
# want to define this:
|
||||
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
db = SQLAlchemy(app)
|
||||
toolbar = DebugToolbarExtension(app)
|
||||
|
||||
|
||||
class ExampleModel(db.Model):
|
||||
__tablename__ = "examples"
|
||||
value = db.Column(db.String(100), primary_key=True)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
app.logger.info("Hello there")
|
||||
ExampleModel.query.get(1)
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.route("/redirect")
|
||||
def redirect_example():
|
||||
response = redirect(url_for("index"))
|
||||
response.set_cookie("test_cookie", "1")
|
||||
return response
|
||||
|
||||
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
@@ -1,46 +0,0 @@
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
from flask import Flask, render_template, redirect, url_for
|
||||
from flaskext.script import Manager
|
||||
from flaskext.sqlalchemy import SQLAlchemy
|
||||
from flask_debugtoolbar import DebugToolbarExtension
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
|
||||
#app.config['DEBUG_TB_PANELS'] = (
|
||||
# 'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
|
||||
# 'flask_debugtoolbar.panels.logger.LoggingPanel',
|
||||
# 'flask_debugtoolbar.panels.timer.TimerDebugPanel',
|
||||
#)
|
||||
app.config['SECRET_KEY'] = 'asd'
|
||||
app.config['DEBUG'] = True
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
|
||||
db = SQLAlchemy(app)
|
||||
|
||||
toolbar = DebugToolbarExtension(app)
|
||||
|
||||
class ExampleModel(db.Model):
|
||||
__tablename__ = 'examples'
|
||||
value = db.Column(db.String(100), primary_key=True)
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
app.logger.info("Hello there")
|
||||
ExampleModel.query.get(1)
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/redirect')
|
||||
def redirect_example():
|
||||
|
||||
response = redirect(url_for('index'))
|
||||
response.set_cookie('test_cookie', '1')
|
||||
return response
|
||||
|
||||
if __name__ == "__main__":
|
||||
db.create_all()
|
||||
|
||||
manager = Manager(app)
|
||||
manager.run()
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
import os
|
||||
|
||||
from flask import current_app, request, g
|
||||
from flask.globals import _request_ctx_stack
|
||||
from flask import send_from_directory
|
||||
from jinja2 import Environment, PackageLoader
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from werkzeug.urls import url_quote_plus
|
||||
|
||||
from flask_debugtoolbar.toolbar import DebugToolbar
|
||||
from flask import Blueprint
|
||||
|
||||
|
||||
module = Blueprint('debugtoolbar', __name__)
|
||||
|
||||
def replace_insensitive(string, target, replacement):
|
||||
"""Similar to string.replace() but is case insensitive
|
||||
Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
|
||||
"""
|
||||
no_case = string.lower()
|
||||
index = no_case.rfind(target.lower())
|
||||
if index >= 0:
|
||||
return string[:index] + replacement + string[index + len(target):]
|
||||
else: # no results so return the original string
|
||||
return string
|
||||
|
||||
|
||||
class DebugToolbarExtension(object):
|
||||
_static_dir = os.path.realpath(
|
||||
os.path.join(os.path.dirname(__file__), 'static'))
|
||||
|
||||
_redirect_codes = [301, 302, 303, 304]
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.debug_toolbars = {}
|
||||
|
||||
if not app.debug:
|
||||
return
|
||||
|
||||
if not app.config.get('SECRET_KEY'):
|
||||
raise RuntimeError(
|
||||
"The Flask-DebugToolbar requires the 'SECRET_KEY' config "
|
||||
"var to be set")
|
||||
|
||||
DebugToolbar.load_panels(app)
|
||||
|
||||
self.app.before_request(self.process_request)
|
||||
self.app.after_request(self.process_response)
|
||||
|
||||
# Monkey-patch the Flask.dispatch_request method
|
||||
app.dispatch_request = self.dispatch_request
|
||||
|
||||
# Configure jinja for the internal templates and add url rules
|
||||
# for static data
|
||||
self.jinja_env = Environment(
|
||||
autoescape=True,
|
||||
extensions=['jinja2.ext.i18n'],
|
||||
loader=PackageLoader(__name__, 'templates'))
|
||||
self.jinja_env.filters['urlencode'] = url_quote_plus
|
||||
|
||||
app.add_url_rule('/_debug_toolbar/static/<path:filename>',
|
||||
'_debug_toolbar.static', self.send_static_file)
|
||||
|
||||
app.register_blueprint(module, url_prefix='/_debug_toolbar/views')
|
||||
|
||||
def dispatch_request(self):
|
||||
"""Modified version of Flask.dispatch_request to call process_view."""
|
||||
req = _request_ctx_stack.top.request
|
||||
app = current_app
|
||||
|
||||
if req.routing_exception is not None:
|
||||
app.raise_routing_exception(req)
|
||||
|
||||
rule = req.url_rule
|
||||
|
||||
# if we provide automatic options for this URL and the
|
||||
# request came with the OPTIONS method, reply automatically
|
||||
if getattr(rule, 'provide_automatic_options', False) \
|
||||
and req.method == 'OPTIONS':
|
||||
return app.make_default_options_response()
|
||||
|
||||
# otherwise dispatch to the handler for that endpoint
|
||||
view_func = app.view_functions[rule.endpoint]
|
||||
view_func = self.process_view(app, view_func, req.view_args)
|
||||
|
||||
return view_func(**req.view_args)
|
||||
|
||||
def _show_toolbar(self):
|
||||
"""Return a boolean to indicate if we need to show the toolbar."""
|
||||
if request.path.startswith('/_debug_toolbar/'):
|
||||
return False
|
||||
return True
|
||||
|
||||
def send_static_file(self, filename):
|
||||
"""Send a static file from the flask-debugtoolbar static directory."""
|
||||
return send_from_directory(self._static_dir, filename)
|
||||
|
||||
def process_request(self):
|
||||
g.debug_toolbar = self
|
||||
|
||||
if not self._show_toolbar():
|
||||
return
|
||||
|
||||
real_request = request._get_current_object()
|
||||
|
||||
self.debug_toolbars[real_request] = DebugToolbar(real_request, self.jinja_env)
|
||||
for panel in self.debug_toolbars[real_request].panels:
|
||||
panel.process_request(real_request)
|
||||
|
||||
def process_view(self, app, view_func, view_kwargs):
|
||||
""" This method is called just before the flask view is called.
|
||||
This is done by the dispatch_request method.
|
||||
"""
|
||||
real_request = request._get_current_object()
|
||||
if real_request in self.debug_toolbars:
|
||||
for panel in self.debug_toolbars[real_request].panels:
|
||||
new_view = panel.process_view(real_request, view_func, view_kwargs)
|
||||
if new_view:
|
||||
view_func = new_view
|
||||
return view_func
|
||||
|
||||
def process_response(self, response):
|
||||
real_request = request._get_current_object()
|
||||
if real_request not in self.debug_toolbars:
|
||||
return response
|
||||
|
||||
# Intercept http redirect codes and display an html page with a
|
||||
# link to the target.
|
||||
if self.debug_toolbars[real_request].config['DEBUG_TB_INTERCEPT_REDIRECTS']:
|
||||
if response.status_code in self._redirect_codes:
|
||||
redirect_to = response.location
|
||||
redirect_code = response.status_code
|
||||
if redirect_to:
|
||||
content = self.render('redirect.html', {
|
||||
'redirect_to': redirect_to,
|
||||
'redirect_code': redirect_code
|
||||
})
|
||||
response.content_length = len(content)
|
||||
response.location = None
|
||||
response.response = [content]
|
||||
response.status_code = 200
|
||||
|
||||
# If the http response code is 200 then we process to add the
|
||||
# toolbar to the returned html response.
|
||||
if (response.status_code == 200
|
||||
and response.headers['content-type'].startswith('text/html')):
|
||||
for panel in self.debug_toolbars[real_request].panels:
|
||||
panel.process_response(real_request, response)
|
||||
|
||||
if response.is_sequence:
|
||||
response_html = response.data.decode(response.charset)
|
||||
toolbar_html = self.debug_toolbars[real_request].render_toolbar()
|
||||
|
||||
content = replace_insensitive(
|
||||
response_html, '</body>', toolbar_html + '</body>')
|
||||
content = content.encode(response.charset)
|
||||
response.response = [content]
|
||||
response.content_length = len(content)
|
||||
|
||||
return response
|
||||
|
||||
def render(self, template_name, context):
|
||||
template = self.jinja_env.get_template(template_name)
|
||||
return template.render(**context)
|
||||
@@ -1,61 +0,0 @@
|
||||
"""Base DebugPanel class"""
|
||||
|
||||
class DebugPanel(object):
|
||||
"""
|
||||
Base class for debug panels.
|
||||
"""
|
||||
# name = Base
|
||||
has_content = False # If content returns something, set to true in subclass
|
||||
|
||||
# If the client is able to activate/de-activate the panel
|
||||
user_enable = False
|
||||
|
||||
|
||||
# We'll maintain a local context instance so we can expose our template
|
||||
# context variables to panels which need them:
|
||||
context = {}
|
||||
|
||||
# Panel methods
|
||||
def __init__(self, jinja_env, context={}):
|
||||
self.context.update(context)
|
||||
self.jinja_env = jinja_env
|
||||
|
||||
# If the client enabled the panel
|
||||
self.is_active = False
|
||||
|
||||
def render(self, template_name, context):
|
||||
template = self.jinja_env.get_template(template_name)
|
||||
return template.render(**context)
|
||||
|
||||
def dom_id(self):
|
||||
return 'flDebug%sPanel' % (self.name.replace(' ', ''))
|
||||
|
||||
def nav_title(self):
|
||||
"""Title showing in toolbar"""
|
||||
raise NotImplementedError
|
||||
|
||||
def nav_subtitle(self):
|
||||
"""Subtitle showing until title in toolbar"""
|
||||
return ''
|
||||
|
||||
def title(self):
|
||||
"""Title showing in panel"""
|
||||
raise NotImplementedError
|
||||
|
||||
def url(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def content(self):
|
||||
raise NotImplementedError
|
||||
|
||||
# Standard middleware methods
|
||||
def process_request(self, request):
|
||||
pass
|
||||
|
||||
def process_view(self, request, view_func, view_kwargs):
|
||||
pass
|
||||
|
||||
def process_response(self, request, response):
|
||||
pass
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
|
||||
class HeaderDebugPanel(DebugPanel):
|
||||
"""
|
||||
A panel to display HTTP headers.
|
||||
"""
|
||||
name = 'Header'
|
||||
has_content = True
|
||||
# List of headers we want to display
|
||||
header_filter = (
|
||||
'CONTENT_TYPE',
|
||||
'HTTP_ACCEPT',
|
||||
'HTTP_ACCEPT_CHARSET',
|
||||
'HTTP_ACCEPT_ENCODING',
|
||||
'HTTP_ACCEPT_LANGUAGE',
|
||||
'HTTP_CACHE_CONTROL',
|
||||
'HTTP_CONNECTION',
|
||||
'HTTP_HOST',
|
||||
'HTTP_KEEP_ALIVE',
|
||||
'HTTP_REFERER',
|
||||
'HTTP_USER_AGENT',
|
||||
'QUERY_STRING',
|
||||
'REMOTE_ADDR',
|
||||
'REMOTE_HOST',
|
||||
'REQUEST_METHOD',
|
||||
'SCRIPT_NAME',
|
||||
'SERVER_NAME',
|
||||
'SERVER_PORT',
|
||||
'SERVER_PROTOCOL',
|
||||
'SERVER_SOFTWARE',
|
||||
)
|
||||
|
||||
def nav_title(self):
|
||||
return _('HTTP Headers')
|
||||
|
||||
def title(self):
|
||||
return _('HTTP Headers')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def process_request(self, request):
|
||||
self.headers = dict(
|
||||
[(k, request.environ[k])
|
||||
for k in self.header_filter if k in request.environ]
|
||||
)
|
||||
|
||||
def content(self):
|
||||
context = self.context.copy()
|
||||
context.update({
|
||||
'headers': self.headers
|
||||
})
|
||||
return self.render('panels/headers.html', context)
|
||||
@@ -1,106 +0,0 @@
|
||||
from __future__ import with_statement
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
try:
|
||||
import threading
|
||||
except ImportError:
|
||||
threading = None
|
||||
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
from flask_debugtoolbar.utils import format_fname
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class ThreadTrackingHandler(logging.Handler):
|
||||
def __init__(self):
|
||||
if threading is None:
|
||||
raise NotImplementedError("threading module is not available, \
|
||||
the logging panel cannot be used without it")
|
||||
logging.Handler.__init__(self)
|
||||
self.records = {} # a dictionary that maps threads to log records
|
||||
|
||||
def emit(self, record):
|
||||
self.get_records().append(record)
|
||||
|
||||
def get_records(self, thread=None):
|
||||
"""
|
||||
Returns a list of records for the provided thread, of if none is provided,
|
||||
returns a list for the current thread.
|
||||
"""
|
||||
if thread is None:
|
||||
thread = threading.currentThread()
|
||||
if thread not in self.records:
|
||||
self.records[thread] = []
|
||||
return self.records[thread]
|
||||
|
||||
def clear_records(self, thread=None):
|
||||
if thread is None:
|
||||
thread = threading.currentThread()
|
||||
if thread in self.records:
|
||||
del self.records[thread]
|
||||
|
||||
|
||||
handler = None
|
||||
_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def _init_once():
|
||||
# Initialize the logging handler once, but after werkzeug has set up its
|
||||
# default logger. Otherwise, if this sets up the logging first, werkzeug
|
||||
# will not create a default logger, so the development server's output will
|
||||
# not get printed.
|
||||
global handler
|
||||
if handler is not None:
|
||||
return
|
||||
with _init_lock:
|
||||
if handler is not None:
|
||||
return
|
||||
handler = ThreadTrackingHandler()
|
||||
logging.root.addHandler(handler)
|
||||
|
||||
|
||||
class LoggingPanel(DebugPanel):
|
||||
name = 'Logging'
|
||||
has_content = True
|
||||
|
||||
def process_request(self, request):
|
||||
_init_once()
|
||||
handler.clear_records()
|
||||
|
||||
def get_and_delete(self):
|
||||
records = handler.get_records()
|
||||
handler.clear_records()
|
||||
return records
|
||||
|
||||
def nav_title(self):
|
||||
return _("Logging")
|
||||
|
||||
def nav_subtitle(self):
|
||||
# FIXME l10n: use ngettext
|
||||
return "%s message%s" % (len(handler.get_records()), (len(handler.get_records()) == 1) and '' or 's')
|
||||
|
||||
def title(self):
|
||||
return _('Log Messages')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def content(self):
|
||||
records = []
|
||||
for record in self.get_and_delete():
|
||||
records.append({
|
||||
'message': record.getMessage(),
|
||||
'time': datetime.datetime.fromtimestamp(record.created),
|
||||
'level': record.levelname,
|
||||
'file': format_fname(record.pathname),
|
||||
'file_long': record.pathname,
|
||||
'line': record.lineno,
|
||||
})
|
||||
|
||||
context = self.context.copy()
|
||||
context.update({'records': records})
|
||||
|
||||
return self.render('panels/logger.html', context)
|
||||
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import sys
|
||||
try:
|
||||
import cProfile as profile
|
||||
except ImportError:
|
||||
import profile
|
||||
import functools
|
||||
import os.path
|
||||
import pstats
|
||||
|
||||
from flask import current_app
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
from flask_debugtoolbar.utils import format_fname
|
||||
|
||||
|
||||
class ProfilerDebugPanel(DebugPanel):
|
||||
"""
|
||||
Panel that displays the time a response took with cProfile output.
|
||||
"""
|
||||
name = 'Profiler'
|
||||
|
||||
user_activate = True
|
||||
|
||||
def has_content(self):
|
||||
return bool(self.profiler)
|
||||
|
||||
def process_request(self, request):
|
||||
if not self.is_active:
|
||||
return
|
||||
|
||||
self.profiler = profile.Profile()
|
||||
self.stats = None
|
||||
|
||||
def process_view(self, request, view_func, view_kwargs):
|
||||
if self.is_active:
|
||||
return functools.partial(self.profiler.runcall, view_func)
|
||||
|
||||
def process_response(self, request, response):
|
||||
if not self.is_active:
|
||||
return False
|
||||
|
||||
if self.profiler is not None:
|
||||
self.profiler.disable()
|
||||
try:
|
||||
stats = pstats.Stats(self.profiler)
|
||||
except TypeError:
|
||||
self.is_active = False
|
||||
return False
|
||||
function_calls = []
|
||||
for func in stats.sort_stats(1).fcn_list:
|
||||
current = {}
|
||||
info = stats.stats[func]
|
||||
|
||||
# Number of calls
|
||||
if info[0] != info[1]:
|
||||
current['ncalls'] = '%d/%d' % (info[1], info[0])
|
||||
else:
|
||||
current['ncalls'] = info[1]
|
||||
|
||||
# Total time
|
||||
current['tottime'] = info[2] * 1000
|
||||
|
||||
# Quotient of total time divided by number of calls
|
||||
if info[1]:
|
||||
current['percall'] = info[2] * 1000 / info[1]
|
||||
else:
|
||||
current['percall'] = 0
|
||||
|
||||
# Cumulative time
|
||||
current['cumtime'] = info[3] * 1000
|
||||
|
||||
# Quotient of the cumulative time divded by the number of
|
||||
# primitive calls.
|
||||
if info[0]:
|
||||
current['percall_cum'] = info[3] * 1000 / info[0]
|
||||
else:
|
||||
current['percall_cum'] = 0
|
||||
|
||||
# Filename
|
||||
filename = pstats.func_std_string(func)
|
||||
current['filename_long'] = filename
|
||||
current['filename'] = format_fname(filename)
|
||||
function_calls.append(current)
|
||||
|
||||
self.stats = stats
|
||||
self.function_calls = function_calls
|
||||
# destroy the profiler just in case
|
||||
return response
|
||||
|
||||
def title(self):
|
||||
if not self.is_active:
|
||||
return "Profiler not active"
|
||||
return 'View: %.2fms' % (float(self.stats.total_tt)*1000,)
|
||||
|
||||
def nav_title(self):
|
||||
return 'Profiler'
|
||||
|
||||
def nav_subtitle(self):
|
||||
if not self.is_active:
|
||||
return "in-active"
|
||||
return 'View: %.2fms' % (float(self.stats.total_tt)*1000,)
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def content(self):
|
||||
if not self.is_active:
|
||||
return "The profiler is not activated, activate it to use it"
|
||||
|
||||
context = {
|
||||
'stats': self.stats,
|
||||
'function_calls': self.function_calls,
|
||||
}
|
||||
return self.render('panels/profiler.html', context)
|
||||
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
from flask import session
|
||||
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class RequestVarsDebugPanel(DebugPanel):
|
||||
"""
|
||||
A panel to display request variables (POST/GET, session, cookies).
|
||||
"""
|
||||
name = 'RequestVars'
|
||||
has_content = True
|
||||
|
||||
def nav_title(self):
|
||||
return _('Request Vars')
|
||||
|
||||
def title(self):
|
||||
return _('Request Vars')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def process_request(self, request):
|
||||
self.request = request
|
||||
self.session = session
|
||||
self.view_func = None
|
||||
self.view_args = []
|
||||
self.view_kwargs = {}
|
||||
|
||||
def process_view(self, request, view_func, view_kwargs):
|
||||
self.view_func = view_func
|
||||
self.view_kwargs = view_kwargs
|
||||
|
||||
def content(self):
|
||||
context = self.context.copy()
|
||||
context.update({
|
||||
'get': [(k, self.request.args.getlist(k)) for k in self.request.args],
|
||||
'post': [(k, self.request.form.getlist(k)) for k in self.request.form],
|
||||
'cookies': [(k, self.request.cookies.get(k)) for k in self.request.cookies],
|
||||
'view_func': '%s.%s' % (self.view_func.__module__, self.view_func.__name__) if self.view_func else '[unknown]',
|
||||
'view_args': self.view_args,
|
||||
'view_kwargs': self.view_kwargs or {},
|
||||
'session': self.session.items(),
|
||||
})
|
||||
|
||||
return self.render('panels/request_vars.html', context)
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
import hashlib
|
||||
|
||||
try:
|
||||
from flaskext.sqlalchemy import get_debug_queries, SQLAlchemy
|
||||
except ImportError:
|
||||
sqlalchemy_available = False
|
||||
get_debug_queries = SQLAlchemy = None
|
||||
else:
|
||||
sqlalchemy_available = True
|
||||
|
||||
from flask import request, current_app, abort, json_available, g
|
||||
from flask.helpers import json
|
||||
from flask_debugtoolbar import module
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
from flask_debugtoolbar.utils import format_fname, format_sql
|
||||
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class SQLAlchemyDebugPanel(DebugPanel):
|
||||
"""
|
||||
Panel that displays the time a response took in milliseconds.
|
||||
"""
|
||||
name = 'SQLAlchemy'
|
||||
|
||||
|
||||
@property
|
||||
def has_content(self):
|
||||
if not json_available or not sqlalchemy_available:
|
||||
return True # will display an error message
|
||||
return bool(get_debug_queries())
|
||||
|
||||
def process_request(self, request):
|
||||
pass
|
||||
|
||||
def process_response(self, request, response):
|
||||
pass
|
||||
|
||||
def nav_title(self):
|
||||
return _('SQLAlchemy')
|
||||
|
||||
def nav_subtitle(self):
|
||||
if not json_available or not sqlalchemy_available:
|
||||
return 'Unavailable'
|
||||
|
||||
if get_debug_queries:
|
||||
count = len(get_debug_queries())
|
||||
return "%d %s" % (count, "query" if count == 1 else "queries")
|
||||
|
||||
def title(self):
|
||||
return _('SQLAlchemy queries')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def content(self):
|
||||
if not json_available or not sqlalchemy_available:
|
||||
msg = ['Missing required libraries:', '<ul>']
|
||||
if not json_available:
|
||||
msg.append('<li>simplejson</li>')
|
||||
if not sqlalchemy_available:
|
||||
msg.append('<li>Flask-SQLAlchemy</li>')
|
||||
msg.append('</ul>')
|
||||
return '\n'.join(msg)
|
||||
|
||||
queries = get_debug_queries()
|
||||
data = []
|
||||
for query in queries:
|
||||
is_select = query.statement.strip().lower().startswith('select')
|
||||
_params = ''
|
||||
try:
|
||||
_params = json.dumps(query.parameters)
|
||||
except TypeError:
|
||||
pass # object not JSON serializable
|
||||
|
||||
|
||||
hash = hashlib.sha1(
|
||||
current_app.config['SECRET_KEY'] +
|
||||
query.statement + _params).hexdigest()
|
||||
|
||||
data.append({
|
||||
'duration': query.duration,
|
||||
'sql': format_sql(query.statement, query.parameters),
|
||||
'raw_sql': query.statement,
|
||||
'hash': hash,
|
||||
'params': _params,
|
||||
'is_select': is_select,
|
||||
'context_long': query.context,
|
||||
'context': format_fname(query.context)
|
||||
})
|
||||
return self.render('panels/sqlalchemy.html', { 'queries': data})
|
||||
|
||||
# Panel views
|
||||
|
||||
@module.route('/sqlalchemy/sql_select', methods=['GET', 'POST'])
|
||||
def sql_select():
|
||||
return ''
|
||||
statement = request.args['sql']
|
||||
params = request.args['params']
|
||||
|
||||
# Validate hash
|
||||
hash = hashlib.sha1(
|
||||
current_app.config['SECRET_KEY'] + statement + params).hexdigest()
|
||||
if hash != request.args['hash']:
|
||||
return abort(406)
|
||||
|
||||
# Make sure it is a select statement
|
||||
if not statement.lower().strip().startswith('select'):
|
||||
return abort(406)
|
||||
|
||||
params = json.loads(params)
|
||||
|
||||
engine = SQLAlchemy().get_engine(current_app)
|
||||
|
||||
result = engine.execute(statement, params)
|
||||
return g.debug_toolbar.render('panels/sqlalchemy_select.html', {
|
||||
'result': result.fetchall(),
|
||||
'headers': result.keys(),
|
||||
'sql': format_sql(statement, params),
|
||||
'duration': float(request.args['duration']),
|
||||
})
|
||||
|
||||
@module.route('/sqlalchemy/sql_explain', methods=['GET', 'POST'])
|
||||
def sql_explain():
|
||||
statement = request.args['sql']
|
||||
params = request.args['params']
|
||||
|
||||
# Validate hash
|
||||
hash = hashlib.sha1(
|
||||
current_app.config['SECRET_KEY'] + statement + params).hexdigest()
|
||||
if hash != request.args['hash']:
|
||||
return abort(406)
|
||||
|
||||
# Make sure it is a select statement
|
||||
if not statement.lower().strip().startswith('select'):
|
||||
return abort(406)
|
||||
|
||||
params = json.loads(params)
|
||||
|
||||
engine = SQLAlchemy().get_engine(current_app)
|
||||
|
||||
if engine.driver == 'pysqlite':
|
||||
query = 'EXPLAIN QUERY PLAN %s' % statement
|
||||
else:
|
||||
query = 'EXPLAIN %s' % statement
|
||||
|
||||
result = engine.execute(query, params)
|
||||
return g.debug_toolbar.render('panels/sqlalchemy_explain.html', {
|
||||
'result': result.fetchall(),
|
||||
'headers': result.keys(),
|
||||
'sql': format_sql(statement, params),
|
||||
'duration': float(request.args['duration']),
|
||||
})
|
||||
@@ -1,44 +0,0 @@
|
||||
from flask import template_rendered
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class TemplateDebugPanel(DebugPanel):
|
||||
"""
|
||||
Panel that displays the time a response took in milliseconds.
|
||||
"""
|
||||
name = 'Template'
|
||||
has_content = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(self.__class__, self).__init__(*args, **kwargs)
|
||||
self.templates = []
|
||||
template_rendered.connect(self._store_template_info)
|
||||
|
||||
def _store_template_info(self, sender, **kwargs):
|
||||
self.templates.append(kwargs)
|
||||
|
||||
def process_request(self, request):
|
||||
pass
|
||||
|
||||
def process_response(self, request, response):
|
||||
pass
|
||||
|
||||
def nav_title(self):
|
||||
return _('Templates')
|
||||
|
||||
def nav_subtitle(self):
|
||||
return "%d rendered" % len(self.templates)
|
||||
|
||||
def title(self):
|
||||
return _('Templates')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def content(self):
|
||||
return self.render('panels/template.html', {
|
||||
'templates': self.templates
|
||||
})
|
||||
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
try:
|
||||
import resource
|
||||
except ImportError:
|
||||
pass # Will fail on Win32 systems
|
||||
import time
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class TimerDebugPanel(DebugPanel):
|
||||
"""
|
||||
Panel that displays the time a response took in milliseconds.
|
||||
"""
|
||||
name = 'Timer'
|
||||
try: # if resource module not available, don't show content panel
|
||||
resource
|
||||
except NameError:
|
||||
has_content = False
|
||||
has_resource = False
|
||||
else:
|
||||
has_content = True
|
||||
has_resource = True
|
||||
|
||||
def process_request(self, request):
|
||||
self._start_time = time.time()
|
||||
if self.has_resource:
|
||||
self._start_rusage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
|
||||
def process_response(self, request, response):
|
||||
self.total_time = (time.time() - self._start_time) * 1000
|
||||
if self.has_resource:
|
||||
self._end_rusage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
|
||||
def nav_title(self):
|
||||
return _('Time')
|
||||
|
||||
def nav_subtitle(self):
|
||||
# TODO l10n
|
||||
if self.has_resource:
|
||||
utime = self._end_rusage.ru_utime - self._start_rusage.ru_utime
|
||||
stime = self._end_rusage.ru_stime - self._start_rusage.ru_stime
|
||||
return 'CPU: %0.2fms (%0.2fms)' % ((utime + stime) * 1000.0, self.total_time)
|
||||
else:
|
||||
return 'TOTAL: %0.2fms' % (self.total_time)
|
||||
|
||||
def title(self):
|
||||
return _('Resource Usage')
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def _elapsed_ru(self, name):
|
||||
return getattr(self._end_rusage, name) - getattr(self._start_rusage, name)
|
||||
|
||||
def content(self):
|
||||
|
||||
utime = 1000 * self._elapsed_ru('ru_utime')
|
||||
stime = 1000 * self._elapsed_ru('ru_stime')
|
||||
vcsw = self._elapsed_ru('ru_nvcsw')
|
||||
ivcsw = self._elapsed_ru('ru_nivcsw')
|
||||
minflt = self._elapsed_ru('ru_minflt')
|
||||
majflt = self._elapsed_ru('ru_majflt')
|
||||
|
||||
# these are documented as not meaningful under Linux. If you're running BSD
|
||||
# feel free to enable them, and add any others that I hadn't gotten to before
|
||||
# I noticed that I was getting nothing but zeroes and that the docs agreed. :-(
|
||||
#
|
||||
# blkin = self._elapsed_ru('ru_inblock')
|
||||
# blkout = self._elapsed_ru('ru_oublock')
|
||||
# swap = self._elapsed_ru('ru_nswap')
|
||||
# rss = self._end_rusage.ru_maxrss
|
||||
# srss = self._end_rusage.ru_ixrss
|
||||
# urss = self._end_rusage.ru_idrss
|
||||
# usrss = self._end_rusage.ru_isrss
|
||||
|
||||
# TODO l10n on values
|
||||
rows = (
|
||||
(_('User CPU time'), '%0.3f msec' % utime),
|
||||
(_('System CPU time'), '%0.3f msec' % stime),
|
||||
(_('Total CPU time'), '%0.3f msec' % (utime + stime)),
|
||||
(_('Elapsed time'), '%0.3f msec' % self.total_time),
|
||||
(_('Context switches'), '%d voluntary, %d involuntary' % (vcsw, ivcsw)),
|
||||
# ('Memory use', '%d max RSS, %d shared, %d unshared' % (rss, srss, urss + usrss)),
|
||||
# ('Page faults', '%d no i/o, %d requiring i/o' % (minflt, majflt)),
|
||||
# ('Disk operations', '%d in, %d out, %d swapout' % (blkin, blkout, swap)),
|
||||
)
|
||||
|
||||
context = self.context.copy()
|
||||
context.update({
|
||||
'rows': rows,
|
||||
})
|
||||
|
||||
return self.render('panels/timer.html', context)
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
from flask import __version__ as flask_version
|
||||
from flask_debugtoolbar.panels import DebugPanel
|
||||
|
||||
_ = lambda x: x
|
||||
|
||||
class VersionDebugPanel(DebugPanel):
|
||||
"""
|
||||
Panel that displays the Flask version.
|
||||
"""
|
||||
name = 'Version'
|
||||
has_content = False
|
||||
|
||||
def nav_title(self):
|
||||
return _('Versions')
|
||||
|
||||
def nav_subtitle(self):
|
||||
return 'Flask %s' % flask_version
|
||||
|
||||
def url(self):
|
||||
return ''
|
||||
|
||||
def title(self):
|
||||
return _('Versions')
|
||||
|
||||
def content(self):
|
||||
return None
|
||||
|
||||
|
||||
@@ -1,418 +0,0 @@
|
||||
/* Debug Toolbar CSS Reset, adapted from Eric Meyer's CSS Reset */
|
||||
#flDebug {color:#000;background:#FFF;}
|
||||
#flDebug, #flDebug div, #flDebug span, #flDebug applet, #flDebug object, #flDebug iframe,
|
||||
#flDebug h1, #flDebug h2, #flDebug h3, #flDebug h4, #flDebug h5, #flDebug h6, #flDebug p, #flDebug blockquote, #flDebug pre,
|
||||
#flDebug a, #flDebug abbr, #flDebug acronym, #flDebug address, #flDebug big, #flDebug cite, #flDebug code,
|
||||
#flDebug del, #flDebug dfn, #flDebug em, #flDebug font, #flDebug img, #flDebug ins, #flDebug kbd, #flDebug q, #flDebug s, #flDebug samp,
|
||||
#flDebug small, #flDebug strike, #flDebug strong, #flDebug sub, #flDebug sup, #flDebug tt, #flDebug var,
|
||||
#flDebug b, #flDebug u, #flDebug i, #flDebug center,
|
||||
#flDebug dl, #flDebug dt, #flDebug dd, #flDebug ol, #flDebug ul, #flDebug li,
|
||||
#flDebug fieldset, #flDebug form, #flDebug label, #flDebug legend,
|
||||
#flDebug table, #flDebug caption, #flDebug tbody, #flDebug tfoot, #flDebug thead, #flDebug tr, #flDebug th, #flDebug td {
|
||||
margin:0;
|
||||
padding:0;
|
||||
border:0;
|
||||
outline:0;
|
||||
font-size:12px;
|
||||
line-height:1.5em;
|
||||
color:#000;
|
||||
vertical-align:baseline;
|
||||
background:transparent;
|
||||
font-family:sans-serif;
|
||||
text-align:left;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar {
|
||||
background:#111;
|
||||
width:200px;
|
||||
z-index:100000000;
|
||||
position:fixed;
|
||||
top:0;
|
||||
bottom:0;
|
||||
right:0;
|
||||
opacity:0.9;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar small {
|
||||
color:#999;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar ul {
|
||||
margin:0;
|
||||
padding:0;
|
||||
list-style:none;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li {
|
||||
border-bottom:1px solid #222;
|
||||
color:#fff;
|
||||
display:block;
|
||||
font-weight:bold;
|
||||
float:none;
|
||||
margin:0;
|
||||
padding:0;
|
||||
position:relative;
|
||||
width:auto;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li>a,
|
||||
#flDebug #flDebugToolbar li>div.contentless {
|
||||
font-weight:normal;
|
||||
font-style:normal;
|
||||
text-decoration:none;
|
||||
display:block;
|
||||
font-size:16px;
|
||||
padding:10px 10px 5px 25px;
|
||||
color:#fff;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li a:hover {
|
||||
color:#111;
|
||||
background-color:#ffc;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li.active {
|
||||
background-image:url(../img/indicator.png);
|
||||
background-repeat:no-repeat;
|
||||
background-position:left center;
|
||||
background-color:#333;
|
||||
padding-left:10px;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li.active a:hover {
|
||||
color:#b36a60;
|
||||
background-color:transparent;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li small {
|
||||
font-size:12px;
|
||||
color:#999;
|
||||
font-style:normal;
|
||||
text-decoration:none;
|
||||
font-variant:small-caps;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li .switch {
|
||||
font-size: 10px;
|
||||
position: absolute;
|
||||
display: block;
|
||||
color: white;
|
||||
height: 16px;
|
||||
width: 16px;
|
||||
cursor: pointer;
|
||||
top: 15px;
|
||||
right: 2px;
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li .switch.active {
|
||||
background-image: url(../img/tick.png);
|
||||
}
|
||||
|
||||
#flDebug #flDebugToolbar li .switch.inactive {
|
||||
background-image: url(../img/tick-red.png);
|
||||
}
|
||||
|
||||
|
||||
#flDebug #flDebugToolbarHandle {
|
||||
position:fixed;
|
||||
background:#fff;
|
||||
border:1px solid #111;
|
||||
top:30px;
|
||||
right:0;
|
||||
z-index:100000000;
|
||||
opacity:0.75;
|
||||
}
|
||||
|
||||
#flDebug a#flShowToolBarButton {
|
||||
display:block;
|
||||
height:75px;
|
||||
width:30px;
|
||||
border-right:none;
|
||||
border-bottom:4px solid #fff;
|
||||
border-top:4px solid #fff;
|
||||
border-left:4px solid #fff;
|
||||
color:#fff;
|
||||
font-size:10px;
|
||||
font-weight:bold;
|
||||
text-decoration:none;
|
||||
text-align:center;
|
||||
text-indent:-999999px;
|
||||
background:#000 url(../img/djdt_vertical.png) no-repeat left center;
|
||||
opacity:0.5;
|
||||
}
|
||||
|
||||
#flDebug a#flShowToolBarButton:hover {
|
||||
background-color:#111;
|
||||
padding-right:6px;
|
||||
border-top-color:#FFE761;
|
||||
border-left-color:#FFE761;
|
||||
border-bottom-color:#FFE761;
|
||||
opacity:1.0;
|
||||
}
|
||||
|
||||
#flDebug code {
|
||||
display:block;
|
||||
font-family:Consolas, Monaco, "Bitstream Vera Sans Mono", "Lucida Console", monospace;
|
||||
white-space:pre;
|
||||
overflow:auto;
|
||||
}
|
||||
|
||||
#flDebug tr.flDebugOdd {
|
||||
background-color:#f5f5f5;
|
||||
}
|
||||
|
||||
#flDebug .panelContent {
|
||||
display:none;
|
||||
position:fixed;
|
||||
margin:0;
|
||||
top:0;
|
||||
right:200px;
|
||||
bottom:0;
|
||||
left:0px;
|
||||
background-color:#eee;
|
||||
color:#666;
|
||||
z-index:100000000;
|
||||
}
|
||||
|
||||
#flDebug .panelContent > div {
|
||||
border-bottom:1px solid #ddd;
|
||||
}
|
||||
|
||||
#flDebug .flDebugPanelTitle {
|
||||
position:absolute;
|
||||
background-color:#ffc;
|
||||
color:#666;
|
||||
padding-left:20px;
|
||||
top:0;
|
||||
right:0;
|
||||
left:0;
|
||||
height:50px;
|
||||
}
|
||||
|
||||
#flDebug .flDebugPanelTitle code {
|
||||
display:inline;
|
||||
font-size:inherit;
|
||||
}
|
||||
|
||||
#flDebug .flDebugPanelContent {
|
||||
position:absolute;
|
||||
top:50px;
|
||||
right:0;
|
||||
bottom:0;
|
||||
left:0;
|
||||
height:auto;
|
||||
padding:0 0 0 20px;
|
||||
}
|
||||
|
||||
#flDebug .flDebugPanelContent .scroll {
|
||||
height:100%;
|
||||
overflow:auto;
|
||||
display:block;
|
||||
padding:0 10px 0 0;
|
||||
}
|
||||
|
||||
#flDebug h3 {
|
||||
font-size:24px;
|
||||
font-weight:normal;
|
||||
line-height:50px;
|
||||
}
|
||||
|
||||
#flDebug h4 {
|
||||
font-size:20px;
|
||||
font-weight:bold;
|
||||
margin-top:0.8em;
|
||||
}
|
||||
|
||||
#flDebug .panelContent table {
|
||||
border:1px solid #ccc;
|
||||
border-collapse:collapse;
|
||||
width:100%;
|
||||
background-color:#fff;
|
||||
display:block;
|
||||
margin-top:0.8em;
|
||||
overflow: auto;
|
||||
}
|
||||
#flDebug .panelContent tbody td,
|
||||
#flDebug .panelContent tbody th {
|
||||
vertical-align:top;
|
||||
padding:2px 3px;
|
||||
}
|
||||
#flDebug .panelContent thead th {
|
||||
padding:1px 6px 1px 3px;
|
||||
text-align:left;
|
||||
font-weight:bold;
|
||||
font-size:14px;
|
||||
}
|
||||
#flDebug .panelContent tbody th {
|
||||
width:12em;
|
||||
text-align:right;
|
||||
color:#666;
|
||||
padding-right:.5em;
|
||||
}
|
||||
|
||||
#flDebug .flTemplateHideContextDiv {
|
||||
background-color:#fff;
|
||||
}
|
||||
|
||||
/*
|
||||
#flDebug .panelContent p a:hover, #flDebug .panelContent dd a:hover {
|
||||
color:#111;
|
||||
background-color:#ffc;
|
||||
}
|
||||
|
||||
#flDebug .panelContent p {
|
||||
padding:0 5px;
|
||||
}
|
||||
|
||||
#flDebug .panelContent p, #flDebug .panelContent table, #flDebug .panelContent ol, #flDebug .panelContent ul, #flDebug .panelContent dl {
|
||||
margin:5px 0 15px;
|
||||
background-color:#fff;
|
||||
}
|
||||
#flDebug .panelContent table {
|
||||
clear:both;
|
||||
border:0;
|
||||
padding:0;
|
||||
margin:0;
|
||||
border-collapse:collapse;
|
||||
border-spacing:0;
|
||||
}
|
||||
|
||||
#flDebug .panelContent table a {
|
||||
color:#000;
|
||||
padding:2px 4px;
|
||||
}
|
||||
#flDebug .panelContent table a:hover {
|
||||
background-color:#ffc;
|
||||
}
|
||||
|
||||
#flDebug .panelContent table th {
|
||||
background-color:#333;
|
||||
font-weight:bold;
|
||||
color:#fff;
|
||||
padding:3px 7px 3px;
|
||||
text-align:left;
|
||||
cursor:pointer;
|
||||
}
|
||||
#flDebug .panelContent table td {
|
||||
padding:5px 10px;
|
||||
font-size:14px;
|
||||
background:#fff;
|
||||
color:#000;
|
||||
vertical-align:top;
|
||||
border:0;
|
||||
}
|
||||
#flDebug .panelContent table tr.flDebugOdd td {
|
||||
background:#eee;
|
||||
}
|
||||
*/
|
||||
|
||||
#flDebug .panelContent .flDebugClose {
|
||||
text-indent:-9999999px;
|
||||
display:block;
|
||||
position:absolute;
|
||||
top:4px;
|
||||
right:15px;
|
||||
height:40px;
|
||||
width:40px;
|
||||
background:url(../img/close.png) no-repeat center center;
|
||||
}
|
||||
|
||||
#flDebug .panelContent .flDebugClose:hover {
|
||||
background-image:url(../img/close_hover.png);
|
||||
}
|
||||
|
||||
#flDebug .panelContent .flDebugClose.flDebugBack {
|
||||
background-image:url(../img/back.png);
|
||||
}
|
||||
|
||||
#flDebug .panelContent .flDebugClose.flDebugBack:hover {
|
||||
background-image:url(../img/back_hover.png);
|
||||
}
|
||||
|
||||
#flDebug .panelContent dt, #flDebug .panelContent dd {
|
||||
display:block;
|
||||
}
|
||||
|
||||
#flDebug .panelContent dt {
|
||||
margin-top:0.75em;
|
||||
}
|
||||
|
||||
#flDebug .panelContent dd {
|
||||
margin-left:10px;
|
||||
}
|
||||
|
||||
#flDebug a.toggleTemplate {
|
||||
padding:4px;
|
||||
background-color:#bbb;
|
||||
-moz-border-radius:3px;
|
||||
-webkit-border-radius:3px;
|
||||
}
|
||||
|
||||
#flDebug a.toggleTemplate:hover {
|
||||
padding:4px;
|
||||
background-color:#444;
|
||||
color:#ffe761;
|
||||
-moz-border-radius:3px;
|
||||
-webkit-border-radius:3px;
|
||||
}
|
||||
|
||||
|
||||
#flDebug a.flTemplateShowContext, #flDebug a.flTemplateShowContext span.toggleArrow {
|
||||
color:#999;
|
||||
}
|
||||
|
||||
#flDebug a.flTemplateShowContext:hover, #flDebug a.flTemplateShowContext:hover span.toggleArrow {
|
||||
color:#000;
|
||||
cursor:pointer;
|
||||
}
|
||||
|
||||
#flDebug .flDebugSqlWrap {
|
||||
position:relative;
|
||||
}
|
||||
|
||||
#flDebug .flDebugSql {
|
||||
z-index:100000002;
|
||||
}
|
||||
|
||||
#flDebug .flSQLHideStacktraceDiv tbody th {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
#flDebug .flSqlExplain td {
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
#flDebug span.flDebugLineChart {
|
||||
background-color:#777;
|
||||
height:3px;
|
||||
position:absolute;
|
||||
bottom:0;
|
||||
top:0;
|
||||
left:0;
|
||||
display:block;
|
||||
z-index:1000000001;
|
||||
}
|
||||
#flDebug span.flDebugLineChartWarning {
|
||||
background-color:#900;
|
||||
}
|
||||
|
||||
#flDebug .highlight { color:#000; }
|
||||
#flDebug .highlight .err { color:#000; } /* Error */
|
||||
#flDebug .highlight .g { color:#000; } /* Generic */
|
||||
#flDebug .highlight .k { color:#000; font-weight:bold } /* Keyword */
|
||||
#flDebug .highlight .o { color:#000; } /* Operator */
|
||||
#flDebug .highlight .n { color:#000; } /* Name */
|
||||
#flDebug .highlight .mi { color:#000; font-weight:bold } /* Literal.Number.Integer */
|
||||
#flDebug .highlight .l { color:#000; } /* Literal */
|
||||
#flDebug .highlight .x { color:#000; } /* Other */
|
||||
#flDebug .highlight .p { color:#000; } /* Punctuation */
|
||||
#flDebug .highlight .m { color:#000; font-weight:bold } /* Literal.Number */
|
||||
#flDebug .highlight .s { color:#333 } /* Literal.String */
|
||||
#flDebug .highlight .w { color:#888888 } /* Text.Whitespace */
|
||||
#flDebug .highlight .il { color:#000; font-weight:bold } /* Literal.Number.Integer.Long */
|
||||
#flDebug .highlight .na { color:#333 } /* Name.Attribute */
|
||||
#flDebug .highlight .nt { color:#000; font-weight:bold } /* Name.Tag */
|
||||
#flDebug .highlight .nv { color:#333 } /* Name.Variable */
|
||||
#flDebug .highlight .s2 { color:#333 } /* Literal.String.Double */
|
||||
#flDebug .highlight .cp { color:#333 } /* Comment.Preproc */
|
||||
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 607 B |
|
Before Width: | Height: | Size: 110 B |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 634 B |
16
flask_debugtoolbar/static/js/jquery.js
vendored
@@ -1,184 +0,0 @@
|
||||
(function(window, document, version, callback) {
|
||||
var j, d;
|
||||
var loaded = false;
|
||||
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j)) {
|
||||
var script = document.createElement("script");
|
||||
script.type = "text/javascript";
|
||||
script.src = DEBUG_TOOLBAR_STATIC_PATH + "js/jquery.js";
|
||||
script.onload = script.onreadystatechange = function() {
|
||||
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
|
||||
callback((j = window.jQuery).noConflict(1), loaded = true);
|
||||
j(script).remove();
|
||||
}
|
||||
};
|
||||
document.documentElement.childNodes[0].appendChild(script)
|
||||
}
|
||||
})(window, document, "1.3", function($, jquery_loaded) {
|
||||
$.cookie = function(name, value, options) { if (typeof value != 'undefined') { options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); } var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = $.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
|
||||
$('head').append('<link rel="stylesheet" href="'+DEBUG_TOOLBAR_STATIC_PATH+'css/toolbar.css?'+ Math.random() +'" type="text/css" />');
|
||||
var COOKIE_NAME = 'fldt';
|
||||
var COOKIE_NAME_ACTIVE = COOKIE_NAME +'_active';
|
||||
var fldt = {
|
||||
init: function() {
|
||||
$('#flDebug').show();
|
||||
var current = null;
|
||||
$('#flDebugPanelList li a').click(function() {
|
||||
if (!this.className) {
|
||||
return false;
|
||||
}
|
||||
current = $('#flDebug #' + this.className + '-content');
|
||||
if (current.is(':visible')) {
|
||||
$(document).trigger('close.flDebug');
|
||||
$(this).parent().removeClass('active');
|
||||
} else {
|
||||
$('.panelContent').hide(); // Hide any that are already open
|
||||
current.show();
|
||||
$('#flDebugToolbar li').removeClass('active');
|
||||
$(this).parent().addClass('active');
|
||||
}
|
||||
return false;
|
||||
});
|
||||
$('#flDebugPanelList li .switch').click(function() {
|
||||
var $panel = $(this).parent();
|
||||
var $this = $(this);
|
||||
var dom_id = $panel.attr('id');
|
||||
|
||||
// Turn cookie content into an array of active panels
|
||||
var active_str = $.cookie(COOKIE_NAME_ACTIVE);
|
||||
var active = (active_str) ? active_str.split(';') : [];
|
||||
active = $.grep(active, function(n,i) { return n != dom_id; });
|
||||
|
||||
if ($this.hasClass('active')) {
|
||||
$this.removeClass('active');
|
||||
$this.addClass('inactive');
|
||||
}
|
||||
else {
|
||||
active.push(dom_id);
|
||||
$this.removeClass('inactive');
|
||||
$this.addClass('active');
|
||||
}
|
||||
|
||||
if (active.length > 0) {
|
||||
$.cookie(COOKIE_NAME_ACTIVE, active.join(';'), {
|
||||
path: '/', expires: 10
|
||||
});
|
||||
}
|
||||
else {
|
||||
$.cookie(COOKIE_NAME_ACTIVE, null, {
|
||||
path: '/', expires: -1
|
||||
});
|
||||
}
|
||||
});
|
||||
$('#flDebug a.flDebugClose').click(function() {
|
||||
$(document).trigger('close.flDebug');
|
||||
$('#flDebugToolbar li').removeClass('active');
|
||||
return false;
|
||||
});
|
||||
$('#flDebug a.remoteCall').click(function() {
|
||||
$('#flDebugWindow').load(this.href, {}, function() {
|
||||
$('#flDebugWindow a.flDebugBack').click(function() {
|
||||
$(this).parent().parent().hide();
|
||||
return false;
|
||||
});
|
||||
});
|
||||
$('#flDebugWindow').show();
|
||||
return false;
|
||||
});
|
||||
$('#flDebugTemplatePanel a.flTemplateShowContext').click(function() {
|
||||
fldt.toggle_arrow($(this).children('.toggleArrow'))
|
||||
fldt.toggle_content($(this).parent().next());
|
||||
return false;
|
||||
});
|
||||
$('#flDebugSQLPanel a.flSQLShowStacktrace').click(function() {
|
||||
fldt.toggle_content($('.flSQLHideStacktraceDiv', $(this).parents('tr')));
|
||||
return false;
|
||||
});
|
||||
$('#flHideToolBarButton').click(function() {
|
||||
fldt.hide_toolbar(true);
|
||||
return false;
|
||||
});
|
||||
$('#flShowToolBarButton').click(function() {
|
||||
fldt.show_toolbar();
|
||||
return false;
|
||||
});
|
||||
$(document).bind('close.flDebug', function() {
|
||||
// If a sub-panel is open, close that
|
||||
if ($('#flDebugWindow').is(':visible')) {
|
||||
$('#flDebugWindow').hide();
|
||||
return;
|
||||
}
|
||||
// If a panel is open, close that
|
||||
if ($('.panelContent').is(':visible')) {
|
||||
$('.panelContent').hide();
|
||||
return;
|
||||
}
|
||||
// Otherwise, just minimize the toolbar
|
||||
if ($('#flDebugToolbar').is(':visible')) {
|
||||
fldt.hide_toolbar(true);
|
||||
return;
|
||||
}
|
||||
});
|
||||
if ($.cookie(COOKIE_NAME)) {
|
||||
fldt.hide_toolbar(false);
|
||||
} else {
|
||||
fldt.show_toolbar(false);
|
||||
}
|
||||
},
|
||||
toggle_content: function(elem) {
|
||||
if (elem.is(':visible')) {
|
||||
elem.hide();
|
||||
} else {
|
||||
elem.show();
|
||||
}
|
||||
},
|
||||
close: function() {
|
||||
$(document).trigger('close.flDebug');
|
||||
return false;
|
||||
},
|
||||
hide_toolbar: function(setCookie) {
|
||||
// close any sub panels
|
||||
$('#flDebugWindow').hide();
|
||||
// close all panels
|
||||
$('.panelContent').hide();
|
||||
$('#flDebugToolbar li').removeClass('active');
|
||||
// finally close toolbar
|
||||
$('#flDebugToolbar').hide('fast');
|
||||
$('#flDebugToolbarHandle').show();
|
||||
// Unbind keydown
|
||||
$(document).unbind('keydown.flDebug');
|
||||
if (setCookie) {
|
||||
$.cookie(COOKIE_NAME, 'hide', {
|
||||
path: '/',
|
||||
expires: 10
|
||||
});
|
||||
}
|
||||
},
|
||||
show_toolbar: function(animate) {
|
||||
// Set up keybindings
|
||||
$(document).bind('keydown.flDebug', function(e) {
|
||||
if (e.keyCode == 27) {
|
||||
fldt.close();
|
||||
}
|
||||
});
|
||||
$('#flDebugToolbarHandle').hide();
|
||||
if (animate) {
|
||||
$('#flDebugToolbar').show('fast');
|
||||
} else {
|
||||
$('#flDebugToolbar').show();
|
||||
}
|
||||
$.cookie(COOKIE_NAME, null, {
|
||||
path: '/',
|
||||
expires: -1
|
||||
});
|
||||
},
|
||||
toggle_arrow: function(elem) {
|
||||
var uarr = String.fromCharCode(0x25b6);
|
||||
var darr = String.fromCharCode(0x25bc);
|
||||
elem.html(elem.html() == uarr ? darr : uarr);
|
||||
}
|
||||
};
|
||||
$(document).ready(function() {
|
||||
fldt.init();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
<div id="flDebug" style="display:none;">
|
||||
<script type="text/javascript">var DEBUG_TOOLBAR_STATIC_PATH = '{{ static_path }}'</script>
|
||||
<script type="text/javascript" src="{{ static_path }}js/toolbar.js"></script>
|
||||
|
||||
<div style="display: none;" id="flDebugToolbar">
|
||||
<ol id="flDebugPanelList">
|
||||
{% if panels %}
|
||||
<li><a id="flHideToolBarButton" href="#" title="Hide Toolbar">Hide »</a></li>
|
||||
{% else %}
|
||||
<li id="flDebugButton">DEBUG</li>
|
||||
{% endif %}
|
||||
{% for panel in panels %}
|
||||
<li id="{{ panel.dom_id() }}">
|
||||
{% if panel.has_content %}
|
||||
<a href="{{ panel.url()|default("#") }}" title="{{ panel.title() }}" class="{{ panel.dom_id() }}">
|
||||
{% else %}
|
||||
<div class="contentless">
|
||||
{% endif %}
|
||||
|
||||
{{ panel.nav_title() }}
|
||||
{% if panel.nav_subtitle() %}<br /><small>{{ panel.nav_subtitle() }}</small>{% endif %}
|
||||
|
||||
{% if panel.has_content %}
|
||||
</a>
|
||||
{% else %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if panel.user_activate %}
|
||||
<span class="switch {{ 'active' if panel.is_active else 'inactive' }}" title="Enable or disable the panel"></span>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ol>
|
||||
</div>
|
||||
<div style="display:none;" id="flDebugToolbarHandle">
|
||||
<a title="Show Toolbar" id="flShowToolBarButton" href="#">«</a>
|
||||
</div>
|
||||
{% for panel in panels %}
|
||||
{% if panel.has_content %}
|
||||
<div id="{{ panel.dom_id() }}-content" class="panelContent">
|
||||
<div class="flDebugPanelTitle">
|
||||
<a href="" class="flDebugClose">Close</a>
|
||||
<h3>{{ panel.title()|safe }}</h3>
|
||||
</div>
|
||||
<div class="flDebugPanelContent">
|
||||
<div class="scroll">
|
||||
{{ panel.content()|safe }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<div id="flDebugWindow" class="panelContent"></div>
|
||||
</div>
|
||||
@@ -1,16 +0,0 @@
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in headers.iteritems() %}
|
||||
<tr class="{{ loop.cycle('djDebugOdd' 'djDebugEven') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -1,26 +0,0 @@
|
||||
{% if records %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Level</th>
|
||||
<th>Time</th>
|
||||
<th>Message</th>
|
||||
<th>Location</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for record in records %}
|
||||
<tr class="{{ loop.cycle('fjDebugOdd' 'fjDebugEven') }}">
|
||||
<td>{{ record.level }}</td>
|
||||
<td>{{ record.time }}</td>
|
||||
<td>{{ record.message }}</td>
|
||||
<td title="{{ record.file_long }}:{{ record.line }}">{{ record.file }}:{{ record.line }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No messages logged.</p>
|
||||
{% endif %}
|
||||
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Calls</th>
|
||||
<th>Total Time (ms)</th>
|
||||
<th>Per Call (ms)</th>
|
||||
<th>Cumulative Time (ms)</th>
|
||||
<th>Per Call (ms)</th>
|
||||
<th>Function</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in function_calls %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd' 'flDebugEven') }}">
|
||||
<td>{{ row.ncalls }}</td>
|
||||
<td>{{ row.tottime }}</td>
|
||||
<td>{{ '%.4f'|format(row.percall) }}</td>
|
||||
<td>{{ row.cumtime }}</td>
|
||||
<td>{{ '%.4f'|format(row.percall_cum) }}</td>
|
||||
<td title="{{ row.filename_long }}">{{ row.filename|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
|
||||
<h4>View information</h4>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>View Function</th>
|
||||
<th>args</th>
|
||||
<th>kwargs</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>{{ view_func }}</td>
|
||||
<td>{{ view_args|default("None") }}</td>
|
||||
<td>
|
||||
{% if view_kwargs.items() %}
|
||||
{% for k, v in view_kwargs.items() %}
|
||||
{{ k }}={{ v }}{% if not loop.last %}, {% endif %}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
None
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h4>COOKIES Variables</h4>
|
||||
{% if cookies %}
|
||||
<table>
|
||||
<colgroup>
|
||||
<col style="width:20%"/>
|
||||
<col/>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Variable</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in cookies %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd' 'flDebugEven') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No COOKIE data</p>
|
||||
{% endif %}
|
||||
|
||||
<h4>SESSION Variables</h4>
|
||||
{% if session %}
|
||||
<table>
|
||||
<colgroup>
|
||||
<col style="width:20%"/>
|
||||
<col/>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Variable</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in session %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd' 'flDebugEven') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No SESSION data</p>
|
||||
{% endif %}
|
||||
|
||||
<h4>GET Variables</h4>
|
||||
{% if get %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Variable</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in get %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd' 'flDebugEven') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|join(", ")|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No GET data</p>
|
||||
{% endif %}
|
||||
|
||||
<h4>POST Variables</h4>
|
||||
{% if post %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Variable</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in post %}
|
||||
<tr class="{{ loop.cycle('row1' 'row2') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|join(", ")|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No POST data</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th> (ms)</th>
|
||||
<th>Action</th>
|
||||
<th>Context</th>
|
||||
<th>Query</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for query in queries %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd' 'flDebugEven') }}">
|
||||
<td>{{ '%.4f'|format(query.duration) }}</td>
|
||||
<td>
|
||||
{% if query.params %}
|
||||
{% if query.is_select %}
|
||||
<a class="remoteCall" href="/_debug_toolbar/views/sqlalchemy/sql_select?sql={{ query.raw_sql|urlencode }}&params={{ query.params|urlencode }}&duration={{ query.duration|urlencode }}&hash={{ query.hash }}">SELECT</a><br />
|
||||
<a class="remoteCall" href="/_debug_toolbar/views/sqlalchemy/sql_explain?sql={{ query.raw_sql|urlencode }}&params={{ query.params|urlencode }}&duration={{ query.duration|urlencode }}&hash={{ query.hash }}">EXPLAIN</a><br />
|
||||
{% if is_mysql %}
|
||||
<a class="remoteCall" href="/__debug__/sql_profile/?sql={{ query.raw_sql|urlencode }}&params={{ query.params|urlencode }}&duration={{ query.duration|urlencode }}&hash={{ query.hash }}">PROFILE</a><br />
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</td>
|
||||
<td title="{{ query.context_long }}">
|
||||
{{ query.context }}
|
||||
</td>
|
||||
<td class="syntax">
|
||||
<div class="djDebugSqlWrap">
|
||||
<div class="flDebugSql">{{ query.sql|safe }}</div>
|
||||
{#
|
||||
{% if query.stacktrace %}
|
||||
<div class="djSQLHideStacktraceDiv" style="display:none;">
|
||||
<table>
|
||||
<tr>
|
||||
<th>{% trans "Line" %}</th>
|
||||
<th>{% trans "Method" %}</th>
|
||||
<th>{% trans "File" %}</th>
|
||||
</tr>
|
||||
{% for file, line, method in query.stacktrace %}
|
||||
<tr>
|
||||
<td>{{ line }}</td>
|
||||
<td><code>{{ method|escape }}</code></td>
|
||||
<td><code>{{ file|escape }}</code></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% if query.template_info %}
|
||||
<table>
|
||||
{% for line in query.template_info.context %}
|
||||
<tr>
|
||||
<td>{{ line.num }}</td>
|
||||
<td><code style="font-family: monospace;{% if line.highlight %}background-color: lightgrey{% endif %}">{{ line.content }}</code></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
<p><strong>{{ query.template_info.name|default:"(unknown)" }}</strong></p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<span class="djDebugLineChart{% if query.is_slow %} djDebugLineChartWarning{% endif %}" style="width:{{ query.width_ratio }}%; left:{{ query.start_offset }}%;"></span>
|
||||
#}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -1,33 +0,0 @@
|
||||
<div class="flDebugPanelTitle">
|
||||
<a class="flDebugClose flDebugBack" href="">Back</a>
|
||||
<h3>SQL Explained</h3>
|
||||
</div>
|
||||
<div class="flDebugPanelContent">
|
||||
<div class="scroll">
|
||||
<dl>
|
||||
<dt>Executed SQL</dt>
|
||||
<dd>{{ sql|safe }}</dd>
|
||||
<dt>Time</dt>
|
||||
<dd>{{ '%.4f'|format(duration) }} ms</dd>
|
||||
</dl>
|
||||
<table class="djSqlExplain">
|
||||
<thead>
|
||||
<tr>
|
||||
{% for h in headers %}
|
||||
<th>{{ h|upper }}</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in result %}
|
||||
<tr class="{{ loop.cycle('fjDebugOdd' 'fjDebugEven') }}">
|
||||
{% for column in row %}
|
||||
<td>{{ column }}</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
<div class="flDebugPanelTitle">
|
||||
<a class="flDebugClose flDebugBack" href="">Back</a>
|
||||
<h3>SQL Explained</h3>
|
||||
</div>
|
||||
<div class="flDebugPanelContent">
|
||||
<div class="scroll">
|
||||
<dl>
|
||||
<dt>Executed SQL</dt>
|
||||
<dd>{{ sql|safe }}</dd>
|
||||
<dt>Time</dt>
|
||||
<dd>{{ '%.4f'|format(duration) }} ms</dd>
|
||||
</dl>
|
||||
{% if result %}
|
||||
<table class="flSqlSelect">
|
||||
<thead>
|
||||
<tr>
|
||||
{% for h in headers %}
|
||||
<th>{{ h|upper }}</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in result %}
|
||||
<tr class="{{ loop.cycle('fjDebugOdd' 'fjDebugEven') }}">
|
||||
{% for column in row %}
|
||||
<td>{{ column }}</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>Empty set</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
{% if templates %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Filename</th>
|
||||
<th>Context vars</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for template in templates %}
|
||||
<tr class="{{ loop.cycle('fjDebugOdd' 'fjDebugEven') }}">
|
||||
<td>{{ template.template.name }}</td>
|
||||
<td>{{ template.context.keys()|join(', ') }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No templates rendered.</p>
|
||||
{% endif %}
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
<table>
|
||||
<colgroup>
|
||||
<col style="width:20%"/>
|
||||
<col/>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Resource</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, value in rows %}
|
||||
<tr class="{{ loop.cycle('flDebugOdd', 'flDebugEven') }}">
|
||||
<td>{{ key|escape }}</td>
|
||||
<td>{{ value|escape }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Redirect intercepted</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Redirect ({{ redirect_code }})</h1>
|
||||
<p>Location: <a href="{{ redirect_to }}">{{ redirect_to }}</a></p>
|
||||
<p class="notice">
|
||||
The Flask Debug Toolbar has intercepted a redirect to the above URL for
|
||||
debug viewing purposes. You can click the above link to continue with the
|
||||
redirect as normal. If you'd like to disable this feature, you can set the
|
||||
config variable <code>DEBUG_TB_INTERCEPT_REDIRECTS</code> to <code>False</code>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,73 +0,0 @@
|
||||
from flask import url_for, current_app
|
||||
|
||||
|
||||
|
||||
class DebugToolbar(object):
|
||||
|
||||
# default config settings
|
||||
config = {
|
||||
'DEBUG_TB_INTERCEPT_REDIRECTS': True,
|
||||
'DEBUG_TB_PANELS': (
|
||||
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
|
||||
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
|
||||
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
|
||||
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
|
||||
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
|
||||
'flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel',
|
||||
'flask_debugtoolbar.panels.logger.LoggingPanel',
|
||||
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
|
||||
)
|
||||
}
|
||||
|
||||
panel_classes = []
|
||||
|
||||
def __init__(self, request, jinja_env):
|
||||
self.jinja_env = jinja_env
|
||||
self.request = request
|
||||
self.panels = []
|
||||
|
||||
self.template_context = {
|
||||
'static_path': url_for('_debug_toolbar.static', filename='')
|
||||
}
|
||||
|
||||
self.create_panels()
|
||||
|
||||
@classmethod
|
||||
def load_panels(cls, app):
|
||||
cls.config.update(app.config)
|
||||
|
||||
for panel_path in cls.config['DEBUG_TB_PANELS']:
|
||||
dot = panel_path.rindex('.')
|
||||
panel_module, panel_classname = panel_path[:dot], panel_path[dot+1:]
|
||||
|
||||
try:
|
||||
mod = __import__(panel_module, {}, {}, [''])
|
||||
except ImportError, e:
|
||||
app.logger.warning('Disabled %s due to ImportError: %s', panel_classname, e)
|
||||
continue
|
||||
panel_class = getattr(mod, panel_classname)
|
||||
cls.panel_classes.append(panel_class)
|
||||
|
||||
def create_panels(self):
|
||||
"""
|
||||
Populate debug panels
|
||||
"""
|
||||
activated = self.request.cookies.get('fldt_active', '').split(';')
|
||||
|
||||
for panel_class in self.panel_classes:
|
||||
panel_instance = panel_class(
|
||||
context=self.template_context,
|
||||
jinja_env=self.jinja_env)
|
||||
|
||||
if panel_instance.dom_id() in activated:
|
||||
panel_instance.is_active = True
|
||||
self.panels.append(panel_instance)
|
||||
|
||||
def render_toolbar(self):
|
||||
context = self.template_context.copy()
|
||||
context.update({'panels': self.panels})
|
||||
|
||||
template = self.jinja_env.get_template('base.html')
|
||||
return template.render(**context)
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import os.path
|
||||
import sys
|
||||
|
||||
try:
|
||||
from pygments import highlight
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.lexers import SqlLexer
|
||||
from pygments.styles import get_style_by_name
|
||||
PYGMENT_STYLE = get_style_by_name('colorful')
|
||||
HAVE_PYGMENTS = True
|
||||
except ImportError:
|
||||
HAVE_PYGMENTS = False
|
||||
|
||||
|
||||
from flask import current_app
|
||||
|
||||
def format_fname(value):
|
||||
# If the value is not an absolute path, the it is a builtin or
|
||||
# a relative file (thus a project file).
|
||||
if not os.path.isabs(value):
|
||||
if value.startswith(('{', '<')):
|
||||
return value
|
||||
if value.startswith('.' + os.path.sep):
|
||||
return value
|
||||
return '.' + os.path.sep + value
|
||||
|
||||
# If the file is absolute and within the project root handle it as
|
||||
# a project file
|
||||
if value.startswith(current_app.root_path):
|
||||
return "." + value[len(current_app.root_path):]
|
||||
|
||||
# Loop through sys.path to find the longest match and return
|
||||
# the relative path from there.
|
||||
paths = sys.path
|
||||
prefix = None
|
||||
prefix_len = 0
|
||||
for path in sys.path:
|
||||
new_prefix = os.path.commonprefix([path, value])
|
||||
if len(new_prefix) > prefix_len:
|
||||
prefix = new_prefix
|
||||
prefix_len = len(prefix)
|
||||
|
||||
if not prefix.endswith(os.path.sep):
|
||||
prefix_len -= 1
|
||||
path = value[prefix_len:]
|
||||
return '<%s>' % path
|
||||
|
||||
def format_sql(query, args):
|
||||
if not HAVE_PYGMENTS:
|
||||
return query
|
||||
|
||||
return highlight(
|
||||
query,
|
||||
SqlLexer(encoding='utf-8'),
|
||||
HtmlFormatter(encoding='utf-8', noclasses=True, style=PYGMENT_STYLE))
|
||||
|
||||
84
pyproject.toml
Normal file
@@ -0,0 +1,84 @@
|
||||
[project]
|
||||
name = "Flask-DebugToolbar"
|
||||
version = "0.16.0"
|
||||
description = "A toolbar overlay for debugging Flask applications."
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE.txt" }
|
||||
author = [{ name = "Michael van Tellingen" }]
|
||||
maintainers = [{ name = "Pallets Ecosystem", email = "contact@palletsprojects.com" }]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Framework :: Flask",
|
||||
"License :: OSI Approved :: BSD License",
|
||||
"Programming Language :: Python",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
requires-python = ">=3.8"
|
||||
dependencies = [
|
||||
"flask>=2.3.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Documentation = "https://flask-debugtoolbar.readthedocs.io"
|
||||
Changes = "https://github.com/pallets-eco/flask-debugtoolbar/releases/"
|
||||
Source = "https://github.com/pallets-eco/flask-debugtoolbar/"
|
||||
Chat = "https://discord.gg/pallets"
|
||||
|
||||
[build-system]
|
||||
requires = ["flit_core<4"]
|
||||
build-backend = "flit_core.buildapi"
|
||||
|
||||
[tool.flit.module]
|
||||
name = "flask_debugtoolbar"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
branch = true
|
||||
source = ["flask_debugtoolbar", "tests"]
|
||||
|
||||
[tool.coverage.paths]
|
||||
source = ["src", "*/site-packages"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.8"
|
||||
files = ["src/flask_debugtoolbar", "tests"]
|
||||
show_error_codes = true
|
||||
pretty = true
|
||||
strict = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = [
|
||||
"sqlparse.*"
|
||||
]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.pyright]
|
||||
pythonVersion = "3.8"
|
||||
include = ["src/flask_debugtoolbar", "tests"]
|
||||
typeCheckingMode = "basic"
|
||||
|
||||
[tool.ruff]
|
||||
src = ["src"]
|
||||
fix = true
|
||||
show-fixes = true
|
||||
output-format = "full"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = [
|
||||
"B", # flake8-bugbear
|
||||
"E", # pycodestyle error
|
||||
"F", # pyflakes
|
||||
"I", # isort
|
||||
"UP", # pyupgrade
|
||||
"W", # pycodestyle warning
|
||||
]
|
||||
ignore-init-module-imports = true
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
force-single-line = true
|
||||
order-by-type = false
|
||||
1
requirements/build.in
Normal file
@@ -0,0 +1 @@
|
||||
build
|
||||
18
requirements/build.txt
Normal file
@@ -0,0 +1,18 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.8
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile build.in
|
||||
#
|
||||
build==1.2.2.post1
|
||||
# via -r build.in
|
||||
importlib-metadata==7.1.0
|
||||
# via build
|
||||
packaging==24.0
|
||||
# via build
|
||||
pyproject-hooks==1.1.0
|
||||
# via build
|
||||
tomli==2.0.1
|
||||
# via build
|
||||
zipp==3.19.1
|
||||
# via importlib-metadata
|
||||
5
requirements/dev.in
Normal file
@@ -0,0 +1,5 @@
|
||||
-r docs.txt
|
||||
-r tests.txt
|
||||
-r typing.txt
|
||||
pre-commit
|
||||
tox
|
||||
262
requirements/dev.txt
Normal file
@@ -0,0 +1,262 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.8
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile dev.in
|
||||
#
|
||||
alabaster==0.7.13
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
babel==2.14.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
blinker==1.8.1
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
cachetools==5.3.3
|
||||
# via tox
|
||||
certifi==2024.7.4
|
||||
# via
|
||||
# -r docs.txt
|
||||
# requests
|
||||
cfgv==3.4.0
|
||||
# via pre-commit
|
||||
chardet==5.2.0
|
||||
# via tox
|
||||
charset-normalizer==3.3.2
|
||||
# via
|
||||
# -r docs.txt
|
||||
# requests
|
||||
click==8.1.7
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
colorama==0.4.6
|
||||
# via tox
|
||||
distlib==0.3.8
|
||||
# via virtualenv
|
||||
docutils==0.20.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
exceptiongroup==1.2.1
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# pytest
|
||||
filelock==3.14.0
|
||||
# via
|
||||
# tox
|
||||
# virtualenv
|
||||
flask==3.0.3
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask-sqlalchemy
|
||||
flask-sqlalchemy==3.1.1
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
greenlet==3.0.3
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# sqlalchemy
|
||||
identify==2.5.36
|
||||
# via pre-commit
|
||||
idna==3.7
|
||||
# via
|
||||
# -r docs.txt
|
||||
# requests
|
||||
imagesize==1.4.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
importlib-metadata==7.1.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
# sphinx
|
||||
iniconfig==2.0.0
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# pytest
|
||||
itsdangerous==2.2.0
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
jinja2==3.1.4
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
# sphinx
|
||||
markupsafe==2.1.5
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# jinja2
|
||||
# werkzeug
|
||||
mypy==1.13.0
|
||||
# via -r typing.txt
|
||||
mypy-extensions==1.0.0
|
||||
# via
|
||||
# -r typing.txt
|
||||
# mypy
|
||||
nodeenv==1.8.0
|
||||
# via
|
||||
# -r typing.txt
|
||||
# pre-commit
|
||||
# pyright
|
||||
packaging==24.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# pallets-sphinx-themes
|
||||
# pyproject-api
|
||||
# pytest
|
||||
# sphinx
|
||||
# tox
|
||||
pallets-sphinx-themes==2.3.0
|
||||
# via -r docs.txt
|
||||
platformdirs==4.2.1
|
||||
# via
|
||||
# tox
|
||||
# virtualenv
|
||||
pluggy==1.5.0
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# pytest
|
||||
# tox
|
||||
pre-commit==3.5.0
|
||||
# via -r dev.in
|
||||
pygments==2.18.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# sphinx
|
||||
pyproject-api==1.6.1
|
||||
# via tox
|
||||
pyright==1.1.389
|
||||
# via -r typing.txt
|
||||
pytest==8.3.3
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
pytz==2024.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# babel
|
||||
pyyaml==6.0.1
|
||||
# via pre-commit
|
||||
requests==2.32.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
snowballstemmer==2.2.0
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinx==7.1.2
|
||||
# via
|
||||
# -r docs.txt
|
||||
# pallets-sphinx-themes
|
||||
# sphinx-notfound-page
|
||||
# sphinxcontrib-log-cabinet
|
||||
sphinx-notfound-page==1.0.4
|
||||
# via
|
||||
# -r docs.txt
|
||||
# pallets-sphinx-themes
|
||||
sphinxcontrib-applehelp==1.0.4
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinxcontrib-devhelp==1.0.2
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinxcontrib-htmlhelp==2.0.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinxcontrib-jsmath==1.0.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinxcontrib-log-cabinet==1.0.1
|
||||
# via -r docs.txt
|
||||
sphinxcontrib-qthelp==1.0.3
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sphinxcontrib-serializinghtml==1.1.5
|
||||
# via
|
||||
# -r docs.txt
|
||||
# sphinx
|
||||
sqlalchemy==2.0.29
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask-sqlalchemy
|
||||
tomli==2.0.1
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# mypy
|
||||
# pyproject-api
|
||||
# pytest
|
||||
# tox
|
||||
tox==4.15.1
|
||||
# via -r dev.in
|
||||
types-docutils==0.21.0.20240423
|
||||
# via
|
||||
# -r typing.txt
|
||||
# types-pygments
|
||||
types-pygments==2.18.0.20240506
|
||||
# via -r typing.txt
|
||||
types-setuptools==69.5.0.20240423
|
||||
# via
|
||||
# -r typing.txt
|
||||
# types-pygments
|
||||
typing-extensions==4.11.0
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# mypy
|
||||
# pyright
|
||||
# sqlalchemy
|
||||
urllib3==2.2.2
|
||||
# via
|
||||
# -r docs.txt
|
||||
# requests
|
||||
virtualenv==20.26.1
|
||||
# via
|
||||
# pre-commit
|
||||
# tox
|
||||
werkzeug==3.0.3
|
||||
# via
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# flask
|
||||
zipp==3.19.1
|
||||
# via
|
||||
# -r docs.txt
|
||||
# -r tests.txt
|
||||
# -r typing.txt
|
||||
# importlib-metadata
|
||||
|
||||
# The following packages are considered to be unsafe in a requirements file:
|
||||
# setuptools
|
||||
3
requirements/docs.in
Normal file
@@ -0,0 +1,3 @@
|
||||
pallets-sphinx-themes
|
||||
sphinx
|
||||
sphinxcontrib-log-cabinet
|
||||
66
requirements/docs.txt
Normal file
@@ -0,0 +1,66 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.8
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile docs.in
|
||||
#
|
||||
alabaster==0.7.13
|
||||
# via sphinx
|
||||
babel==2.14.0
|
||||
# via sphinx
|
||||
certifi==2024.7.4
|
||||
# via requests
|
||||
charset-normalizer==3.3.2
|
||||
# via requests
|
||||
docutils==0.20.1
|
||||
# via sphinx
|
||||
idna==3.7
|
||||
# via requests
|
||||
imagesize==1.4.1
|
||||
# via sphinx
|
||||
importlib-metadata==7.1.0
|
||||
# via sphinx
|
||||
jinja2==3.1.4
|
||||
# via sphinx
|
||||
markupsafe==2.1.5
|
||||
# via jinja2
|
||||
packaging==24.0
|
||||
# via
|
||||
# pallets-sphinx-themes
|
||||
# sphinx
|
||||
pallets-sphinx-themes==2.3.0
|
||||
# via -r docs.in
|
||||
pygments==2.18.0
|
||||
# via sphinx
|
||||
pytz==2024.1
|
||||
# via babel
|
||||
requests==2.32.0
|
||||
# via sphinx
|
||||
snowballstemmer==2.2.0
|
||||
# via sphinx
|
||||
sphinx==7.1.2
|
||||
# via
|
||||
# -r docs.in
|
||||
# pallets-sphinx-themes
|
||||
# sphinx-notfound-page
|
||||
# sphinxcontrib-log-cabinet
|
||||
sphinx-notfound-page==1.0.4
|
||||
# via pallets-sphinx-themes
|
||||
sphinxcontrib-applehelp==1.0.4
|
||||
# via sphinx
|
||||
sphinxcontrib-devhelp==1.0.2
|
||||
# via sphinx
|
||||
sphinxcontrib-htmlhelp==2.0.1
|
||||
# via sphinx
|
||||
sphinxcontrib-jsmath==1.0.1
|
||||
# via sphinx
|
||||
sphinxcontrib-log-cabinet==1.0.1
|
||||
# via -r docs.in
|
||||
sphinxcontrib-qthelp==1.0.3
|
||||
# via sphinx
|
||||
sphinxcontrib-serializinghtml==1.1.5
|
||||
# via sphinx
|
||||
urllib3==2.2.2
|
||||
# via requests
|
||||
zipp==3.19.1
|
||||
# via importlib-metadata
|
||||
3
requirements/tests.in
Normal file
@@ -0,0 +1,3 @@
|
||||
pytest
|
||||
flask-sqlalchemy
|
||||
pygments
|
||||
48
requirements/tests.txt
Normal file
@@ -0,0 +1,48 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.8
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile tests.in
|
||||
#
|
||||
blinker==1.8.1
|
||||
# via flask
|
||||
click==8.1.7
|
||||
# via flask
|
||||
exceptiongroup==1.2.1
|
||||
# via pytest
|
||||
flask==3.0.3
|
||||
# via flask-sqlalchemy
|
||||
flask-sqlalchemy==3.1.1
|
||||
# via -r tests.in
|
||||
greenlet==3.0.3
|
||||
# via sqlalchemy
|
||||
importlib-metadata==7.1.0
|
||||
# via flask
|
||||
iniconfig==2.0.0
|
||||
# via pytest
|
||||
itsdangerous==2.2.0
|
||||
# via flask
|
||||
jinja2==3.1.4
|
||||
# via flask
|
||||
markupsafe==2.1.5
|
||||
# via
|
||||
# jinja2
|
||||
# werkzeug
|
||||
packaging==24.0
|
||||
# via pytest
|
||||
pluggy==1.5.0
|
||||
# via pytest
|
||||
pygments==2.18.0
|
||||
# via -r tests.in
|
||||
pytest==8.3.3
|
||||
# via -r tests.in
|
||||
sqlalchemy==2.0.29
|
||||
# via flask-sqlalchemy
|
||||
tomli==2.0.1
|
||||
# via pytest
|
||||
typing-extensions==4.11.0
|
||||
# via sqlalchemy
|
||||
werkzeug==3.0.3
|
||||
# via flask
|
||||
zipp==3.19.1
|
||||
# via importlib-metadata
|
||||
5
requirements/typing.in
Normal file
@@ -0,0 +1,5 @@
|
||||
mypy
|
||||
pyright
|
||||
pytest
|
||||
types-pygments
|
||||
flask-sqlalchemy
|
||||
68
requirements/typing.txt
Normal file
@@ -0,0 +1,68 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.8
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile typing.in
|
||||
#
|
||||
blinker==1.8.1
|
||||
# via flask
|
||||
click==8.1.7
|
||||
# via flask
|
||||
exceptiongroup==1.2.1
|
||||
# via pytest
|
||||
flask==3.0.3
|
||||
# via flask-sqlalchemy
|
||||
flask-sqlalchemy==3.1.1
|
||||
# via -r typing.in
|
||||
greenlet==3.0.3
|
||||
# via sqlalchemy
|
||||
importlib-metadata==7.1.0
|
||||
# via flask
|
||||
iniconfig==2.0.0
|
||||
# via pytest
|
||||
itsdangerous==2.2.0
|
||||
# via flask
|
||||
jinja2==3.1.4
|
||||
# via flask
|
||||
markupsafe==2.1.5
|
||||
# via
|
||||
# jinja2
|
||||
# werkzeug
|
||||
mypy==1.13.0
|
||||
# via -r typing.in
|
||||
mypy-extensions==1.0.0
|
||||
# via mypy
|
||||
nodeenv==1.8.0
|
||||
# via pyright
|
||||
packaging==24.0
|
||||
# via pytest
|
||||
pluggy==1.5.0
|
||||
# via pytest
|
||||
pyright==1.1.389
|
||||
# via -r typing.in
|
||||
pytest==8.3.3
|
||||
# via -r typing.in
|
||||
sqlalchemy==2.0.29
|
||||
# via flask-sqlalchemy
|
||||
tomli==2.0.1
|
||||
# via
|
||||
# mypy
|
||||
# pytest
|
||||
types-docutils==0.21.0.20240423
|
||||
# via types-pygments
|
||||
types-pygments==2.18.0.20240506
|
||||
# via -r typing.in
|
||||
types-setuptools==69.5.0.20240423
|
||||
# via types-pygments
|
||||
typing-extensions==4.11.0
|
||||
# via
|
||||
# mypy
|
||||
# pyright
|
||||
# sqlalchemy
|
||||
werkzeug==3.0.3
|
||||
# via flask
|
||||
zipp==3.19.1
|
||||
# via importlib-metadata
|
||||
|
||||
# The following packages are considered to be unsafe in a requirements file:
|
||||
# setuptools
|
||||
36
setup.py
@@ -1,36 +0,0 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
setup(
|
||||
name='Flask-DebugToolbar',
|
||||
version='0.6',
|
||||
url='http://github.com/mgood/flask-debugtoolbar',
|
||||
license='BSD',
|
||||
author='Michael van Tellingen',
|
||||
author_email='michaelvantellingen@gmail.com',
|
||||
maintainer='Matt Good',
|
||||
maintainer_email='matt@matt-good.net',
|
||||
description='A port of the Django debug toolbar to Flask',
|
||||
long_description=__doc__,
|
||||
zip_safe=False,
|
||||
platforms='any',
|
||||
include_package_data=True,
|
||||
packages=['flask_debugtoolbar',
|
||||
'flask_debugtoolbar.panels'
|
||||
],
|
||||
install_requires=[
|
||||
'setuptools',
|
||||
'Flask>=0.8',
|
||||
'Blinker',
|
||||
],
|
||||
classifiers=[
|
||||
'Development Status :: 4 - Beta',
|
||||
'Environment :: Web Environment',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python',
|
||||
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
|
||||
'Topic :: Software Development :: Libraries :: Python Modules'
|
||||
]
|
||||
)
|
||||
359
src/flask_debugtoolbar/__init__.py
Normal file
@@ -0,0 +1,359 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import collections.abc as c
|
||||
import os
|
||||
import typing as t
|
||||
import urllib.parse
|
||||
import warnings
|
||||
from contextvars import ContextVar
|
||||
|
||||
import jinja2.ext
|
||||
from flask import Blueprint
|
||||
from flask import current_app
|
||||
from flask import Flask
|
||||
from flask import g
|
||||
from flask import request
|
||||
from flask import send_from_directory
|
||||
from flask import url_for
|
||||
from flask.globals import request_ctx
|
||||
from jinja2 import Environment
|
||||
from jinja2 import PackageLoader
|
||||
from werkzeug import Request
|
||||
from werkzeug import Response
|
||||
from werkzeug.routing import Rule
|
||||
|
||||
from .toolbar import DebugToolbar
|
||||
from .utils import decode_text
|
||||
from .utils import gzip_compress
|
||||
from .utils import gzip_decompress
|
||||
|
||||
module: Blueprint = Blueprint("debugtoolbar", __name__)
|
||||
|
||||
|
||||
def replace_insensitive(string: str, target: str, replacement: str) -> str:
|
||||
"""Similar to string.replace() but is case insensitive
|
||||
Code borrowed from:
|
||||
http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
|
||||
"""
|
||||
no_case = string.lower()
|
||||
index = no_case.rfind(target.lower())
|
||||
|
||||
if index >= 0:
|
||||
return string[:index] + replacement + string[index + len(target) :]
|
||||
else: # no results so return the original string
|
||||
return string
|
||||
|
||||
|
||||
def _printable(value: object) -> str:
|
||||
try:
|
||||
return decode_text(repr(value))
|
||||
except Exception as e:
|
||||
return f"<repr({object.__repr__(value)}) raised {type(e).__name__}: {e}>"
|
||||
|
||||
|
||||
class DebugToolbarExtension:
|
||||
_static_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "static"))
|
||||
|
||||
_toolbar_codes = [200, 201, 400, 401, 403, 404, 405, 500, 501, 502, 503, 504]
|
||||
_redirect_codes = [301, 302, 303, 304]
|
||||
|
||||
def __init__(self, app: Flask | None = None) -> None:
|
||||
self.app = app
|
||||
self.toolbar_routes_host: str | None = None
|
||||
|
||||
# Support threads running `flask.copy_current_request_context` without
|
||||
# poping toolbar during `teardown_request`
|
||||
self.debug_toolbars_var: ContextVar[dict[Request, DebugToolbar]] = ContextVar(
|
||||
"debug_toolbars"
|
||||
)
|
||||
jinja_extensions = [jinja2.ext.i18n]
|
||||
|
||||
# Jinja2<3
|
||||
if hasattr(jinja2.ext, "with_"):
|
||||
jinja_extensions.append(jinja2.ext.with_) # pyright: ignore
|
||||
|
||||
# Configure jinja for the internal templates and add url rules
|
||||
# for static data
|
||||
self.jinja_env: Environment = Environment(
|
||||
autoescape=True,
|
||||
extensions=jinja_extensions,
|
||||
loader=PackageLoader(__name__, "templates"),
|
||||
)
|
||||
self.jinja_env.filters["urlencode"] = urllib.parse.quote_plus
|
||||
self.jinja_env.filters["printable"] = _printable
|
||||
self.jinja_env.globals["url_for"] = url_for
|
||||
|
||||
if app is not None:
|
||||
self.init_app(app)
|
||||
|
||||
def init_app(self, app: Flask) -> None:
|
||||
for k, v in self._default_config(app).items():
|
||||
app.config.setdefault(k, v)
|
||||
|
||||
if not app.config["DEBUG_TB_ENABLED"]:
|
||||
return
|
||||
|
||||
if not app.config.get("SECRET_KEY"):
|
||||
raise RuntimeError(
|
||||
"The Flask-DebugToolbar requires the 'SECRET_KEY' config "
|
||||
"var to be set"
|
||||
)
|
||||
|
||||
self._validate_and_configure_toolbar_routes_host(app)
|
||||
|
||||
DebugToolbar.load_panels(app)
|
||||
|
||||
app.before_request(self.process_request)
|
||||
app.after_request(self.process_response)
|
||||
app.teardown_request(self.teardown_request)
|
||||
|
||||
# Monkey-patch the Flask.dispatch_request method
|
||||
app.dispatch_request = self.dispatch_request # type: ignore[method-assign]
|
||||
|
||||
app.add_url_rule(
|
||||
"/_debug_toolbar/static/<path:filename>",
|
||||
"_debug_toolbar.static",
|
||||
self.send_static_file,
|
||||
host=self.toolbar_routes_host,
|
||||
)
|
||||
|
||||
app.register_blueprint(module, url_prefix="/_debug_toolbar/views")
|
||||
|
||||
def _default_config(self, app: Flask) -> dict[str, t.Any]:
|
||||
return {
|
||||
"DEBUG_TB_ENABLED": app.debug,
|
||||
"DEBUG_TB_HOSTS": (),
|
||||
"DEBUG_TB_ROUTES_HOST": None,
|
||||
"DEBUG_TB_INTERCEPT_REDIRECTS": True,
|
||||
"DEBUG_TB_PANELS": (
|
||||
"flask_debugtoolbar.panels.versions.VersionDebugPanel",
|
||||
"flask_debugtoolbar.panels.timer.TimerDebugPanel",
|
||||
"flask_debugtoolbar.panels.headers.HeaderDebugPanel",
|
||||
"flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel",
|
||||
"flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel",
|
||||
"flask_debugtoolbar.panels.template.TemplateDebugPanel",
|
||||
"flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel",
|
||||
"flask_debugtoolbar.panels.logger.LoggingPanel",
|
||||
"flask_debugtoolbar.panels.route_list.RouteListDebugPanel",
|
||||
"flask_debugtoolbar.panels.profiler.ProfilerDebugPanel",
|
||||
"flask_debugtoolbar.panels.g.GDebugPanel",
|
||||
),
|
||||
"SQLALCHEMY_RECORD_QUERIES": app.debug,
|
||||
}
|
||||
|
||||
def _validate_and_configure_toolbar_routes_host(self, app: Flask) -> None:
|
||||
toolbar_routes_host = app.config["DEBUG_TB_ROUTES_HOST"]
|
||||
if app.url_map.host_matching and not toolbar_routes_host:
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"Flask-DebugToolbar requires DEBUG_TB_ROUTES_HOST to be set if Flask "
|
||||
"is running in `host_matching` mode. Static assets for the toolbar "
|
||||
"will not be served correctly unless this is set.",
|
||||
stacklevel=1,
|
||||
)
|
||||
|
||||
if toolbar_routes_host:
|
||||
if not app.url_map.host_matching:
|
||||
raise ValueError(
|
||||
"`DEBUG_TB_ROUTES_HOST` should only be set if your Flask app is "
|
||||
"using `host_matching`."
|
||||
)
|
||||
|
||||
if toolbar_routes_host.strip() == "*":
|
||||
toolbar_routes_host = "<toolbar_routes_host>"
|
||||
elif "<" in toolbar_routes_host and ">" in toolbar_routes_host:
|
||||
raise ValueError(
|
||||
"`DEBUG_TB_ROUTES_HOST` must either be a host name with no "
|
||||
"variables, to serve all Flask-DebugToolbar assets from a single "
|
||||
"host, or `*` to match the current request's host."
|
||||
)
|
||||
|
||||
# Automatically inject `toolbar_routes_host` into `url_for` calls for
|
||||
# the toolbar's `send_static_file` method.
|
||||
@app.url_defaults
|
||||
def inject_toolbar_routes_host_if_required(
|
||||
endpoint: str, values: dict[str, t.Any]
|
||||
) -> None:
|
||||
if app.url_map.is_endpoint_expecting(endpoint, "toolbar_routes_host"):
|
||||
values.setdefault("toolbar_routes_host", request.host)
|
||||
|
||||
# Automatically strip `toolbar_routes_host` from the endpoint values so
|
||||
# that the `send_static_host` method doesn't receive that parameter,
|
||||
# as it's not actually required internally.
|
||||
@app.url_value_preprocessor
|
||||
def strip_toolbar_routes_host_from_static_endpoint(
|
||||
endpoint: str | None, values: dict[str, t.Any] | None
|
||||
) -> None:
|
||||
if (
|
||||
endpoint
|
||||
and values
|
||||
and app.url_map.is_endpoint_expecting(
|
||||
endpoint, "toolbar_routes_host"
|
||||
)
|
||||
):
|
||||
values.pop("toolbar_routes_host", None)
|
||||
|
||||
self.toolbar_routes_host = toolbar_routes_host
|
||||
|
||||
def dispatch_request(self) -> t.Any:
|
||||
"""Modified version of ``Flask.dispatch_request`` to call
|
||||
:meth:`process_view`.
|
||||
"""
|
||||
# self references this extension, use current_app to call app methods.
|
||||
app = current_app._get_current_object() # type: ignore[attr-defined]
|
||||
req = request_ctx.request
|
||||
|
||||
if req.routing_exception is not None:
|
||||
app.raise_routing_exception(req)
|
||||
|
||||
rule: Rule = req.url_rule # type: ignore[assignment]
|
||||
|
||||
if (
|
||||
getattr(rule, "provide_automatic_options", False)
|
||||
and req.method == "OPTIONS"
|
||||
):
|
||||
return app.make_default_options_response()
|
||||
|
||||
view_func = app.view_functions[rule.endpoint]
|
||||
view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]
|
||||
# allow each toolbar to process the view and args
|
||||
view_func = self.process_view(app, view_func, view_args)
|
||||
return view_func(**view_args)
|
||||
|
||||
def _show_toolbar(self) -> bool:
|
||||
"""Return a boolean to indicate if we need to show the toolbar."""
|
||||
if request.blueprint == "debugtoolbar":
|
||||
return False
|
||||
|
||||
hosts = current_app.config["DEBUG_TB_HOSTS"]
|
||||
|
||||
if hosts and request.remote_addr not in hosts:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def send_static_file(self, filename: str) -> Response:
|
||||
"""Send a static file from the flask-debugtoolbar static directory."""
|
||||
return send_from_directory(self._static_dir, filename)
|
||||
|
||||
def process_request(self) -> None:
|
||||
g.debug_toolbar = self
|
||||
|
||||
if not self._show_toolbar():
|
||||
return
|
||||
|
||||
real_request = request._get_current_object() # type: ignore[attr-defined]
|
||||
self.debug_toolbars_var.set({})
|
||||
self.debug_toolbars_var.get()[real_request] = DebugToolbar(
|
||||
real_request, self.jinja_env
|
||||
)
|
||||
|
||||
for panel in self.debug_toolbars_var.get()[real_request].panels:
|
||||
panel.process_request(real_request)
|
||||
|
||||
def process_view(
|
||||
self,
|
||||
app: Flask,
|
||||
view_func: c.Callable[..., t.Any],
|
||||
view_kwargs: dict[str, t.Any],
|
||||
) -> c.Callable[..., t.Any]:
|
||||
"""This method is called just before the flask view is called.
|
||||
This is done by the dispatch_request method.
|
||||
"""
|
||||
real_request = request._get_current_object() # type: ignore[attr-defined]
|
||||
|
||||
try:
|
||||
toolbar = self.debug_toolbars_var.get({})[real_request]
|
||||
except KeyError:
|
||||
return view_func
|
||||
|
||||
for panel in toolbar.panels:
|
||||
new_view = panel.process_view(real_request, view_func, view_kwargs)
|
||||
|
||||
if new_view:
|
||||
view_func = new_view
|
||||
|
||||
return view_func
|
||||
|
||||
def process_response(self, response: Response) -> Response:
|
||||
real_request = request._get_current_object() # type: ignore[attr-defined]
|
||||
|
||||
if real_request not in self.debug_toolbars_var.get({}):
|
||||
return response
|
||||
|
||||
# Intercept http redirect codes and display an html page with a
|
||||
# link to the target.
|
||||
if current_app.config["DEBUG_TB_INTERCEPT_REDIRECTS"]:
|
||||
if response.status_code in self._redirect_codes:
|
||||
redirect_to = response.location
|
||||
redirect_code = response.status_code
|
||||
|
||||
if redirect_to:
|
||||
content = self.render(
|
||||
"redirect.html",
|
||||
{"redirect_to": redirect_to, "redirect_code": redirect_code},
|
||||
)
|
||||
response.content_length = len(content)
|
||||
del response.location
|
||||
response.response = [content]
|
||||
response.status_code = 200
|
||||
|
||||
# If the http response code is an allowed code then we process to add the
|
||||
# toolbar to the returned html response.
|
||||
if not (
|
||||
response.status_code in self._toolbar_codes
|
||||
and response.is_sequence
|
||||
and response.headers["content-type"].startswith("text/html")
|
||||
):
|
||||
return response
|
||||
|
||||
content_encoding = response.headers.get("Content-Encoding")
|
||||
|
||||
if content_encoding and "gzip" in content_encoding:
|
||||
response_html = gzip_decompress(response.data).decode()
|
||||
else:
|
||||
response_html = response.get_data(as_text=True)
|
||||
|
||||
no_case = response_html.lower()
|
||||
body_end = no_case.rfind("</body>")
|
||||
|
||||
if body_end >= 0:
|
||||
before = response_html[:body_end]
|
||||
after = response_html[body_end:]
|
||||
elif no_case.startswith("<!doctype html>"):
|
||||
before = response_html
|
||||
after = ""
|
||||
else:
|
||||
warnings.warn(
|
||||
"Could not insert debug toolbar." " </body> tag not found in response.",
|
||||
stacklevel=1,
|
||||
)
|
||||
return response
|
||||
|
||||
toolbar = self.debug_toolbars_var.get()[real_request]
|
||||
|
||||
for panel in toolbar.panels:
|
||||
panel.process_response(real_request, response)
|
||||
|
||||
toolbar_html = toolbar.render_toolbar()
|
||||
|
||||
content = "".join((before, toolbar_html, after))
|
||||
content_bytes = content.encode("utf-8")
|
||||
|
||||
if content_encoding and "gzip" in content_encoding:
|
||||
content_bytes = gzip_compress(content_bytes)
|
||||
|
||||
response.response = [content_bytes]
|
||||
response.content_length = len(content_bytes)
|
||||
|
||||
return response
|
||||
|
||||
def teardown_request(self, exc: BaseException | None) -> None:
|
||||
# debug_toolbars_var won't be set under `flask.copy_current_request_context`
|
||||
real_request = request._get_current_object() # type: ignore[attr-defined]
|
||||
self.debug_toolbars_var.get({}).pop(real_request, None)
|
||||
|
||||
def render(self, template_name: str, context: dict[str, t.Any]) -> str:
|
||||
template = self.jinja_env.get_template(template_name)
|
||||
return template.render(**context)
|
||||
99
src/flask_debugtoolbar/panels/__init__.py
Normal file
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import collections.abc as c
|
||||
import typing as t
|
||||
|
||||
from flask import Flask
|
||||
from jinja2 import Environment
|
||||
from werkzeug import Request
|
||||
from werkzeug import Response
|
||||
|
||||
|
||||
class DebugPanel:
|
||||
"""Base class for debug panels."""
|
||||
|
||||
name: str
|
||||
|
||||
# If content returns something, set to true in subclass
|
||||
has_content = False
|
||||
|
||||
# If the client is able to activate/de-activate the panel
|
||||
user_enable = False
|
||||
|
||||
# We'll maintain a local context instance so we can expose our template
|
||||
# context variables to panels which need them:
|
||||
context: dict[str, t.Any] = {}
|
||||
|
||||
# Panel methods
|
||||
def __init__(
|
||||
self, jinja_env: Environment, context: dict[str, t.Any] | None = None
|
||||
) -> None:
|
||||
if context is not None:
|
||||
self.context.update(context)
|
||||
|
||||
self.jinja_env = jinja_env
|
||||
# If the client enabled the panel
|
||||
self.is_active = False
|
||||
|
||||
@classmethod
|
||||
def init_app(cls, app: Flask) -> None:
|
||||
"""Method that can be overridden by child classes.
|
||||
Can be used for setting up additional URL-rules/routes.
|
||||
|
||||
Example::
|
||||
|
||||
class UMLDiagramPanel(DebugPanel):
|
||||
|
||||
@classmethod
|
||||
def init_app(cls, app):
|
||||
app.add_url_rule(
|
||||
'/_flask_debugtoolbar_umldiagram/<path:filename>',
|
||||
'_flask_debugtoolbar_umldiagram.serve_generated_image',
|
||||
cls.serve_generated_image
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def serve_generated_image(cls, app):
|
||||
return Response(...)
|
||||
"""
|
||||
pass
|
||||
|
||||
def render(self, template_name: str, context: dict[str, t.Any]) -> str:
|
||||
template = self.jinja_env.get_template(template_name)
|
||||
return template.render(**context)
|
||||
|
||||
def dom_id(self) -> str:
|
||||
return f"flDebug{self.name.replace(' ', '')}Panel"
|
||||
|
||||
def nav_title(self) -> str:
|
||||
"""Title showing in toolbar"""
|
||||
raise NotImplementedError
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
"""Subtitle showing until title in toolbar"""
|
||||
return ""
|
||||
|
||||
def title(self) -> str:
|
||||
"""Title showing in panel"""
|
||||
raise NotImplementedError
|
||||
|
||||
def url(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
def content(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
# Standard middleware methods
|
||||
def process_request(self, request: Request) -> None:
|
||||
pass
|
||||
|
||||
def process_view(
|
||||
self,
|
||||
request: Request,
|
||||
view_func: c.Callable[..., t.Any],
|
||||
view_kwargs: dict[str, t.Any],
|
||||
) -> c.Callable[..., t.Any] | None:
|
||||
pass
|
||||
|
||||
def process_response(self, request: Request, response: Response) -> None:
|
||||
pass
|
||||
30
src/flask_debugtoolbar/panels/config_vars.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class ConfigVarsDebugPanel(DebugPanel):
|
||||
"""A panel to display all variables from Flask configuration."""
|
||||
|
||||
name = "ConfigVars"
|
||||
has_content = True
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Config"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Config"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
context = self.context.copy()
|
||||
context.update(
|
||||
{
|
||||
"config": current_app.config,
|
||||
}
|
||||
)
|
||||
return self.render("panels/config_vars.html", context)
|
||||
26
src/flask_debugtoolbar/panels/g.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class GDebugPanel(DebugPanel):
|
||||
"""A panel to display ``flask.g`` content."""
|
||||
|
||||
name = "g"
|
||||
has_content = True
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "flask.g"
|
||||
|
||||
def title(self) -> str:
|
||||
return "flask.g content"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
context = self.context.copy()
|
||||
context.update({"g_content": g.__dict__})
|
||||
return self.render("panels/g.html", context)
|
||||
56
src/flask_debugtoolbar/panels/headers.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing as t
|
||||
|
||||
from werkzeug import Request
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class HeaderDebugPanel(DebugPanel):
|
||||
"""A panel to display HTTP headers."""
|
||||
|
||||
name = "Header"
|
||||
has_content = True
|
||||
# List of headers we want to display
|
||||
header_filter: tuple[str, ...] = (
|
||||
"CONTENT_TYPE",
|
||||
"HTTP_ACCEPT",
|
||||
"HTTP_ACCEPT_CHARSET",
|
||||
"HTTP_ACCEPT_ENCODING",
|
||||
"HTTP_ACCEPT_LANGUAGE",
|
||||
"HTTP_CACHE_CONTROL",
|
||||
"HTTP_CONNECTION",
|
||||
"HTTP_HOST",
|
||||
"HTTP_KEEP_ALIVE",
|
||||
"HTTP_REFERER",
|
||||
"HTTP_USER_AGENT",
|
||||
"QUERY_STRING",
|
||||
"REMOTE_ADDR",
|
||||
"REMOTE_HOST",
|
||||
"REQUEST_METHOD",
|
||||
"SCRIPT_NAME",
|
||||
"SERVER_NAME",
|
||||
"SERVER_PORT",
|
||||
"SERVER_PROTOCOL",
|
||||
"SERVER_SOFTWARE",
|
||||
)
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "HTTP Headers"
|
||||
|
||||
def title(self) -> str:
|
||||
return "HTTP Headers"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
self.headers: dict[str, t.Any] = {
|
||||
k: request.environ[k] for k in self.header_filter if k in request.environ
|
||||
}
|
||||
|
||||
def content(self) -> str:
|
||||
context = self.context.copy()
|
||||
context.update({"headers": self.headers})
|
||||
return self.render("panels/headers.html", context)
|
||||
115
src/flask_debugtoolbar/panels/logger.py
Normal file
@@ -0,0 +1,115 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from werkzeug import Request
|
||||
|
||||
from ..utils import format_fname
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class ThreadTrackingHandler(logging.Handler):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
# a dictionary that maps threads to log records
|
||||
self.records: dict[threading.Thread, list[logging.LogRecord]] = {}
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
self.get_records().append(record)
|
||||
|
||||
def get_records(
|
||||
self, thread: threading.Thread | None = None
|
||||
) -> list[logging.LogRecord]:
|
||||
"""
|
||||
Returns a list of records for the provided thread, of if none is
|
||||
provided, returns a list for the current thread.
|
||||
"""
|
||||
if thread is None:
|
||||
thread = threading.current_thread()
|
||||
|
||||
if thread not in self.records:
|
||||
self.records[thread] = []
|
||||
|
||||
return self.records[thread]
|
||||
|
||||
def clear_records(self, thread: threading.Thread | None = None) -> None:
|
||||
if thread is None:
|
||||
thread = threading.current_thread()
|
||||
|
||||
if thread in self.records:
|
||||
del self.records[thread]
|
||||
|
||||
|
||||
handler: ThreadTrackingHandler = None # type: ignore[assignment]
|
||||
_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def _init_once() -> None:
|
||||
global handler
|
||||
|
||||
if handler is not None:
|
||||
return
|
||||
|
||||
with _init_lock:
|
||||
if handler is not None:
|
||||
return
|
||||
|
||||
# Call werkzeug's internal logging to make sure it gets configured
|
||||
# before we add our handler. Otherwise werkzeug will see our handler
|
||||
# and not configure console logging for the request log.
|
||||
# Werkzeug's default log level is INFO so this message probably won't
|
||||
# be seen.
|
||||
from werkzeug._internal import _log
|
||||
|
||||
_log("debug", "Initializing Flask-DebugToolbar log handler")
|
||||
handler = ThreadTrackingHandler()
|
||||
logging.root.addHandler(handler)
|
||||
|
||||
|
||||
class LoggingPanel(DebugPanel):
|
||||
name = "Logging"
|
||||
has_content = True
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
_init_once()
|
||||
handler.clear_records()
|
||||
|
||||
def get_and_delete(self) -> list[logging.LogRecord]:
|
||||
records = handler.get_records()
|
||||
handler.clear_records()
|
||||
return records
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Logging"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
num_records = len(handler.get_records())
|
||||
plural = "message" if num_records == 1 else "messages"
|
||||
return f"{num_records} {plural}"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Log Messages"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
records = []
|
||||
|
||||
for record in self.get_and_delete():
|
||||
records.append(
|
||||
{
|
||||
"message": record.getMessage(),
|
||||
"time": datetime.datetime.fromtimestamp(record.created),
|
||||
"level": record.levelname,
|
||||
"file": format_fname(record.pathname),
|
||||
"file_long": record.pathname,
|
||||
"line": record.lineno,
|
||||
}
|
||||
)
|
||||
|
||||
context = self.context.copy()
|
||||
context.update({"records": records})
|
||||
return self.render("panels/logger.html", context)
|
||||
156
src/flask_debugtoolbar/panels/profiler.py
Normal file
@@ -0,0 +1,156 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import collections.abc as c
|
||||
import functools
|
||||
import pstats
|
||||
import typing as t
|
||||
|
||||
from flask import current_app
|
||||
from jinja2 import Environment
|
||||
from werkzeug import Request
|
||||
from werkzeug import Response
|
||||
|
||||
from ..utils import format_fname
|
||||
from . import DebugPanel
|
||||
|
||||
try:
|
||||
import cProfile as profile
|
||||
except ImportError:
|
||||
import profile # type: ignore[no-redef]
|
||||
|
||||
|
||||
class ProfilerDebugPanel(DebugPanel):
|
||||
"""Panel that displays the time a response took with cProfile output."""
|
||||
|
||||
name = "Profiler"
|
||||
user_activate = True
|
||||
|
||||
is_active: bool = False
|
||||
dump_filename: str | None = None
|
||||
profiler: profile.Profile
|
||||
stats: pstats.Stats | None = None
|
||||
function_calls: list[dict[str, t.Any]]
|
||||
|
||||
def __init__(
|
||||
self, jinja_env: Environment, context: dict[str, t.Any] | None = None
|
||||
) -> None:
|
||||
super().__init__(jinja_env, context=context)
|
||||
|
||||
if current_app.config.get("DEBUG_TB_PROFILER_ENABLED"):
|
||||
self.is_active = True
|
||||
self.dump_filename = current_app.config.get(
|
||||
"DEBUG_TB_PROFILER_DUMP_FILENAME"
|
||||
)
|
||||
|
||||
@property
|
||||
def has_content(self) -> bool: # type: ignore[override]
|
||||
return bool(self.profiler)
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
if not self.is_active:
|
||||
return
|
||||
|
||||
self.profiler = profile.Profile() # pyright: ignore
|
||||
self.stats = None
|
||||
|
||||
def process_view(
|
||||
self,
|
||||
request: Request,
|
||||
view_func: c.Callable[..., t.Any],
|
||||
view_kwargs: dict[str, t.Any],
|
||||
) -> c.Callable[..., t.Any] | None:
|
||||
if self.is_active:
|
||||
func = functools.partial(self.profiler.runcall, view_func)
|
||||
functools.update_wrapper(func, view_func)
|
||||
return func
|
||||
|
||||
return None
|
||||
|
||||
def process_response(self, request: Request, response: Response) -> None:
|
||||
if not self.is_active:
|
||||
return
|
||||
|
||||
if self.profiler is not None:
|
||||
self.profiler.disable() # pyright: ignore
|
||||
|
||||
try:
|
||||
stats = pstats.Stats(self.profiler)
|
||||
except TypeError:
|
||||
self.is_active = False
|
||||
return
|
||||
|
||||
function_calls: list[dict[str, t.Any]] = []
|
||||
|
||||
for func in stats.sort_stats(1).fcn_list: # type: ignore[attr-defined]
|
||||
current: dict[str, t.Any] = {}
|
||||
info = stats.stats[func] # type: ignore[attr-defined]
|
||||
|
||||
# Number of calls
|
||||
if info[0] != info[1]:
|
||||
current["ncalls"] = f"{info[1]}/{info[0]}"
|
||||
else:
|
||||
current["ncalls"] = info[1]
|
||||
|
||||
# Total time
|
||||
current["tottime"] = info[2] * 1000
|
||||
|
||||
# Quotient of total time divided by number of calls
|
||||
if info[1]:
|
||||
current["percall"] = info[2] * 1000 / info[1]
|
||||
else:
|
||||
current["percall"] = 0
|
||||
|
||||
# Cumulative time
|
||||
current["cumtime"] = info[3] * 1000
|
||||
|
||||
# Quotient of the cumulative time divided by the number of
|
||||
# primitive calls.
|
||||
if info[0]:
|
||||
current["percall_cum"] = info[3] * 1000 / info[0]
|
||||
else:
|
||||
current["percall_cum"] = 0
|
||||
|
||||
# Filename
|
||||
filename = pstats.func_std_string(func) # type: ignore[attr-defined]
|
||||
current["filename_long"] = filename
|
||||
current["filename"] = format_fname(filename)
|
||||
function_calls.append(current)
|
||||
|
||||
self.stats = stats
|
||||
self.function_calls = function_calls
|
||||
|
||||
if self.dump_filename:
|
||||
if callable(self.dump_filename):
|
||||
filename = self.dump_filename()
|
||||
else:
|
||||
filename = self.dump_filename
|
||||
|
||||
self.profiler.dump_stats(filename)
|
||||
|
||||
def title(self) -> str:
|
||||
if not self.is_active:
|
||||
return "Profiler not active"
|
||||
|
||||
return f"View: {float(self.stats.total_tt) * 1000:.2f}ms" # type: ignore[union-attr]
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Profiler"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
if not self.is_active:
|
||||
return "in-active"
|
||||
|
||||
return f"View: {float(self.stats.total_tt) * 1000:.2f}ms" # type: ignore[union-attr]
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
if not self.is_active:
|
||||
return "The profiler is not activated, activate it to use it"
|
||||
|
||||
context = {
|
||||
"stats": self.stats,
|
||||
"function_calls": self.function_calls,
|
||||
}
|
||||
return self.render("panels/profiler.html", context)
|
||||
59
src/flask_debugtoolbar/panels/request_vars.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import collections.abc as c
|
||||
import typing as t
|
||||
|
||||
from flask import session
|
||||
from werkzeug import Request
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class RequestVarsDebugPanel(DebugPanel):
|
||||
"""A panel to display request variables (POST/GET, session, cookies)."""
|
||||
|
||||
name = "RequestVars"
|
||||
has_content = True
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Request Vars"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Request Vars"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
self.request = request
|
||||
self.session = session
|
||||
self.view_func: c.Callable[..., t.Any] | None = None
|
||||
self.view_kwargs: dict[str, t.Any] = {}
|
||||
|
||||
def process_view(
|
||||
self,
|
||||
request: Request,
|
||||
view_func: c.Callable[..., t.Any],
|
||||
view_kwargs: dict[str, t.Any],
|
||||
) -> None:
|
||||
self.view_func = view_func
|
||||
self.view_kwargs = view_kwargs
|
||||
|
||||
def content(self) -> str:
|
||||
context = self.context.copy()
|
||||
context.update(
|
||||
{
|
||||
"get": self.request.args.lists(),
|
||||
"post": self.request.form.lists(),
|
||||
"cookies": self.request.cookies.items(),
|
||||
"view_func": (
|
||||
f"{self.view_func.__module__}.{self.view_func.__name__}"
|
||||
if self.view_func
|
||||
else "[unknown]"
|
||||
),
|
||||
"view_kwargs": self.view_kwargs or {},
|
||||
"session": self.session.items(),
|
||||
}
|
||||
)
|
||||
|
||||
return self.render("panels/request_vars.html", context)
|
||||
44
src/flask_debugtoolbar/panels/route_list.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug import Request
|
||||
from werkzeug.routing import Rule
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class RouteListDebugPanel(DebugPanel):
|
||||
"""Panel that displays the URL routing rules."""
|
||||
|
||||
name = "RouteList"
|
||||
has_content = True
|
||||
routes: list[Rule] = []
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Route List"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Route List"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
count = len(self.routes)
|
||||
plural = "route" if count == 1 else "routes"
|
||||
return f"{count} {plural}"
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
self.routes = [
|
||||
rule
|
||||
for rule in current_app.url_map.iter_rules()
|
||||
if not rule.rule.startswith("/_debug_toolbar")
|
||||
]
|
||||
|
||||
def content(self) -> str:
|
||||
return self.render(
|
||||
"panels/route_list.html",
|
||||
{
|
||||
"routes": self.routes,
|
||||
},
|
||||
)
|
||||
186
src/flask_debugtoolbar/panels/sqlalchemy.py
Normal file
@@ -0,0 +1,186 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing as t
|
||||
|
||||
import itsdangerous
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import g
|
||||
from flask import request
|
||||
|
||||
from .. import module
|
||||
from ..utils import format_fname
|
||||
from ..utils import format_sql
|
||||
from . import DebugPanel
|
||||
|
||||
try:
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
except ImportError:
|
||||
sqlalchemy_available: bool = False
|
||||
get_recorded_queries = SQLAlchemy = None # type: ignore[misc, assignment]
|
||||
debug_enables_record_queries: bool = False
|
||||
else:
|
||||
try:
|
||||
from flask_sqlalchemy.record_queries import ( # type: ignore[assignment]
|
||||
get_recorded_queries,
|
||||
)
|
||||
|
||||
debug_enables_record_queries = False
|
||||
except ImportError:
|
||||
# For flask_sqlalchemy < 3.0.0
|
||||
from flask_sqlalchemy import ( # type: ignore[no-redef]
|
||||
get_debug_queries as get_recorded_queries,
|
||||
)
|
||||
|
||||
# flask_sqlalchemy < 3.0.0 automatically enabled
|
||||
# SQLALCHEMY_RECORD_QUERIES in debug or test mode
|
||||
debug_enables_record_queries = True
|
||||
location_property: str = "context"
|
||||
else:
|
||||
location_property = "location"
|
||||
|
||||
sqlalchemy_available = True
|
||||
|
||||
|
||||
def query_signer() -> itsdangerous.URLSafeSerializer:
|
||||
return itsdangerous.URLSafeSerializer(
|
||||
current_app.config["SECRET_KEY"], salt="fdt-sql-query"
|
||||
)
|
||||
|
||||
|
||||
def is_select(statement: str | bytes) -> bool:
|
||||
statement = statement.lower().strip()
|
||||
|
||||
if isinstance(statement, bytes):
|
||||
return statement.startswith(b"select")
|
||||
|
||||
return statement.startswith("select") # pyright: ignore
|
||||
|
||||
|
||||
def dump_query(statement: str, params: t.Any) -> str | None:
|
||||
if not params or not is_select(statement):
|
||||
return None
|
||||
|
||||
try:
|
||||
return query_signer().dumps([statement, params])
|
||||
except TypeError:
|
||||
return None
|
||||
|
||||
|
||||
def load_query(data: str) -> tuple[str, t.Any]:
|
||||
try:
|
||||
statement, params = query_signer().loads(data)
|
||||
except (itsdangerous.BadSignature, TypeError):
|
||||
abort(406)
|
||||
|
||||
# Make sure it is a select statement
|
||||
if not is_select(statement):
|
||||
abort(406)
|
||||
|
||||
return statement, params
|
||||
|
||||
|
||||
def extension_used() -> bool:
|
||||
return "sqlalchemy" in current_app.extensions
|
||||
|
||||
|
||||
def recording_enabled() -> bool:
|
||||
return (
|
||||
debug_enables_record_queries and current_app.debug
|
||||
) or current_app.config.get("SQLALCHEMY_RECORD_QUERIES", False)
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
return sqlalchemy_available and extension_used() and recording_enabled()
|
||||
|
||||
|
||||
def get_queries() -> list[t.Any]:
|
||||
if get_recorded_queries:
|
||||
return get_recorded_queries()
|
||||
else:
|
||||
return []
|
||||
|
||||
|
||||
class SQLAlchemyDebugPanel(DebugPanel):
|
||||
"""Panel that displays the time a response took in milliseconds."""
|
||||
|
||||
name = "SQLAlchemy"
|
||||
|
||||
@property
|
||||
def has_content(self) -> bool: # type: ignore[override]
|
||||
return bool(get_queries()) or not is_available()
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "SQLAlchemy"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
count = len(get_queries())
|
||||
|
||||
if not count and not is_available():
|
||||
return "Unavailable"
|
||||
|
||||
plural = "query" if count == 1 else "queries"
|
||||
return f"{count} {plural}"
|
||||
|
||||
def title(self) -> str:
|
||||
return "SQLAlchemy queries"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
queries = get_queries()
|
||||
|
||||
if not queries and not is_available():
|
||||
return self.render(
|
||||
"panels/sqlalchemy_error.html",
|
||||
{
|
||||
"sqlalchemy_available": sqlalchemy_available,
|
||||
"extension_used": extension_used(),
|
||||
"recording_enabled": recording_enabled(),
|
||||
},
|
||||
)
|
||||
|
||||
data = []
|
||||
|
||||
for query in queries:
|
||||
data.append(
|
||||
{
|
||||
"duration": query.duration,
|
||||
"sql": format_sql(query.statement, query.parameters),
|
||||
"signed_query": dump_query(query.statement, query.parameters),
|
||||
"location_long": getattr(query, location_property),
|
||||
"location": format_fname(getattr(query, location_property)),
|
||||
}
|
||||
)
|
||||
|
||||
return self.render("panels/sqlalchemy.html", {"queries": data})
|
||||
|
||||
|
||||
# Panel views
|
||||
|
||||
|
||||
@module.route("/sqlalchemy/sql_select", methods=["GET", "POST"])
|
||||
@module.route(
|
||||
"/sqlalchemy/sql_explain", methods=["GET", "POST"], defaults=dict(explain=True)
|
||||
)
|
||||
def sql_select(explain: bool = False) -> str:
|
||||
statement, params = load_query(request.args["query"])
|
||||
engine = current_app.extensions["sqlalchemy"].engine
|
||||
|
||||
if explain:
|
||||
if engine.driver == "pysqlite":
|
||||
statement = f"EXPLAIN QUERY PLAN\n{statement}"
|
||||
else:
|
||||
statement = f"EXPLAIN\n{statement}"
|
||||
|
||||
result = engine.execute(statement, params)
|
||||
return g.debug_toolbar.render( # type: ignore[no-any-return]
|
||||
"panels/sqlalchemy_select.html",
|
||||
{
|
||||
"result": result.fetchall(),
|
||||
"headers": result.keys(),
|
||||
"sql": format_sql(statement, params),
|
||||
"duration": float(request.args["duration"]),
|
||||
},
|
||||
)
|
||||
149
src/flask_debugtoolbar/panels/template.py
Normal file
@@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import typing as t
|
||||
import uuid
|
||||
from collections import deque
|
||||
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import g
|
||||
from flask import request
|
||||
from flask import Response
|
||||
from flask import template_rendered
|
||||
from flask import url_for
|
||||
from jinja2 import Template
|
||||
|
||||
from .. import module
|
||||
from . import DebugPanel
|
||||
|
||||
|
||||
class TemplateDebugPanel(DebugPanel):
|
||||
"""Panel that displays the time a response took in milliseconds."""
|
||||
|
||||
name = "Template"
|
||||
has_content = True
|
||||
|
||||
# save the context for the 5 most recent requests
|
||||
template_cache: deque[tuple[str, list[dict[str, t.Any]]]] = deque(maxlen=5)
|
||||
|
||||
@classmethod
|
||||
def get_cache_for_key(cls, key: str) -> list[dict[str, t.Any]]:
|
||||
for cache_key, value in cls.template_cache:
|
||||
if key == cache_key:
|
||||
return value
|
||||
|
||||
raise KeyError(key)
|
||||
|
||||
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.key: str = str(uuid.uuid4())
|
||||
self.templates: list[dict[str, t.Any]] = []
|
||||
template_rendered.connect(self._store_template_info)
|
||||
|
||||
def _store_template_info(self, sender: t.Any, **kwargs: t.Any) -> None:
|
||||
# only record in the cache if the editor is enabled and there is
|
||||
# actually a template for this request
|
||||
if not self.templates and is_editor_enabled():
|
||||
self.template_cache.append((self.key, self.templates))
|
||||
|
||||
self.templates.append(kwargs)
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Templates"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
return f"{len(self.templates)} rendered"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Templates"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def content(self) -> str:
|
||||
return self.render(
|
||||
"panels/template.html",
|
||||
{
|
||||
"key": self.key,
|
||||
"templates": self.templates,
|
||||
"editable": is_editor_enabled(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def is_editor_enabled() -> bool:
|
||||
return current_app.config.get("DEBUG_TB_TEMPLATE_EDITOR_ENABLED", False) # type: ignore
|
||||
|
||||
|
||||
def require_enabled() -> None:
|
||||
if not is_editor_enabled():
|
||||
abort(403)
|
||||
|
||||
|
||||
def _get_source(template: Template) -> str:
|
||||
if template.filename is None:
|
||||
return ""
|
||||
|
||||
with open(template.filename, "rb") as fp:
|
||||
source = fp.read()
|
||||
|
||||
return source.decode(_template_encoding())
|
||||
|
||||
|
||||
def _template_encoding() -> str:
|
||||
return getattr(current_app.jinja_loader, "encoding", "utf-8")
|
||||
|
||||
|
||||
@module.route("/template/<key>")
|
||||
def template_editor(key: str) -> str:
|
||||
require_enabled()
|
||||
# TODO set up special loader that caches templates it loads
|
||||
# and can override template contents
|
||||
templates = [t["template"] for t in TemplateDebugPanel.get_cache_for_key(key)]
|
||||
return g.debug_toolbar.render( # type: ignore[no-any-return]
|
||||
"panels/template_editor.html",
|
||||
{
|
||||
"static_path": url_for("_debug_toolbar.static", filename=""),
|
||||
"request": request,
|
||||
"templates": [
|
||||
{"name": t.name, "source": _get_source(t)} for t in templates
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@module.route("/template/<key>/save", methods=["POST"])
|
||||
def save_template(key: str) -> str:
|
||||
require_enabled()
|
||||
template = TemplateDebugPanel.get_cache_for_key(key)[0]["template"]
|
||||
content = request.form["content"].encode(_template_encoding())
|
||||
|
||||
with open(template.filename, "wb") as fp:
|
||||
fp.write(content)
|
||||
|
||||
return "ok"
|
||||
|
||||
|
||||
@module.route("/template/<key>", methods=["POST"])
|
||||
def template_preview(key: str) -> str | Response:
|
||||
require_enabled()
|
||||
context = TemplateDebugPanel.get_cache_for_key(key)[0]["context"]
|
||||
content = request.form["content"]
|
||||
env = current_app.jinja_env.overlay(autoescape=True)
|
||||
|
||||
try:
|
||||
template = env.from_string(content)
|
||||
return template.render(context)
|
||||
except Exception as e:
|
||||
tb = sys.exc_info()[2]
|
||||
|
||||
try:
|
||||
while tb.tb_next: # type: ignore[union-attr]
|
||||
tb = tb.tb_next # type: ignore[union-attr]
|
||||
|
||||
msg = {"lineno": tb.tb_lineno, "error": str(e)} # type: ignore[union-attr]
|
||||
return Response(json.dumps(msg), status=400, mimetype="application/json")
|
||||
finally:
|
||||
del tb
|
||||
93
src/flask_debugtoolbar/panels/timer.py
Normal file
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from werkzeug import Request
|
||||
from werkzeug import Response
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
try:
|
||||
import resource
|
||||
|
||||
HAVE_RESOURCE = True
|
||||
except ImportError:
|
||||
HAVE_RESOURCE = False
|
||||
|
||||
|
||||
class TimerDebugPanel(DebugPanel):
|
||||
"""Panel that displays the time a response took in milliseconds."""
|
||||
|
||||
name = "Timer"
|
||||
has_content = HAVE_RESOURCE
|
||||
|
||||
def process_request(self, request: Request) -> None:
|
||||
self._start_time = time.time()
|
||||
|
||||
if HAVE_RESOURCE:
|
||||
self._start_rusage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
|
||||
def process_response(self, request: Request, response: Response) -> None:
|
||||
self.total_time: float = (time.time() - self._start_time) * 1000
|
||||
|
||||
if HAVE_RESOURCE:
|
||||
self._end_rusage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Time"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
if not HAVE_RESOURCE:
|
||||
return f"TOTAL: {self.total_time:0.2f}ms"
|
||||
|
||||
utime = self._end_rusage.ru_utime - self._start_rusage.ru_utime
|
||||
stime = self._end_rusage.ru_stime - self._start_rusage.ru_stime
|
||||
return f"CPU: {(utime + stime) * 1000.0:0.2f}ms ({self.total_time:0.2f}ms)"
|
||||
|
||||
def title(self) -> str:
|
||||
return "Resource Usage"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def _elapsed_ru(self, name: str) -> float:
|
||||
return getattr(self._end_rusage, name) - getattr(self._start_rusage, name) # type: ignore[no-any-return]
|
||||
|
||||
def content(self) -> str:
|
||||
utime = 1000 * self._elapsed_ru("ru_utime")
|
||||
stime = 1000 * self._elapsed_ru("ru_stime")
|
||||
vcsw = self._elapsed_ru("ru_nvcsw")
|
||||
ivcsw = self._elapsed_ru("ru_nivcsw")
|
||||
# minflt = self._elapsed_ru("ru_minflt")
|
||||
# majflt = self._elapsed_ru("ru_majflt")
|
||||
|
||||
# these are documented as not meaningful under Linux. If you're running BSD
|
||||
# feel free to enable them, and add any others that I hadn't gotten to before
|
||||
# I noticed that I was getting nothing but zeroes and that the docs agreed. :-(
|
||||
# blkin = self._elapsed_ru("ru_inblock")
|
||||
# blkout = self._elapsed_ru("ru_oublock")
|
||||
# swap = self._elapsed_ru("ru_nswap")
|
||||
# rss = self._end_rusage.ru_maxrss
|
||||
# srss = self._end_rusage.ru_ixrss
|
||||
# urss = self._end_rusage.ru_idrss
|
||||
# usrss = self._end_rusage.ru_isrss
|
||||
rows = (
|
||||
("User CPU time", f"{utime:0.3f} msec"),
|
||||
("System CPU time", f"{stime:0.3f} msec"),
|
||||
("Total CPU time", f"{(utime + stime):0.3f} msec"),
|
||||
("Elapsed time", f"{self.total_time:0.3f} msec"),
|
||||
("Context switches", f"{vcsw} voluntary, {ivcsw} involuntary"),
|
||||
# (
|
||||
# "Memory use",
|
||||
# f"{rss} max RSS, {srss} shared, {urss + usrss} unshared",
|
||||
# ),
|
||||
# ("Page faults", f"{minflt} no i/o, {majflt} requiring i/o"),
|
||||
# ("Disk operations", f"{blkin} in, {blkout} out, {swap} swapout"),
|
||||
)
|
||||
context = self.context.copy()
|
||||
context.update(
|
||||
{
|
||||
"rows": rows,
|
||||
}
|
||||
)
|
||||
return self.render("panels/timer.html", context)
|
||||
39
src/flask_debugtoolbar/panels/versions.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.metadata
|
||||
import os
|
||||
from sysconfig import get_path
|
||||
|
||||
from . import DebugPanel
|
||||
|
||||
flask_version: str = importlib.metadata.version("flask")
|
||||
|
||||
|
||||
class VersionDebugPanel(DebugPanel):
|
||||
"""Panel that displays the Flask version."""
|
||||
|
||||
name = "Version"
|
||||
has_content = True
|
||||
|
||||
def nav_title(self) -> str:
|
||||
return "Versions"
|
||||
|
||||
def nav_subtitle(self) -> str:
|
||||
return f"Flask {flask_version}"
|
||||
|
||||
def url(self) -> str:
|
||||
return ""
|
||||
|
||||
def title(self) -> str:
|
||||
return "Versions"
|
||||
|
||||
def content(self) -> str:
|
||||
packages_metadata = [p.metadata for p in importlib.metadata.distributions()]
|
||||
packages = sorted(packages_metadata, key=lambda p: p["Name"].lower())
|
||||
return self.render(
|
||||
"panels/versions.html",
|
||||
{
|
||||
"packages": packages,
|
||||
"python_lib_dir": os.path.normpath(get_path("platlib")),
|
||||
},
|
||||
)
|
||||
0
src/flask_debugtoolbar/py.typed
Normal file
112
src/flask_debugtoolbar/static/codemirror/codemirror.css
Normal file
@@ -0,0 +1,112 @@
|
||||
.CodeMirror {
|
||||
line-height: 1em;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.CodeMirror-scroll {
|
||||
overflow: auto;
|
||||
height: 300px;
|
||||
/* This is needed to prevent an IE[67] bug where the scrolled content
|
||||
is visible outside of the scrolling box. */
|
||||
position: relative;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.CodeMirror-gutter {
|
||||
position: absolute; left: 0; top: 0;
|
||||
z-index: 10;
|
||||
background-color: #f7f7f7;
|
||||
border-right: 1px solid #eee;
|
||||
min-width: 2em;
|
||||
height: 100%;
|
||||
}
|
||||
.CodeMirror-gutter-text {
|
||||
color: #aaa;
|
||||
text-align: right;
|
||||
padding: .4em .2em .4em .4em;
|
||||
white-space: pre !important;
|
||||
}
|
||||
.CodeMirror-lines {
|
||||
padding: .4em;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.CodeMirror pre {
|
||||
-moz-border-radius: 0;
|
||||
-webkit-border-radius: 0;
|
||||
-o-border-radius: 0;
|
||||
border-radius: 0;
|
||||
border-width: 0; margin: 0; padding: 0; background: transparent;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
padding: 0; margin: 0;
|
||||
white-space: pre;
|
||||
word-wrap: normal;
|
||||
}
|
||||
|
||||
.CodeMirror-wrap pre {
|
||||
word-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.CodeMirror-wrap .CodeMirror-scroll {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.CodeMirror textarea {
|
||||
outline: none !important;
|
||||
}
|
||||
|
||||
.CodeMirror pre.CodeMirror-cursor {
|
||||
z-index: 10;
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
border-left: 1px solid black;
|
||||
border-right:none;
|
||||
width:0;
|
||||
}
|
||||
.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
|
||||
.CodeMirror-focused pre.CodeMirror-cursor {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
div.CodeMirror-selected { background: #d9d9d9; }
|
||||
.CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
|
||||
|
||||
.CodeMirror-searching {
|
||||
background: #ffa;
|
||||
background: rgba(255, 255, 0, .4);
|
||||
}
|
||||
|
||||
/* Default theme */
|
||||
|
||||
.cm-s-default span.cm-keyword {color: #708;}
|
||||
.cm-s-default span.cm-atom {color: #219;}
|
||||
.cm-s-default span.cm-number {color: #164;}
|
||||
.cm-s-default span.cm-def {color: #00f;}
|
||||
.cm-s-default span.cm-variable {color: black;}
|
||||
.cm-s-default span.cm-variable-2 {color: #05a;}
|
||||
.cm-s-default span.cm-variable-3 {color: #085;}
|
||||
.cm-s-default span.cm-property {color: black;}
|
||||
.cm-s-default span.cm-operator {color: black;}
|
||||
.cm-s-default span.cm-comment {color: #a50;}
|
||||
.cm-s-default span.cm-string {color: #a11;}
|
||||
.cm-s-default span.cm-string-2 {color: #f50;}
|
||||
.cm-s-default span.cm-meta {color: #555;}
|
||||
.cm-s-default span.cm-error {color: #f00;}
|
||||
.cm-s-default span.cm-qualifier {color: #555;}
|
||||
.cm-s-default span.cm-builtin {color: #30a;}
|
||||
.cm-s-default span.cm-bracket {color: #cc7;}
|
||||
.cm-s-default span.cm-tag {color: #170;}
|
||||
.cm-s-default span.cm-attribute {color: #00c;}
|
||||
.cm-s-default span.cm-header {color: #a0a;}
|
||||
.cm-s-default span.cm-quote {color: #090;}
|
||||
.cm-s-default span.cm-hr {color: #999;}
|
||||
.cm-s-default span.cm-link {color: #00c;}
|
||||
|
||||
span.cm-header, span.cm-strong {font-weight: bold;}
|
||||
span.cm-em {font-style: italic;}
|
||||
span.cm-emstrong {font-style: italic; font-weight: bold;}
|
||||
span.cm-link {text-decoration: underline;}
|
||||
|
||||
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
|
||||
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
|
||||
2972
src/flask_debugtoolbar/static/codemirror/codemirror.js
Normal file
234
src/flask_debugtoolbar/static/codemirror/mode/clike/clike.js
vendored
Normal file
@@ -0,0 +1,234 @@
|
||||
CodeMirror.defineMode("clike", function(config, parserConfig) {
|
||||
var indentUnit = config.indentUnit,
|
||||
keywords = parserConfig.keywords || {},
|
||||
blockKeywords = parserConfig.blockKeywords || {},
|
||||
atoms = parserConfig.atoms || {},
|
||||
hooks = parserConfig.hooks || {},
|
||||
multiLineStrings = parserConfig.multiLineStrings;
|
||||
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
|
||||
|
||||
var curPunc;
|
||||
|
||||
function tokenBase(stream, state) {
|
||||
var ch = stream.next();
|
||||
if (hooks[ch]) {
|
||||
var result = hooks[ch](stream, state);
|
||||
if (result !== false) return result;
|
||||
}
|
||||
if (ch == '"' || ch == "'") {
|
||||
state.tokenize = tokenString(ch);
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
|
||||
curPunc = ch;
|
||||
return null
|
||||
}
|
||||
if (/\d/.test(ch)) {
|
||||
stream.eatWhile(/[\w\.]/);
|
||||
return "number";
|
||||
}
|
||||
if (ch == "/") {
|
||||
if (stream.eat("*")) {
|
||||
state.tokenize = tokenComment;
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (stream.eat("/")) {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
}
|
||||
if (isOperatorChar.test(ch)) {
|
||||
stream.eatWhile(isOperatorChar);
|
||||
return "operator";
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
var cur = stream.current();
|
||||
if (keywords.propertyIsEnumerable(cur)) {
|
||||
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
|
||||
return "keyword";
|
||||
}
|
||||
if (atoms.propertyIsEnumerable(cur)) return "atom";
|
||||
return "word";
|
||||
}
|
||||
|
||||
function tokenString(quote) {
|
||||
return function(stream, state) {
|
||||
var escaped = false, next, end = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == quote && !escaped) {end = true; break;}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
if (end || !(escaped || multiLineStrings))
|
||||
state.tokenize = null;
|
||||
return "string";
|
||||
};
|
||||
}
|
||||
|
||||
function tokenComment(stream, state) {
|
||||
var maybeEnd = false, ch;
|
||||
while (ch = stream.next()) {
|
||||
if (ch == "/" && maybeEnd) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
maybeEnd = (ch == "*");
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function Context(indented, column, type, align, prev) {
|
||||
this.indented = indented;
|
||||
this.column = column;
|
||||
this.type = type;
|
||||
this.align = align;
|
||||
this.prev = prev;
|
||||
}
|
||||
function pushContext(state, col, type) {
|
||||
return state.context = new Context(state.indented, col, type, null, state.context);
|
||||
}
|
||||
function popContext(state) {
|
||||
var t = state.context.type;
|
||||
if (t == ")" || t == "]" || t == "}")
|
||||
state.indented = state.context.indented;
|
||||
return state.context = state.context.prev;
|
||||
}
|
||||
|
||||
// Interface
|
||||
|
||||
return {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: null,
|
||||
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
|
||||
indented: 0,
|
||||
startOfLine: true
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var ctx = state.context;
|
||||
if (stream.sol()) {
|
||||
if (ctx.align == null) ctx.align = false;
|
||||
state.indented = stream.indentation();
|
||||
state.startOfLine = true;
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
curPunc = null;
|
||||
var style = (state.tokenize || tokenBase)(stream, state);
|
||||
if (style == "comment" || style == "meta") return style;
|
||||
if (ctx.align == null) ctx.align = true;
|
||||
|
||||
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
|
||||
else if (curPunc == "{") pushContext(state, stream.column(), "}");
|
||||
else if (curPunc == "[") pushContext(state, stream.column(), "]");
|
||||
else if (curPunc == "(") pushContext(state, stream.column(), ")");
|
||||
else if (curPunc == "}") {
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
if (ctx.type == "}") ctx = popContext(state);
|
||||
while (ctx.type == "statement") ctx = popContext(state);
|
||||
}
|
||||
else if (curPunc == ctx.type) popContext(state);
|
||||
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
|
||||
pushContext(state, stream.column(), "statement");
|
||||
state.startOfLine = false;
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
|
||||
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
|
||||
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
|
||||
var closing = firstChar == ctx.type;
|
||||
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
|
||||
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
|
||||
else return ctx.indented + (closing ? 0 : indentUnit);
|
||||
},
|
||||
|
||||
electricChars: "{}"
|
||||
};
|
||||
});
|
||||
|
||||
(function() {
|
||||
function words(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
|
||||
"double static else struct entry switch extern typedef float union for unsigned " +
|
||||
"goto while enum void const signed volatile";
|
||||
|
||||
function cppHook(stream, state) {
|
||||
if (!state.startOfLine) return false;
|
||||
stream.skipToEnd();
|
||||
return "meta";
|
||||
}
|
||||
|
||||
// C#-style strings where "" escapes a quote.
|
||||
function tokenAtString(stream, state) {
|
||||
var next;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == '"' && !stream.eat('"')) {
|
||||
state.tokenize = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return "string";
|
||||
}
|
||||
|
||||
CodeMirror.defineMIME("text/x-csrc", {
|
||||
name: "clike",
|
||||
keywords: words(cKeywords),
|
||||
blockKeywords: words("case do else for if switch while struct"),
|
||||
atoms: words("null"),
|
||||
hooks: {"#": cppHook}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-c++src", {
|
||||
name: "clike",
|
||||
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
|
||||
"static_cast typeid catch operator template typename class friend private " +
|
||||
"this using const_cast inline public throw virtual delete mutable protected " +
|
||||
"wchar_t"),
|
||||
blockKeywords: words("catch class do else finally for if struct switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {"#": cppHook}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-java", {
|
||||
name: "clike",
|
||||
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
|
||||
"do double else enum extends final finally float for goto if implements import " +
|
||||
"instanceof int interface long native new package private protected public " +
|
||||
"return short static strictfp super switch synchronized this throw throws transient " +
|
||||
"try void volatile while"),
|
||||
blockKeywords: words("catch class do else finally for if switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {
|
||||
"@": function(stream, state) {
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
CodeMirror.defineMIME("text/x-csharp", {
|
||||
name: "clike",
|
||||
keywords: words("abstract as base bool break byte case catch char checked class const continue decimal" +
|
||||
" default delegate do double else enum event explicit extern finally fixed float for" +
|
||||
" foreach goto if implicit in int interface internal is lock long namespace new object" +
|
||||
" operator out override params private protected public readonly ref return sbyte sealed short" +
|
||||
" sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked" +
|
||||
" unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" +
|
||||
" global group into join let orderby partial remove select set value var yield"),
|
||||
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
|
||||
atoms: words("true false null"),
|
||||
hooks: {
|
||||
"@": function(stream, state) {
|
||||
if (stream.eat('"')) {
|
||||
state.tokenize = tokenAtString;
|
||||
return tokenAtString(stream, state);
|
||||
}
|
||||
stream.eatWhile(/[\w\$_]/);
|
||||
return "meta";
|
||||
}
|
||||
}
|
||||
});
|
||||
}());
|
||||
101
src/flask_debugtoolbar/static/codemirror/mode/clike/index.html
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>CodeMirror: C-like mode</title>
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="clike.js"></script>
|
||||
<link rel="stylesheet" href="../../doc/docs.css">
|
||||
<style>.CodeMirror {border: 2px inset #dee;}</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>CodeMirror: C-like mode</h1>
|
||||
|
||||
<form><textarea id="code" name="code">
|
||||
/* C demo code */
|
||||
|
||||
#include <zmq.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
#include <fcntl.h>
|
||||
#include <malloc.h>
|
||||
|
||||
typedef struct {
|
||||
void* arg_socket;
|
||||
zmq_msg_t* arg_msg;
|
||||
char* arg_string;
|
||||
unsigned long arg_len;
|
||||
int arg_int, arg_command;
|
||||
|
||||
int signal_fd;
|
||||
int pad;
|
||||
void* context;
|
||||
sem_t sem;
|
||||
} acl_zmq_context;
|
||||
|
||||
#define p(X) (context->arg_##X)
|
||||
|
||||
void* zmq_thread(void* context_pointer) {
|
||||
acl_zmq_context* context = (acl_zmq_context*)context_pointer;
|
||||
char ok = 'K', err = 'X';
|
||||
int res;
|
||||
|
||||
while (1) {
|
||||
while ((res = sem_wait(&context->sem)) == EINTR);
|
||||
if (res) {write(context->signal_fd, &err, 1); goto cleanup;}
|
||||
switch(p(command)) {
|
||||
case 0: goto cleanup;
|
||||
case 1: p(socket) = zmq_socket(context->context, p(int)); break;
|
||||
case 2: p(int) = zmq_close(p(socket)); break;
|
||||
case 3: p(int) = zmq_bind(p(socket), p(string)); break;
|
||||
case 4: p(int) = zmq_connect(p(socket), p(string)); break;
|
||||
case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break;
|
||||
case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
|
||||
case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
|
||||
case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
|
||||
case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
|
||||
}
|
||||
p(command) = errno;
|
||||
write(context->signal_fd, &ok, 1);
|
||||
}
|
||||
cleanup:
|
||||
close(context->signal_fd);
|
||||
free(context_pointer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void* zmq_thread_init(void* zmq_context, int signal_fd) {
|
||||
acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
|
||||
pthread_t thread;
|
||||
|
||||
context->context = zmq_context;
|
||||
context->signal_fd = signal_fd;
|
||||
sem_init(&context->sem, 1, 0);
|
||||
pthread_create(&thread, 0, &zmq_thread, context);
|
||||
pthread_detach(thread);
|
||||
return context;
|
||||
}
|
||||
</textarea></form>
|
||||
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
|
||||
lineNumbers: true,
|
||||
matchBrackets: true,
|
||||
mode: "text/x-csrc"
|
||||
});
|
||||
</script>
|
||||
|
||||
<p>Simple mode that tries to handle C-like languages as well as it
|
||||
can. Takes two configuration parameters: <code>keywords</code>, an
|
||||
object whose property names are the keywords in the language,
|
||||
and <code>useCPP</code>, which determines whether C preprocessor
|
||||
directives are recognized.</p>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
|
||||
(C code), <code>text/x-c++src</code> (C++
|
||||
code), <code>text/x-java</code> (Java
|
||||
code), <code>text/x-csharp</code> (C#).</p>
|
||||
</body>
|
||||
</html>
|
||||
207
src/flask_debugtoolbar/static/codemirror/mode/clojure/clojure.js
vendored
Normal file
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* Author: Hans Engel
|
||||
* Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
|
||||
*/
|
||||
CodeMirror.defineMode("clojure", function (config, mode) {
|
||||
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", TAG = "tag",
|
||||
ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
|
||||
var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
|
||||
|
||||
function makeKeywords(str) {
|
||||
var obj = {}, words = str.split(" ");
|
||||
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
var atoms = makeKeywords("true false nil");
|
||||
|
||||
var keywords = makeKeywords(
|
||||
"defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");
|
||||
|
||||
var builtins = makeKeywords(
|
||||
"* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq");
|
||||
|
||||
var indentKeys = makeKeywords(
|
||||
// Built-ins
|
||||
"ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +
|
||||
|
||||
// Binding forms
|
||||
"let letfn binding loop for doseq dotimes when-let if-let " +
|
||||
|
||||
// Data structures
|
||||
"defstruct struct-map assoc " +
|
||||
|
||||
// clojure.test
|
||||
"testing deftest " +
|
||||
|
||||
// contrib
|
||||
"handler-case handle dotrace deftrace");
|
||||
|
||||
var tests = {
|
||||
digit: /\d/,
|
||||
digit_or_colon: /[\d:]/,
|
||||
hex: /[0-9a-fA-F]/,
|
||||
sign: /[+-]/,
|
||||
exponent: /[eE]/,
|
||||
keyword_char: /[^\s\(\[\;\)\]]/,
|
||||
basic: /[\w\$_\-]/,
|
||||
lang_keyword: /[\w*+!\-_?:\/]/
|
||||
};
|
||||
|
||||
function stateStack(indent, type, prev) { // represents a state stack object
|
||||
this.indent = indent;
|
||||
this.type = type;
|
||||
this.prev = prev;
|
||||
}
|
||||
|
||||
function pushStack(state, indent, type) {
|
||||
state.indentStack = new stateStack(indent, type, state.indentStack);
|
||||
}
|
||||
|
||||
function popStack(state) {
|
||||
state.indentStack = state.indentStack.prev;
|
||||
}
|
||||
|
||||
function isNumber(ch, stream){
|
||||
// hex
|
||||
if ( ch === '0' && 'x' == stream.peek().toLowerCase() ) {
|
||||
stream.eat('x');
|
||||
stream.eatWhile(tests.hex);
|
||||
return true;
|
||||
}
|
||||
|
||||
// leading sign
|
||||
if ( ch == '+' || ch == '-' ) {
|
||||
stream.eat(tests.sign);
|
||||
ch = stream.next();
|
||||
}
|
||||
|
||||
if ( tests.digit.test(ch) ) {
|
||||
stream.eat(ch);
|
||||
stream.eatWhile(tests.digit);
|
||||
|
||||
if ( '.' == stream.peek() ) {
|
||||
stream.eat('.');
|
||||
stream.eatWhile(tests.digit);
|
||||
}
|
||||
|
||||
if ( 'e' == stream.peek().toLowerCase() ) {
|
||||
stream.eat(tests.exponent);
|
||||
stream.eat(tests.sign);
|
||||
stream.eatWhile(tests.digit);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
startState: function () {
|
||||
return {
|
||||
indentStack: null,
|
||||
indentation: 0,
|
||||
mode: false
|
||||
};
|
||||
},
|
||||
|
||||
token: function (stream, state) {
|
||||
if (state.indentStack == null && stream.sol()) {
|
||||
// update indentation, but only if indentStack is empty
|
||||
state.indentation = stream.indentation();
|
||||
}
|
||||
|
||||
// skip spaces
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
var returnType = null;
|
||||
|
||||
switch(state.mode){
|
||||
case "string": // multi-line string parsing mode
|
||||
var next, escaped = false;
|
||||
while ((next = stream.next()) != null) {
|
||||
if (next == "\"" && !escaped) {
|
||||
|
||||
state.mode = false;
|
||||
break;
|
||||
}
|
||||
escaped = !escaped && next == "\\";
|
||||
}
|
||||
returnType = STRING; // continue on in string mode
|
||||
break;
|
||||
default: // default parsing mode
|
||||
var ch = stream.next();
|
||||
|
||||
if (ch == "\"") {
|
||||
state.mode = "string";
|
||||
returnType = STRING;
|
||||
} else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
|
||||
returnType = ATOM;
|
||||
} else if (ch == ";") { // comment
|
||||
stream.skipToEnd(); // rest of the line is a comment
|
||||
returnType = COMMENT;
|
||||
} else if (isNumber(ch,stream)){
|
||||
returnType = NUMBER;
|
||||
} else if (ch == "(" || ch == "[") {
|
||||
var keyWord = ''; var indentTemp = stream.column();
|
||||
/**
|
||||
Either
|
||||
(indent-word ..
|
||||
(non-indent-word ..
|
||||
(;something else, bracket, etc.
|
||||
*/
|
||||
|
||||
if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
|
||||
keyWord += letter;
|
||||
}
|
||||
|
||||
if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
|
||||
pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
|
||||
} else { // non-indent word
|
||||
// we continue eating the spaces
|
||||
stream.eatSpace();
|
||||
if (stream.eol() || stream.peek() == ";") {
|
||||
// nothing significant after
|
||||
// we restart indentation 1 space after
|
||||
pushStack(state, indentTemp + 1, ch);
|
||||
} else {
|
||||
pushStack(state, indentTemp + stream.current().length, ch); // else we match
|
||||
}
|
||||
}
|
||||
stream.backUp(stream.current().length - 1); // undo all the eating
|
||||
|
||||
returnType = BRACKET;
|
||||
} else if (ch == ")" || ch == "]") {
|
||||
returnType = BRACKET;
|
||||
if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
|
||||
popStack(state);
|
||||
}
|
||||
} else if ( ch == ":" ) {
|
||||
stream.eatWhile(tests.lang_keyword);
|
||||
return ATOM;
|
||||
} else {
|
||||
stream.eatWhile(tests.basic);
|
||||
|
||||
if (keywords && keywords.propertyIsEnumerable(stream.current())) {
|
||||
returnType = KEYWORD;
|
||||
} else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
|
||||
returnType = BUILTIN;
|
||||
} else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
|
||||
returnType = ATOM;
|
||||
} else returnType = null;
|
||||
}
|
||||
}
|
||||
|
||||
return returnType;
|
||||
},
|
||||
|
||||
indent: function (state, textAfter) {
|
||||
if (state.indentStack == null) return state.indentation;
|
||||
return state.indentStack.indent;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME("text/x-clojure", "clojure");
|
||||
66
src/flask_debugtoolbar/static/codemirror/mode/clojure/index.html
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>CodeMirror: Clojure mode</title>
|
||||
<link rel="stylesheet" href="../../lib/codemirror.css">
|
||||
<script src="../../lib/codemirror.js"></script>
|
||||
<script src="clojure.js"></script>
|
||||
<style>.CodeMirror {background: #f8f8f8;}</style>
|
||||
<link rel="stylesheet" href="../../doc/docs.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>CodeMirror: Clojure mode</h1>
|
||||
<form><textarea id="code" name="code">
|
||||
; Conway's Game of Life, based on the work of:
|
||||
;; Laurent Petit https://gist.github.com/1200343
|
||||
;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
|
||||
|
||||
(ns ^{:doc "Conway's Game of Life."}
|
||||
game-of-life)
|
||||
|
||||
;; Core game of life's algorithm functions
|
||||
|
||||
(defn neighbours
|
||||
"Given a cell's coordinates, returns the coordinates of its neighbours."
|
||||
[[x y]]
|
||||
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
|
||||
[(+ dx x) (+ dy y)]))
|
||||
|
||||
(defn step
|
||||
"Given a set of living cells, computes the new set of living cells."
|
||||
[cells]
|
||||
(set (for [[cell n] (frequencies (mapcat neighbours cells))
|
||||
:when (or (= n 3) (and (= n 2) (cells cell)))]
|
||||
cell)))
|
||||
|
||||
;; Utility methods for displaying game on a text terminal
|
||||
|
||||
(defn print-board
|
||||
"Prints a board on *out*, representing a step in the game."
|
||||
[board w h]
|
||||
(doseq [x (range (inc w)) y (range (inc h))]
|
||||
(if (= y 0) (print "\n"))
|
||||
(print (if (board [x y]) "[X]" " . "))))
|
||||
|
||||
(defn display-grids
|
||||
"Prints a squence of boards on *out*, representing several steps."
|
||||
[grids w h]
|
||||
(doseq [board grids]
|
||||
(print-board board w h)
|
||||
(print "\n")))
|
||||
|
||||
;; Launches an example board
|
||||
|
||||
(def
|
||||
^{:doc "board represents the initial set of living cells"}
|
||||
board #{[2 1] [2 2] [2 3]})
|
||||
|
||||
(display-grids (take 3 (iterate step board)) 5 5) </textarea></form>
|
||||
<script>
|
||||
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
|
||||
</script>
|
||||
|
||||
<p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
22
src/flask_debugtoolbar/static/codemirror/mode/coffeescript/LICENSE
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2011 Jeff Pickhardt
|
||||
Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
341
src/flask_debugtoolbar/static/codemirror/mode/coffeescript/coffeescript.js
vendored
Normal file
@@ -0,0 +1,341 @@
|
||||
/**
|
||||
* Link to the project's GitHub page:
|
||||
* https://github.com/pickhardt/coffeescript-codemirror-mode
|
||||
*/
|
||||
CodeMirror.defineMode('coffeescript', function(conf) {
|
||||
var ERRORCLASS = 'error';
|
||||
|
||||
function wordRegexp(words) {
|
||||
return new RegExp("^((" + words.join(")|(") + "))\\b");
|
||||
}
|
||||
|
||||
var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
|
||||
var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
|
||||
var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
|
||||
var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
|
||||
var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
|
||||
var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*");
|
||||
|
||||
var wordOperators = wordRegexp(['and', 'or', 'not',
|
||||
'is', 'isnt', 'in',
|
||||
'instanceof', 'typeof']);
|
||||
var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
|
||||
'switch', 'try', 'catch', 'finally', 'class'];
|
||||
var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
|
||||
'do', 'in', 'of', 'new', 'return', 'then',
|
||||
'this', 'throw', 'when', 'until'];
|
||||
|
||||
var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
|
||||
|
||||
indentKeywords = wordRegexp(indentKeywords);
|
||||
|
||||
|
||||
var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
|
||||
var regexPrefixes = new RegExp("^(/{3}|/)");
|
||||
var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
|
||||
var constants = wordRegexp(commonConstants);
|
||||
|
||||
// Tokenizers
|
||||
function tokenBase(stream, state) {
|
||||
// Handle scope changes
|
||||
if (stream.sol()) {
|
||||
var scopeOffset = state.scopes[0].offset;
|
||||
if (stream.eatSpace()) {
|
||||
var lineOffset = stream.indentation();
|
||||
if (lineOffset > scopeOffset) {
|
||||
return 'indent';
|
||||
} else if (lineOffset < scopeOffset) {
|
||||
return 'dedent';
|
||||
}
|
||||
return null;
|
||||
} else {
|
||||
if (scopeOffset > 0) {
|
||||
dedent(stream, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stream.eatSpace()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var ch = stream.peek();
|
||||
|
||||
// Handle multi line comments
|
||||
if (stream.match("###")) {
|
||||
state.tokenize = longComment;
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
|
||||
// Single line comment
|
||||
if (ch === '#') {
|
||||
stream.skipToEnd();
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
// Handle number literals
|
||||
if (stream.match(/^-?[0-9\.]/, false)) {
|
||||
var floatLiteral = false;
|
||||
// Floats
|
||||
if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
if (stream.match(/^-?\d+\.\d*/)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
if (stream.match(/^-?\.\d+/)) {
|
||||
floatLiteral = true;
|
||||
}
|
||||
|
||||
if (floatLiteral) {
|
||||
// prevent from getting extra . on 1..
|
||||
if (stream.peek() == "."){
|
||||
stream.backUp(1);
|
||||
}
|
||||
return 'number';
|
||||
}
|
||||
// Integers
|
||||
var intLiteral = false;
|
||||
// Hex
|
||||
if (stream.match(/^-?0x[0-9a-f]+/i)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
// Decimal
|
||||
if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
// Zero by itself with no other piece of number.
|
||||
if (stream.match(/^-?0(?![\dx])/i)) {
|
||||
intLiteral = true;
|
||||
}
|
||||
if (intLiteral) {
|
||||
return 'number';
|
||||
}
|
||||
}
|
||||
|
||||
// Handle strings
|
||||
if (stream.match(stringPrefixes)) {
|
||||
state.tokenize = tokenFactory(stream.current(), 'string');
|
||||
return state.tokenize(stream, state);
|
||||
}
|
||||
// Handle regex literals
|
||||
if (stream.match(regexPrefixes)) {
|
||||
if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
|
||||
state.tokenize = tokenFactory(stream.current(), 'string-2');
|
||||
return state.tokenize(stream, state);
|
||||
} else {
|
||||
stream.backUp(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle operators and delimiters
|
||||
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
|
||||
return 'punctuation';
|
||||
}
|
||||
if (stream.match(doubleOperators)
|
||||
|| stream.match(singleOperators)
|
||||
|| stream.match(wordOperators)) {
|
||||
return 'operator';
|
||||
}
|
||||
if (stream.match(singleDelimiters)) {
|
||||
return 'punctuation';
|
||||
}
|
||||
|
||||
if (stream.match(constants)) {
|
||||
return 'atom';
|
||||
}
|
||||
|
||||
if (stream.match(keywords)) {
|
||||
return 'keyword';
|
||||
}
|
||||
|
||||
if (stream.match(identifiers)) {
|
||||
return 'variable';
|
||||
}
|
||||
|
||||
// Handle non-detected items
|
||||
stream.next();
|
||||
return ERRORCLASS;
|
||||
}
|
||||
|
||||
function tokenFactory(delimiter, outclass) {
|
||||
var singleline = delimiter.length == 1;
|
||||
return function tokenString(stream, state) {
|
||||
while (!stream.eol()) {
|
||||
stream.eatWhile(/[^'"\/\\]/);
|
||||
if (stream.eat('\\')) {
|
||||
stream.next();
|
||||
if (singleline && stream.eol()) {
|
||||
return outclass;
|
||||
}
|
||||
} else if (stream.match(delimiter)) {
|
||||
state.tokenize = tokenBase;
|
||||
return outclass;
|
||||
} else {
|
||||
stream.eat(/['"\/]/);
|
||||
}
|
||||
}
|
||||
if (singleline) {
|
||||
if (conf.mode.singleLineStringErrors) {
|
||||
outclass = ERRORCLASS
|
||||
} else {
|
||||
state.tokenize = tokenBase;
|
||||
}
|
||||
}
|
||||
return outclass;
|
||||
};
|
||||
}
|
||||
|
||||
function longComment(stream, state) {
|
||||
while (!stream.eol()) {
|
||||
stream.eatWhile(/[^#]/);
|
||||
if (stream.match("###")) {
|
||||
state.tokenize = tokenBase;
|
||||
break;
|
||||
}
|
||||
stream.eatWhile("#");
|
||||
}
|
||||
return "comment"
|
||||
}
|
||||
|
||||
function indent(stream, state, type) {
|
||||
type = type || 'coffee';
|
||||
var indentUnit = 0;
|
||||
if (type === 'coffee') {
|
||||
for (var i = 0; i < state.scopes.length; i++) {
|
||||
if (state.scopes[i].type === 'coffee') {
|
||||
indentUnit = state.scopes[i].offset + conf.indentUnit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
indentUnit = stream.column() + stream.current().length;
|
||||
}
|
||||
state.scopes.unshift({
|
||||
offset: indentUnit,
|
||||
type: type
|
||||
});
|
||||
}
|
||||
|
||||
function dedent(stream, state) {
|
||||
if (state.scopes.length == 1) return;
|
||||
if (state.scopes[0].type === 'coffee') {
|
||||
var _indent = stream.indentation();
|
||||
var _indent_index = -1;
|
||||
for (var i = 0; i < state.scopes.length; ++i) {
|
||||
if (_indent === state.scopes[i].offset) {
|
||||
_indent_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (_indent_index === -1) {
|
||||
return true;
|
||||
}
|
||||
while (state.scopes[0].offset !== _indent) {
|
||||
state.scopes.shift();
|
||||
}
|
||||
return false
|
||||
} else {
|
||||
state.scopes.shift();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tokenLexer(stream, state) {
|
||||
var style = state.tokenize(stream, state);
|
||||
var current = stream.current();
|
||||
|
||||
// Handle '.' connected identifiers
|
||||
if (current === '.') {
|
||||
style = state.tokenize(stream, state);
|
||||
current = stream.current();
|
||||
if (style === 'variable') {
|
||||
return 'variable';
|
||||
} else {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle properties
|
||||
if (current === '@') {
|
||||
stream.eat('@');
|
||||
return 'keyword';
|
||||
}
|
||||
|
||||
// Handle scope changes.
|
||||
if (current === 'return') {
|
||||
state.dedent += 1;
|
||||
}
|
||||
if (((current === '->' || current === '=>') &&
|
||||
!state.lambda &&
|
||||
state.scopes[0].type == 'coffee' &&
|
||||
stream.peek() === '')
|
||||
|| style === 'indent') {
|
||||
indent(stream, state);
|
||||
}
|
||||
var delimiter_index = '[({'.indexOf(current);
|
||||
if (delimiter_index !== -1) {
|
||||
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
|
||||
}
|
||||
if (indentKeywords.exec(current)){
|
||||
indent(stream, state);
|
||||
}
|
||||
if (current == 'then'){
|
||||
dedent(stream, state);
|
||||
}
|
||||
|
||||
|
||||
if (style === 'dedent') {
|
||||
if (dedent(stream, state)) {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
delimiter_index = '])}'.indexOf(current);
|
||||
if (delimiter_index !== -1) {
|
||||
if (dedent(stream, state)) {
|
||||
return ERRORCLASS;
|
||||
}
|
||||
}
|
||||
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
|
||||
if (state.scopes.length > 1) state.scopes.shift();
|
||||
state.dedent -= 1;
|
||||
}
|
||||
|
||||
return style;
|
||||
}
|
||||
|
||||
var external = {
|
||||
startState: function(basecolumn) {
|
||||
return {
|
||||
tokenize: tokenBase,
|
||||
scopes: [{offset:basecolumn || 0, type:'coffee'}],
|
||||
lastToken: null,
|
||||
lambda: false,
|
||||
dedent: 0
|
||||
};
|
||||
},
|
||||
|
||||
token: function(stream, state) {
|
||||
var style = tokenLexer(stream, state);
|
||||
|
||||
state.lastToken = {style:style, content: stream.current()};
|
||||
|
||||
if (stream.eol() && stream.lambda) {
|
||||
state.lambda = false;
|
||||
}
|
||||
|
||||
return style;
|
||||
},
|
||||
|
||||
indent: function(state, textAfter) {
|
||||
if (state.tokenize != tokenBase) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return state.scopes[0].offset;
|
||||
}
|
||||
|
||||
};
|
||||
return external;
|
||||
});
|
||||
|
||||
CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
|
||||