{"repo":"flask","file":".editorconfig","line":1,"symbol":"root","kind":"field","lang":"editorconfig","code":"root = true"} {"repo":"flask","file":".editorconfig","line":3,"symbol":"[*]\n","kind":"section","lang":"editorconfig","code":"[*]\nindent_style = space\nindent_size = 4\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nend_of_line = lf\ncharset = utf-8\nmax_line_length = 88"} {"repo":"flask","file":".editorconfig","line":4,"symbol":"indent_style","kind":"field","lang":"editorconfig","code":"indent_style = space"} {"repo":"flask","file":".editorconfig","line":5,"symbol":"indent_size","kind":"field","lang":"editorconfig","code":"indent_size = 4"} {"repo":"flask","file":".editorconfig","line":6,"symbol":"insert_final_newline","kind":"field","lang":"editorconfig","code":"insert_final_newline = true"} {"repo":"flask","file":".editorconfig","line":7,"symbol":"trim_trailing_whitespace","kind":"field","lang":"editorconfig","code":"trim_trailing_whitespace = true"} {"repo":"flask","file":".editorconfig","line":8,"symbol":"end_of_line","kind":"field","lang":"editorconfig","code":"end_of_line = lf"} {"repo":"flask","file":".editorconfig","line":9,"symbol":"charset","kind":"field","lang":"editorconfig","code":"charset = utf-8"} {"repo":"flask","file":".editorconfig","line":10,"symbol":"max_line_length","kind":"field","lang":"editorconfig","code":"max_line_length = 88"} {"repo":"flask","file":".editorconfig","line":12,"symbol":"[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]\n","kind":"section","lang":"editorconfig","code":"[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]\nindent_size = 2"} {"repo":"flask","file":".editorconfig","line":13,"symbol":"indent_size","kind":"field","lang":"editorconfig","code":"indent_size = 2"} {"repo":"flask","file":"CHANGES.rst","line":1,"symbol":"Version 3.2.0","kind":"section","lang":"rst","code":"Version 3.2.0\n-------------"} {"repo":"flask","file":"docs/Makefile","line":6,"symbol":"SPHINXOPTS","kind":"variable","lang":"make","code":"SPHINXOPTS ?="} {"repo":"flask","file":"docs/Makefile","line":7,"symbol":"SPHINXBUILD","kind":"variable","lang":"make","code":"SPHINXBUILD ?= sphinx-build"} {"repo":"flask","file":"docs/Makefile","line":8,"symbol":"SOURCEDIR","kind":"variable","lang":"make","code":"SOURCEDIR = ."} {"repo":"flask","file":"docs/Makefile","line":9,"symbol":"BUILDDIR","kind":"variable","lang":"make","code":"BUILDDIR = _build"} {"repo":"flask","file":"docs/Makefile","line":12,"symbol":"help","kind":"target","lang":"make","code":"help:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)"} {"repo":"flask","file":"docs/Makefile","line":15,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: help Makefile"} {"repo":"flask","file":"docs/Makefile","line":19,"symbol":"%","kind":"target","lang":"make","code":"%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)"} {"repo":"flask","file":"docs/api.rst","line":1,"symbol":"API","kind":"section","lang":"rst","code":"API\n==="} {"repo":"flask","file":"docs/api.rst","line":11,"symbol":"Application Object","kind":"section","lang":"rst","code":"Application Object\n------------------"} {"repo":"flask","file":"docs/api.rst","line":19,"symbol":"Blueprint Objects","kind":"section","lang":"rst","code":"Blueprint Objects\n-----------------"} {"repo":"flask","file":"docs/api.rst","line":26,"symbol":"Incoming Request Data","kind":"section","lang":"rst","code":"Incoming Request Data\n---------------------"} {"repo":"flask","file":"docs/api.rst","line":45,"symbol":"Response Objects","kind":"section","lang":"rst","code":"Response Objects\n----------------"} {"repo":"flask","file":"docs/api.rst","line":53,"symbol":"Sessions","kind":"section","lang":"rst","code":"Sessions\n--------"} {"repo":"flask","file":"docs/api.rst","line":92,"symbol":"Session Interface","kind":"section","lang":"rst","code":"Session Interface\n-----------------"} {"repo":"flask","file":"docs/api.rst","line":124,"symbol":"Test Client","kind":"section","lang":"rst","code":"Test Client\n-----------"} {"repo":"flask","file":"docs/api.rst","line":133,"symbol":"Test CLI Runner","kind":"section","lang":"rst","code":"Test CLI Runner\n---------------"} {"repo":"flask","file":"docs/api.rst","line":142,"symbol":"Application Globals","kind":"section","lang":"rst","code":"Application Globals\n-------------------"} {"repo":"flask","file":"docs/appcontext.rst","line":1,"symbol":"The App and Request Context","kind":"section","lang":"rst","code":"The App and Request Context\n==========================="} {"repo":"flask","file":"docs/appcontext.rst","line":16,"symbol":"Purpose of the Context","kind":"section","lang":"rst","code":"Purpose of the Context\n----------------------"} {"repo":"flask","file":"docs/async-await.rst","line":3,"symbol":"Using ``async`` and ``await``","kind":"section","lang":"rst","code":"Using ``async`` and ``await``\n============================="} {"repo":"flask","file":"docs/async-await.rst","line":27,"symbol":"Performance","kind":"section","lang":"rst","code":"Performance\n-----------"} {"repo":"flask","file":"docs/async-await.rst","line":48,"symbol":"Background tasks","kind":"section","lang":"rst","code":"Background tasks\n----------------"} {"repo":"flask","file":"docs/async-await.rst","line":65,"symbol":"When to use Quart instead","kind":"section","lang":"rst","code":"When to use Quart instead\n-------------------------"} {"repo":"flask","file":"docs/async-await.rst","line":86,"symbol":"Extensions","kind":"section","lang":"rst","code":"Extensions\n----------"} {"repo":"flask","file":"docs/async-await.rst","line":114,"symbol":"Other event loops","kind":"section","lang":"rst","code":"Other event loops\n-----------------"} {"repo":"flask","file":"docs/blueprints.rst","line":1,"symbol":"Modular Applications with Blueprints","kind":"section","lang":"rst","code":"Modular Applications with Blueprints\n===================================="} {"repo":"flask","file":"docs/blueprints.rst","line":16,"symbol":"Why Blueprints?","kind":"section","lang":"rst","code":"Why Blueprints?\n---------------"} {"repo":"flask","file":"docs/changes.rst","line":1,"symbol":"Changes","kind":"section","lang":"rst","code":"Changes\n======="} {"repo":"flask","file":"docs/cli.rst","line":3,"symbol":"Command Line Interface","kind":"section","lang":"rst","code":"Command Line Interface\n======================"} {"repo":"flask","file":"docs/cli.rst","line":14,"symbol":"Application Discovery","kind":"section","lang":"rst","code":"Application Discovery\n---------------------"} {"repo":"flask","file":"docs/conf.py","line":72,"symbol":"github_link","kind":"function","lang":"python","code":"def github_link(name, rawtext, text, lineno, inliner, options=None, content=None):\n app = inliner.document.settings.env.app\n release = app.config.release\n base_url = \"https://github.com/pallets/flask/tree/\"\n\n if text.endswith(\">\"):\n words, text = text[:-1].rsplit(\"<\", 1)\n words = words.strip()\n else:\n words = None\n\n if packaging.version.parse(release).is_devrelease:\n url = f\"{base_url}main/{text}\"\n else:\n url = f\"{base_url}{release}/{text}\"\n\n if words is None:\n words = url\n\n from docutils.nodes import reference\n from docutils.parsers.rst.roles import set_classes\n\n options = options or {}\n set_classes(options)\n node = reference(rawtext, words, refuri=url, **options)\n return [node], []"} {"repo":"flask","file":"docs/conf.py","line":100,"symbol":"setup","kind":"function","lang":"python","code":"def setup(app):\n app.add_role(\"gh\", github_link)"} {"repo":"flask","file":"docs/config.rst","line":1,"symbol":"Configuration Handling","kind":"section","lang":"rst","code":"Configuration Handling\n======================"} {"repo":"flask","file":"docs/contributing.rst","line":1,"symbol":"Contributing","kind":"section","lang":"rst","code":"Contributing\n============"} {"repo":"flask","file":"docs/debugging.rst","line":1,"symbol":"Debugging Application Errors","kind":"section","lang":"rst","code":"Debugging Application Errors\n============================"} {"repo":"flask","file":"docs/debugging.rst","line":5,"symbol":"In Production","kind":"section","lang":"rst","code":"In Production\n-------------"} {"repo":"flask","file":"docs/debugging.rst","line":23,"symbol":"The Built-In Debugger","kind":"section","lang":"rst","code":"The Built-In Debugger\n---------------------"} {"repo":"flask","file":"docs/debugging.rst","line":60,"symbol":"External Debuggers","kind":"section","lang":"rst","code":"External Debuggers\n------------------"} {"repo":"flask","file":"docs/deploying/apache-httpd.rst","line":1,"symbol":"Apache httpd","kind":"section","lang":"rst","code":"Apache httpd\n============"} {"repo":"flask","file":"docs/deploying/apache-httpd.rst","line":19,"symbol":"Domain Name","kind":"section","lang":"rst","code":"Domain Name\n-----------"} {"repo":"flask","file":"docs/deploying/apache-httpd.rst","line":41,"symbol":"Configuration","kind":"section","lang":"rst","code":"Configuration\n-------------"} {"repo":"flask","file":"docs/deploying/asgi.rst","line":1,"symbol":"ASGI","kind":"section","lang":"rst","code":"ASGI\n===="} {"repo":"flask","file":"docs/deploying/eventlet.rst","line":3,"symbol":"eventlet","kind":"section","lang":"rst","code":"eventlet\n========"} {"repo":"flask","file":"docs/deploying/gevent.rst","line":1,"symbol":"gevent","kind":"section","lang":"rst","code":"gevent\n======"} {"repo":"flask","file":"docs/deploying/gevent.rst","line":21,"symbol":"Installing","kind":"section","lang":"rst","code":"Installing\n----------"} {"repo":"flask","file":"docs/deploying/gevent.rst","line":38,"symbol":"Running","kind":"section","lang":"rst","code":"Running\n-------"} {"repo":"flask","file":"docs/deploying/gevent.rst","line":61,"symbol":"Binding Externally","kind":"section","lang":"rst","code":"Binding Externally\n------------------"} {"repo":"flask","file":"docs/deploying/gunicorn.rst","line":1,"symbol":"Gunicorn","kind":"section","lang":"rst","code":"Gunicorn\n========"} {"repo":"flask","file":"docs/deploying/gunicorn.rst","line":21,"symbol":"Installing","kind":"section","lang":"rst","code":"Installing\n----------"} {"repo":"flask","file":"docs/deploying/gunicorn.rst","line":39,"symbol":"Running","kind":"section","lang":"rst","code":"Running\n-------"} {"repo":"flask","file":"docs/deploying/gunicorn.rst","line":74,"symbol":"Binding Externally","kind":"section","lang":"rst","code":"Binding Externally\n------------------"} {"repo":"flask","file":"docs/deploying/gunicorn.rst","line":96,"symbol":"Async with gevent","kind":"section","lang":"rst","code":"Async with gevent\n-----------------"} {"repo":"flask","file":"docs/deploying/index.rst","line":1,"symbol":"Deploying to Production","kind":"section","lang":"rst","code":"Deploying to Production\n======================="} {"repo":"flask","file":"docs/deploying/index.rst","line":17,"symbol":"Self-Hosted Options","kind":"section","lang":"rst","code":"Self-Hosted Options\n-------------------"} {"repo":"flask","file":"docs/deploying/index.rst","line":57,"symbol":"Hosting Platforms","kind":"section","lang":"rst","code":"Hosting Platforms\n-----------------"} {"repo":"flask","file":"docs/deploying/mod_wsgi.rst","line":1,"symbol":"mod_wsgi","kind":"section","lang":"rst","code":"mod_wsgi\n========"} {"repo":"flask","file":"docs/deploying/mod_wsgi.rst","line":23,"symbol":"Installing","kind":"section","lang":"rst","code":"Installing\n----------"} {"repo":"flask","file":"docs/deploying/mod_wsgi.rst","line":42,"symbol":"Running","kind":"section","lang":"rst","code":"Running\n-------"} {"repo":"flask","file":"docs/deploying/mod_wsgi.rst","line":78,"symbol":"Binding Externally","kind":"section","lang":"rst","code":"Binding Externally\n------------------"} {"repo":"flask","file":"docs/deploying/nginx.rst","line":1,"symbol":"nginx","kind":"section","lang":"rst","code":"nginx\n====="} {"repo":"flask","file":"docs/deploying/nginx.rst","line":19,"symbol":"Domain Name","kind":"section","lang":"rst","code":"Domain Name\n-----------"} {"repo":"flask","file":"docs/deploying/nginx.rst","line":41,"symbol":"Configuration","kind":"section","lang":"rst","code":"Configuration\n-------------"} {"repo":"flask","file":"docs/deploying/proxy_fix.rst","line":1,"symbol":"Tell Flask it is Behind a Proxy","kind":"section","lang":"rst","code":"Tell Flask it is Behind a Proxy\n==============================="} {"repo":"flask","file":"docs/deploying/uwsgi.rst","line":1,"symbol":"uWSGI","kind":"section","lang":"rst","code":"uWSGI\n====="} {"repo":"flask","file":"docs/deploying/uwsgi.rst","line":19,"symbol":"Installing","kind":"section","lang":"rst","code":"Installing\n----------"} {"repo":"flask","file":"docs/deploying/uwsgi.rst","line":49,"symbol":"Running","kind":"section","lang":"rst","code":"Running\n-------"} {"repo":"flask","file":"docs/deploying/uwsgi.rst","line":89,"symbol":"Binding Externally","kind":"section","lang":"rst","code":"Binding Externally\n------------------"} {"repo":"flask","file":"docs/deploying/uwsgi.rst","line":119,"symbol":"Async with gevent","kind":"section","lang":"rst","code":"Async with gevent\n-----------------"} {"repo":"flask","file":"docs/deploying/waitress.rst","line":1,"symbol":"Waitress","kind":"section","lang":"rst","code":"Waitress\n========"} {"repo":"flask","file":"docs/deploying/waitress.rst","line":21,"symbol":"Installing","kind":"section","lang":"rst","code":"Installing\n----------"} {"repo":"flask","file":"docs/deploying/waitress.rst","line":36,"symbol":"Running","kind":"section","lang":"rst","code":"Running\n-------"} {"repo":"flask","file":"docs/deploying/waitress.rst","line":61,"symbol":"Binding Externally","kind":"section","lang":"rst","code":"Binding Externally\n------------------"} {"repo":"flask","file":"docs/design.rst","line":1,"symbol":"Design Decisions in Flask","kind":"section","lang":"rst","code":"Design Decisions in Flask\n========================="} {"repo":"flask","file":"docs/design.rst","line":10,"symbol":"The Explicit Application Object","kind":"section","lang":"rst","code":"The Explicit Application Object\n-------------------------------"} {"repo":"flask","file":"docs/errorhandling.rst","line":1,"symbol":"Handling Application Errors","kind":"section","lang":"rst","code":"Handling Application Errors\n==========================="} {"repo":"flask","file":"docs/extensiondev.rst","line":1,"symbol":"Flask Extension Development","kind":"section","lang":"rst","code":"Flask Extension Development\n==========================="} {"repo":"flask","file":"docs/extensiondev.rst","line":25,"symbol":"Naming","kind":"section","lang":"rst","code":"Naming\n------"} {"repo":"flask","file":"docs/extensions.rst","line":1,"symbol":"Extensions","kind":"section","lang":"rst","code":"Extensions\n=========="} {"repo":"flask","file":"docs/extensions.rst","line":10,"symbol":"Finding Extensions","kind":"section","lang":"rst","code":"Finding Extensions\n------------------"} {"repo":"flask","file":"docs/extensions.rst","line":17,"symbol":"Using Extensions","kind":"section","lang":"rst","code":"Using Extensions\n----------------"} {"repo":"flask","file":"docs/extensions.rst","line":39,"symbol":"Building Extensions","kind":"section","lang":"rst","code":"Building Extensions\n-------------------"} {"repo":"flask","file":"docs/gevent.rst","line":1,"symbol":"Async with Gevent","kind":"section","lang":"rst","code":"Async with Gevent\n================="} {"repo":"flask","file":"docs/gevent.rst","line":22,"symbol":"Enabling gevent","kind":"section","lang":"rst","code":"Enabling gevent\n---------------"} {"repo":"flask","file":"docs/index.rst","line":3,"symbol":"Welcome to Flask","kind":"section","lang":"rst","code":"Welcome to Flask\n================"} {"repo":"flask","file":"docs/index.rst","line":31,"symbol":"User's Guide","kind":"section","lang":"rst","code":"User's Guide\n------------"} {"repo":"flask","file":"docs/index.rst","line":67,"symbol":"API Reference","kind":"section","lang":"rst","code":"API Reference\n-------------"} {"repo":"flask","file":"docs/index.rst","line":79,"symbol":"Additional Notes","kind":"section","lang":"rst","code":"Additional Notes\n----------------"} {"repo":"flask","file":"docs/installation.rst","line":1,"symbol":"Installation","kind":"section","lang":"rst","code":"Installation\n============"} {"repo":"flask","file":"docs/installation.rst","line":5,"symbol":"Python Version","kind":"section","lang":"rst","code":"Python Version\n--------------"} {"repo":"flask","file":"docs/installation.rst","line":11,"symbol":"Dependencies","kind":"section","lang":"rst","code":"Dependencies\n------------"} {"repo":"flask","file":"docs/installation.rst","line":36,"symbol":"Optional dependencies","kind":"section","lang":"rst","code":"Optional dependencies\n~~~~~~~~~~~~~~~~~~~~~"} {"repo":"flask","file":"docs/installation.rst","line":51,"symbol":"greenlet","kind":"section","lang":"rst","code":"greenlet\n~~~~~~~~"} {"repo":"flask","file":"docs/installation.rst","line":62,"symbol":"Virtual environments","kind":"section","lang":"rst","code":"Virtual environments\n--------------------"} {"repo":"flask","file":"docs/installation.rst","line":83,"symbol":"Create an environment","kind":"section","lang":"rst","code":"Create an environment\n~~~~~~~~~~~~~~~~~~~~~"} {"repo":"flask","file":"docs/license.rst","line":1,"symbol":"BSD-3-Clause License","kind":"section","lang":"rst","code":"BSD-3-Clause License\n===================="} {"repo":"flask","file":"docs/lifecycle.rst","line":1,"symbol":"Application Structure and Lifecycle","kind":"section","lang":"rst","code":"Application Structure and Lifecycle\n==================================="} {"repo":"flask","file":"docs/lifecycle.rst","line":10,"symbol":"Application Setup","kind":"section","lang":"rst","code":"Application Setup\n-----------------"} {"repo":"flask","file":"docs/logging.rst","line":1,"symbol":"Logging","kind":"section","lang":"rst","code":"Logging\n======="} {"repo":"flask","file":"docs/logging.rst","line":27,"symbol":"Basic Configuration","kind":"section","lang":"rst","code":"Basic Configuration\n-------------------"} {"repo":"flask","file":"docs/logging.rst","line":59,"symbol":"Default Configuration","kind":"section","lang":"rst","code":"Default Configuration\n`````````````````````"} {"repo":"flask","file":"docs/logging.rst","line":69,"symbol":"Removing the Default Handler","kind":"section","lang":"rst","code":"Removing the Default Handler\n````````````````````````````"} {"repo":"flask","file":"docs/logging.rst","line":81,"symbol":"Email Errors to Admins","kind":"section","lang":"rst","code":"Email Errors to Admins\n----------------------"} {"repo":"flask","file":"docs/logging.rst","line":114,"symbol":"Injecting Request Information","kind":"section","lang":"rst","code":"Injecting Request Information\n-----------------------------"} {"repo":"flask","file":"docs/logging.rst","line":145,"symbol":"Other Libraries","kind":"section","lang":"rst","code":"Other Libraries\n---------------"} {"repo":"flask","file":"docs/logging.rst","line":170,"symbol":"Werkzeug","kind":"section","lang":"rst","code":"Werkzeug\n````````"} {"repo":"flask","file":"docs/logging.rst","line":178,"symbol":"Flask Extensions","kind":"section","lang":"rst","code":"Flask Extensions\n````````````````"} {"repo":"flask","file":"docs/patterns/appdispatch.rst","line":1,"symbol":"Application Dispatching","kind":"section","lang":"rst","code":"Application Dispatching\n======================="} {"repo":"flask","file":"docs/patterns/appdispatch.rst","line":17,"symbol":"Working with this Document","kind":"section","lang":"rst","code":"Working with this Document\n--------------------------"} {"repo":"flask","file":"docs/patterns/appdispatch.rst","line":36,"symbol":"Combining Applications","kind":"section","lang":"rst","code":"Combining Applications\n----------------------"} {"repo":"flask","file":"docs/patterns/appdispatch.rst","line":60,"symbol":"Dispatch by Subdomain","kind":"section","lang":"rst","code":"Dispatch by Subdomain\n---------------------"} {"repo":"flask","file":"docs/patterns/appfactories.rst","line":1,"symbol":"Application Factories","kind":"section","lang":"rst","code":"Application Factories\n====================="} {"repo":"flask","file":"docs/patterns/appfactories.rst","line":22,"symbol":"Basic Factories","kind":"section","lang":"rst","code":"Basic Factories\n---------------"} {"repo":"flask","file":"docs/patterns/appfactories.rst","line":55,"symbol":"Factories & Extensions","kind":"section","lang":"rst","code":"Factories & Extensions\n----------------------"} {"repo":"flask","file":"docs/patterns/appfactories.rst","line":87,"symbol":"Using Applications","kind":"section","lang":"rst","code":"Using Applications\n------------------"} {"repo":"flask","file":"docs/patterns/caching.rst","line":1,"symbol":"Caching","kind":"section","lang":"rst","code":"Caching\n======="} {"repo":"flask","file":"docs/patterns/celery.rst","line":1,"symbol":"Background Tasks with Celery","kind":"section","lang":"rst","code":"Background Tasks with Celery\n============================"} {"repo":"flask","file":"docs/patterns/celery.rst","line":22,"symbol":"Install","kind":"section","lang":"rst","code":"Install\n-------"} {"repo":"flask","file":"docs/patterns/deferredcallbacks.rst","line":1,"symbol":"Deferred Request Callbacks","kind":"section","lang":"rst","code":"Deferred Request Callbacks\n=========================="} {"repo":"flask","file":"docs/patterns/favicon.rst","line":1,"symbol":"Adding a favicon","kind":"section","lang":"rst","code":"Adding a favicon\n================"} {"repo":"flask","file":"docs/patterns/fileuploads.rst","line":1,"symbol":"Uploading Files","kind":"section","lang":"rst","code":"Uploading Files\n==============="} {"repo":"flask","file":"docs/patterns/flashing.rst","line":1,"symbol":"Message Flashing","kind":"section","lang":"rst","code":"Message Flashing\n================"} {"repo":"flask","file":"docs/patterns/flashing.rst","line":14,"symbol":"Simple Flashing","kind":"section","lang":"rst","code":"Simple Flashing\n---------------"} {"repo":"flask","file":"docs/patterns/index.rst","line":1,"symbol":"Patterns for Flask","kind":"section","lang":"rst","code":"Patterns for Flask\n=================="} {"repo":"flask","file":"docs/patterns/javascript.rst","line":1,"symbol":"JavaScript, ``fetch``, and JSON","kind":"section","lang":"rst","code":"JavaScript, ``fetch``, and JSON\n==============================="} {"repo":"flask","file":"docs/patterns/javascript.rst","line":24,"symbol":"Rendering Templates","kind":"section","lang":"rst","code":"Rendering Templates\n-------------------"} {"repo":"flask","file":"docs/patterns/javascript.rst","line":62,"symbol":"Generating URLs","kind":"section","lang":"rst","code":"Generating URLs\n---------------"} {"repo":"flask","file":"docs/patterns/jquery.rst","line":3,"symbol":"AJAX with jQuery","kind":"section","lang":"rst","code":"AJAX with jQuery\n================"} {"repo":"flask","file":"docs/patterns/lazyloading.rst","line":1,"symbol":"Lazily Loading Views","kind":"section","lang":"rst","code":"Lazily Loading Views\n===================="} {"repo":"flask","file":"docs/patterns/methodoverrides.rst","line":1,"symbol":"Adding HTTP Method Overrides","kind":"section","lang":"rst","code":"Adding HTTP Method Overrides\n============================"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":1,"symbol":"MongoDB with MongoEngine","kind":"section","lang":"rst","code":"MongoDB with MongoEngine\n========================"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":15,"symbol":"Configuration","kind":"section","lang":"rst","code":"Configuration\n-------------"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":31,"symbol":"Mapping Documents","kind":"section","lang":"rst","code":"Mapping Documents\n-----------------"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":60,"symbol":"Creating Data","kind":"section","lang":"rst","code":"Creating Data\n-------------"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":76,"symbol":"Queries","kind":"section","lang":"rst","code":"Queries\n-------"} {"repo":"flask","file":"docs/patterns/mongoengine.rst","line":94,"symbol":"Documentation","kind":"section","lang":"rst","code":"Documentation\n-------------"} {"repo":"flask","file":"docs/patterns/packages.rst","line":1,"symbol":"Large Applications as Packages","kind":"section","lang":"rst","code":"Large Applications as Packages\n=============================="} {"repo":"flask","file":"docs/patterns/packages.rst","line":21,"symbol":"Simple Packages","kind":"section","lang":"rst","code":"Simple Packages\n---------------"} {"repo":"flask","file":"docs/patterns/requestchecksum.rst","line":1,"symbol":"Request Content Checksums","kind":"section","lang":"rst","code":"Request Content Checksums\n========================="} {"repo":"flask","file":"docs/patterns/singlepageapplications.rst","line":1,"symbol":"Single-Page Applications","kind":"section","lang":"rst","code":"Single-Page Applications\n========================"} {"repo":"flask","file":"docs/patterns/sqlalchemy.rst","line":1,"symbol":"SQLAlchemy in Flask","kind":"section","lang":"rst","code":"SQLAlchemy in Flask\n==================="} {"repo":"flask","file":"docs/patterns/sqlite3.rst","line":1,"symbol":"Using SQLite 3 with Flask","kind":"section","lang":"rst","code":"Using SQLite 3 with Flask\n========================="} {"repo":"flask","file":"docs/patterns/sqlite3.rst","line":48,"symbol":"Connect on Demand","kind":"section","lang":"rst","code":"Connect on Demand\n-----------------"} {"repo":"flask","file":"docs/patterns/sqlite3.rst","line":60,"symbol":"Easy Querying","kind":"section","lang":"rst","code":"Easy Querying\n-------------"} {"repo":"flask","file":"docs/patterns/sqlite3.rst","line":129,"symbol":"Initial Schemas","kind":"section","lang":"rst","code":"Initial Schemas\n---------------"} {"repo":"flask","file":"docs/patterns/streaming.rst","line":1,"symbol":"Streaming Contents","kind":"section","lang":"rst","code":"Streaming Contents\n=================="} {"repo":"flask","file":"docs/patterns/streaming.rst","line":11,"symbol":"HTTP Response Behavior","kind":"section","lang":"rst","code":"HTTP Response Behavior\n----------------------"} {"repo":"flask","file":"docs/patterns/streaming.rst","line":26,"symbol":"Basic Usage","kind":"section","lang":"rst","code":"Basic Usage\n-----------"} {"repo":"flask","file":"docs/patterns/streaming.rst","line":44,"symbol":"Streaming from Templates","kind":"section","lang":"rst","code":"Streaming from Templates\n------------------------"} {"repo":"flask","file":"docs/patterns/streaming.rst","line":64,"symbol":"Streaming with Context","kind":"section","lang":"rst","code":"Streaming with Context\n----------------------"} {"repo":"flask","file":"docs/patterns/subclassing.rst","line":1,"symbol":"Subclassing Flask","kind":"section","lang":"rst","code":"Subclassing Flask\n================="} {"repo":"flask","file":"docs/patterns/templateinheritance.rst","line":1,"symbol":"Template Inheritance","kind":"section","lang":"rst","code":"Template Inheritance\n===================="} {"repo":"flask","file":"docs/patterns/templateinheritance.rst","line":12,"symbol":"Base Template","kind":"section","lang":"rst","code":"Base Template\n-------------"} {"repo":"flask","file":"docs/patterns/urlprocessors.rst","line":1,"symbol":"Using URL Processors","kind":"section","lang":"rst","code":"Using URL Processors\n===================="} {"repo":"flask","file":"docs/patterns/urlprocessors.rst","line":16,"symbol":"Internationalized Application URLs","kind":"section","lang":"rst","code":"Internationalized Application URLs\n----------------------------------"} {"repo":"flask","file":"docs/patterns/urlprocessors.rst","line":98,"symbol":"Internationalized Blueprint URLs","kind":"section","lang":"rst","code":"Internationalized Blueprint URLs\n--------------------------------"} {"repo":"flask","file":"docs/patterns/viewdecorators.rst","line":1,"symbol":"View Decorators","kind":"section","lang":"rst","code":"View Decorators\n==============="} {"repo":"flask","file":"docs/patterns/viewdecorators.rst","line":15,"symbol":"Login Required Decorator","kind":"section","lang":"rst","code":"Login Required Decorator\n------------------------"} {"repo":"flask","file":"docs/patterns/viewdecorators.rst","line":56,"symbol":"Caching Decorator","kind":"section","lang":"rst","code":"Caching Decorator\n-----------------"} {"repo":"flask","file":"docs/patterns/viewdecorators.rst","line":103,"symbol":"Templating Decorator","kind":"section","lang":"rst","code":"Templating Decorator\n--------------------"} {"repo":"flask","file":"docs/patterns/viewdecorators.rst","line":156,"symbol":"Endpoint Decorator","kind":"section","lang":"rst","code":"Endpoint Decorator\n------------------"} {"repo":"flask","file":"docs/patterns/wtforms.rst","line":1,"symbol":"Form Validation with WTForms","kind":"section","lang":"rst","code":"Form Validation with WTForms\n============================"} {"repo":"flask","file":"docs/patterns/wtforms.rst","line":24,"symbol":"The Forms","kind":"section","lang":"rst","code":"The Forms\n---------"} {"repo":"flask","file":"docs/patterns/wtforms.rst","line":41,"symbol":"In the View","kind":"section","lang":"rst","code":"In the View\n-----------"} {"repo":"flask","file":"docs/quickstart.rst","line":1,"symbol":"Quickstart","kind":"section","lang":"rst","code":"Quickstart\n=========="} {"repo":"flask","file":"docs/quickstart.rst","line":8,"symbol":"A Minimal Application","kind":"section","lang":"rst","code":"A Minimal Application\n---------------------"} {"repo":"flask","file":"docs/reqcontext.rst","line":3,"symbol":"The Request Context","kind":"section","lang":"rst","code":"The Request Context\n==================="} {"repo":"flask","file":"docs/server.rst","line":3,"symbol":"Development Server","kind":"section","lang":"rst","code":"Development Server\n=================="} {"repo":"flask","file":"docs/server.rst","line":18,"symbol":"Command Line","kind":"section","lang":"rst","code":"Command Line\n------------"} {"repo":"flask","file":"docs/server.rst","line":37,"symbol":"Address already in use","kind":"section","lang":"rst","code":"Address already in use\n~~~~~~~~~~~~~~~~~~~~~~"} {"repo":"flask","file":"docs/shell.rst","line":1,"symbol":"Working with the Shell","kind":"section","lang":"rst","code":"Working with the Shell\n======================"} {"repo":"flask","file":"docs/shell.rst","line":13,"symbol":"Creating a Request Context","kind":"section","lang":"rst","code":"Creating a Request Context\n--------------------------"} {"repo":"flask","file":"docs/signals.rst","line":1,"symbol":"Signals","kind":"section","lang":"rst","code":"Signals\n======="} {"repo":"flask","file":"docs/signals.rst","line":20,"symbol":"Core Signals","kind":"section","lang":"rst","code":"Core Signals\n------------"} {"repo":"flask","file":"docs/signals.rst","line":27,"symbol":"Subscribing to Signals","kind":"section","lang":"rst","code":"Subscribing to Signals\n----------------------"} {"repo":"flask","file":"docs/signals.rst","line":97,"symbol":"Creating Signals","kind":"section","lang":"rst","code":"Creating Signals\n----------------"} {"repo":"flask","file":"docs/signals.rst","line":118,"symbol":"Sending Signals","kind":"section","lang":"rst","code":"Sending Signals\n---------------"} {"repo":"flask","file":"docs/signals.rst","line":144,"symbol":"Signals and Flask's Request Context","kind":"section","lang":"rst","code":"Signals and Flask's Request Context\n-----------------------------------"} {"repo":"flask","file":"docs/signals.rst","line":153,"symbol":"Decorator Based Signal Subscriptions","kind":"section","lang":"rst","code":"Decorator Based Signal Subscriptions\n------------------------------------"} {"repo":"flask","file":"docs/templating.rst","line":1,"symbol":"Templates","kind":"section","lang":"rst","code":"Templates\n========="} {"repo":"flask","file":"docs/templating.rst","line":15,"symbol":"Jinja Setup","kind":"section","lang":"rst","code":"Jinja Setup\n-----------"} {"repo":"flask","file":"docs/testing.rst","line":1,"symbol":"Testing Flask Applications","kind":"section","lang":"rst","code":"Testing Flask Applications\n=========================="} {"repo":"flask","file":"docs/testing.rst","line":22,"symbol":"Identifying Tests","kind":"section","lang":"rst","code":"Identifying Tests\n-----------------"} {"repo":"flask","file":"docs/testing.rst","line":35,"symbol":"Fixtures","kind":"section","lang":"rst","code":"Fixtures\n--------"} {"repo":"flask","file":"docs/testing.rst","line":83,"symbol":"Sending Requests with the Test Client","kind":"section","lang":"rst","code":"Sending Requests with the Test Client\n-------------------------------------"} {"repo":"flask","file":"docs/testing.rst","line":120,"symbol":"Form Data","kind":"section","lang":"rst","code":"Form Data\n~~~~~~~~~"} {"repo":"flask","file":"docs/testing.rst","line":152,"symbol":"JSON Data","kind":"section","lang":"rst","code":"JSON Data\n~~~~~~~~~"} {"repo":"flask","file":"docs/testing.rst","line":179,"symbol":"Following Redirects","kind":"section","lang":"rst","code":"Following Redirects\n-------------------"} {"repo":"flask","file":"docs/testing.rst","line":202,"symbol":"Accessing and Modifying the Session","kind":"section","lang":"rst","code":"Accessing and Modifying the Session\n-----------------------------------"} {"repo":"flask","file":"docs/testing.rst","line":245,"symbol":"Running Commands with the CLI Runner","kind":"section","lang":"rst","code":"Running Commands with the CLI Runner\n------------------------------------"} {"repo":"flask","file":"docs/testing.rst","line":275,"symbol":"Tests that depend on an Active Context","kind":"section","lang":"rst","code":"Tests that depend on an Active Context\n--------------------------------------"} {"repo":"flask","file":"docs/tutorial/blog.rst","line":3,"symbol":"Blog Blueprint","kind":"section","lang":"rst","code":"Blog Blueprint\n=============="} {"repo":"flask","file":"docs/tutorial/blog.rst","line":15,"symbol":"The Blueprint","kind":"section","lang":"rst","code":"The Blueprint\n-------------"} {"repo":"flask","file":"docs/tutorial/blog.rst","line":69,"symbol":"Index","kind":"section","lang":"rst","code":"Index\n-----"} {"repo":"flask","file":"docs/tutorial/blog.rst","line":131,"symbol":"Create","kind":"section","lang":"rst","code":"Create\n------"} {"repo":"flask","file":"docs/tutorial/blog.rst","line":190,"symbol":"Update","kind":"section","lang":"rst","code":"Update\n------"} {"repo":"flask","file":"docs/tutorial/database.rst","line":3,"symbol":"Define and Access the Database","kind":"section","lang":"rst","code":"Define and Access the Database\n=============================="} {"repo":"flask","file":"docs/tutorial/database.rst","line":24,"symbol":"Connect to the Database","kind":"section","lang":"rst","code":"Connect to the Database\n-----------------------"} {"repo":"flask","file":"docs/tutorial/database.rst","line":88,"symbol":"Create the Tables","kind":"section","lang":"rst","code":"Create the Tables\n-----------------"} {"repo":"flask","file":"docs/tutorial/deploy.rst","line":1,"symbol":"Deploy to Production","kind":"section","lang":"rst","code":"Deploy to Production\n===================="} {"repo":"flask","file":"docs/tutorial/deploy.rst","line":14,"symbol":"Build and Install","kind":"section","lang":"rst","code":"Build and Install\n-----------------"} {"repo":"flask","file":"docs/tutorial/deploy.rst","line":51,"symbol":"Configure the Secret Key","kind":"section","lang":"rst","code":"Configure the Secret Key\n------------------------"} {"repo":"flask","file":"docs/tutorial/factory.rst","line":3,"symbol":"Application Setup","kind":"section","lang":"rst","code":"Application Setup\n================="} {"repo":"flask","file":"docs/tutorial/factory.rst","line":23,"symbol":"The Application Factory","kind":"section","lang":"rst","code":"The Application Factory\n-----------------------"} {"repo":"flask","file":"docs/tutorial/index.rst","line":1,"symbol":"Tutorial","kind":"section","lang":"rst","code":"Tutorial\n========"} {"repo":"flask","file":"docs/tutorial/install.rst","line":1,"symbol":"Make the Project Installable","kind":"section","lang":"rst","code":"Make the Project Installable\n============================"} {"repo":"flask","file":"docs/tutorial/layout.rst","line":1,"symbol":"Project Layout","kind":"section","lang":"rst","code":"Project Layout\n=============="} {"repo":"flask","file":"docs/tutorial/next.rst","line":1,"symbol":"Keep Developing!","kind":"section","lang":"rst","code":"Keep Developing!\n================"} {"repo":"flask","file":"docs/tutorial/static.rst","line":1,"symbol":"Static Files","kind":"section","lang":"rst","code":"Static Files\n============"} {"repo":"flask","file":"docs/tutorial/templates.rst","line":3,"symbol":"Templates","kind":"section","lang":"rst","code":"Templates\n========="} {"repo":"flask","file":"docs/tutorial/templates.rst","line":38,"symbol":"The Base Layout","kind":"section","lang":"rst","code":"The Base Layout\n---------------"} {"repo":"flask","file":"docs/tutorial/tests.rst","line":3,"symbol":"Test Coverage","kind":"section","lang":"rst","code":"Test Coverage\n============="} {"repo":"flask","file":"docs/tutorial/views.rst","line":3,"symbol":"Blueprints and Views","kind":"section","lang":"rst","code":"Blueprints and Views\n===================="} {"repo":"flask","file":"docs/tutorial/views.rst","line":13,"symbol":"Create a Blueprint","kind":"section","lang":"rst","code":"Create a Blueprint\n------------------"} {"repo":"flask","file":"docs/views.rst","line":1,"symbol":"Class-based Views","kind":"section","lang":"rst","code":"Class-based Views\n================="} {"repo":"flask","file":"docs/views.rst","line":21,"symbol":"Basic Reusable View","kind":"section","lang":"rst","code":"Basic Reusable View\n-------------------"} {"repo":"flask","file":"docs/views.rst","line":101,"symbol":"URL Variables","kind":"section","lang":"rst","code":"URL Variables\n-------------"} {"repo":"flask","file":"docs/views.rst","line":125,"symbol":"View Lifetime and ``self``","kind":"section","lang":"rst","code":"View Lifetime and ``self``\n--------------------------"} {"repo":"flask","file":"docs/views.rst","line":160,"symbol":"View Decorators","kind":"section","lang":"rst","code":"View Decorators\n---------------"} {"repo":"flask","file":"docs/web-security.rst","line":1,"symbol":"Security Considerations","kind":"section","lang":"rst","code":"Security Considerations\n======================="} {"repo":"flask","file":"docs/web-security.rst","line":12,"symbol":"Resource Use","kind":"section","lang":"rst","code":"Resource Use\n------------"} {"repo":"flask","file":"docs/web-security.rst","line":44,"symbol":"Cross-Site Scripting (XSS)","kind":"section","lang":"rst","code":"Cross-Site Scripting (XSS)\n--------------------------"} {"repo":"flask","file":"examples/celery/requirements.txt","line":7,"symbol":"amqp","kind":"field","lang":"requirements","code":"amqp==5.1.1"} {"repo":"flask","file":"examples/celery/requirements.txt","line":9,"symbol":"async-timeout","kind":"field","lang":"requirements","code":"async-timeout==4.0.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":11,"symbol":"billiard","kind":"field","lang":"requirements","code":"billiard==3.6.4.0"} {"repo":"flask","file":"examples/celery/requirements.txt","line":13,"symbol":"blinker","kind":"field","lang":"requirements","code":"blinker==1.6.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":15,"symbol":"celery","kind":"field","lang":"requirements","code":"celery[redis]==5.2.7"} {"repo":"flask","file":"examples/celery/requirements.txt","line":17,"symbol":"click","kind":"field","lang":"requirements","code":"click==8.1.3"} {"repo":"flask","file":"examples/celery/requirements.txt","line":24,"symbol":"click-didyoumean","kind":"field","lang":"requirements","code":"click-didyoumean==0.3.0"} {"repo":"flask","file":"examples/celery/requirements.txt","line":26,"symbol":"click-plugins","kind":"field","lang":"requirements","code":"click-plugins==1.1.1"} {"repo":"flask","file":"examples/celery/requirements.txt","line":28,"symbol":"click-repl","kind":"field","lang":"requirements","code":"click-repl==0.2.0"} {"repo":"flask","file":"examples/celery/requirements.txt","line":30,"symbol":"flask","kind":"field","lang":"requirements","code":"flask==2.3.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":32,"symbol":"itsdangerous","kind":"field","lang":"requirements","code":"itsdangerous==2.1.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":34,"symbol":"jinja2","kind":"field","lang":"requirements","code":"jinja2==3.1.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":36,"symbol":"kombu","kind":"field","lang":"requirements","code":"kombu==5.2.4"} {"repo":"flask","file":"examples/celery/requirements.txt","line":38,"symbol":"markupsafe","kind":"field","lang":"requirements","code":"markupsafe==2.1.2"} {"repo":"flask","file":"examples/celery/requirements.txt","line":42,"symbol":"prompt-toolkit","kind":"field","lang":"requirements","code":"prompt-toolkit==3.0.38"} {"repo":"flask","file":"examples/celery/requirements.txt","line":44,"symbol":"pytz","kind":"field","lang":"requirements","code":"pytz==2023.3"} {"repo":"flask","file":"examples/celery/requirements.txt","line":46,"symbol":"redis","kind":"field","lang":"requirements","code":"redis==4.5.4"} {"repo":"flask","file":"examples/celery/requirements.txt","line":48,"symbol":"six","kind":"field","lang":"requirements","code":"six==1.16.0"} {"repo":"flask","file":"examples/celery/requirements.txt","line":50,"symbol":"vine","kind":"field","lang":"requirements","code":"vine==5.0.0"} {"repo":"flask","file":"examples/celery/requirements.txt","line":55,"symbol":"wcwidth","kind":"field","lang":"requirements","code":"wcwidth==0.2.6"} {"repo":"flask","file":"examples/celery/requirements.txt","line":57,"symbol":"werkzeug","kind":"field","lang":"requirements","code":"werkzeug==2.3.3"} {"repo":"flask","file":"examples/celery/src/task_app/__init__.py","line":7,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app() -> Flask:\n app = Flask(__name__)\n app.config.from_mapping(\n CELERY={\n \"broker_url\": \"redis://localhost\",\n \"result_backend\": \"redis://localhost\",\n \"task_ignore_result\": True,\n },\n )\n app.config.from_prefixed_env()\n celery_init_app(app)\n\n @app.route(\"/\")\n def index() -> str:\n return render_template(\"index.html\")\n\n from . import views\n\n app.register_blueprint(views.bp)\n return app"} {"repo":"flask","file":"examples/celery/src/task_app/__init__.py","line":20,"symbol":"index","kind":"function","lang":"python","code":"def index() -> str:\n return render_template(\"index.html\")"} {"repo":"flask","file":"examples/celery/src/task_app/__init__.py","line":29,"symbol":"celery_init_app","kind":"function","lang":"python","code":"def celery_init_app(app: Flask) -> Celery:\n class FlaskTask(Task):\n def __call__(self, *args: object, **kwargs: object) -> object:\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery_app = Celery(app.name, task_cls=FlaskTask)\n celery_app.config_from_object(app.config[\"CELERY\"])\n celery_app.set_default()\n app.extensions[\"celery\"] = celery_app\n return celery_app"} {"repo":"flask","file":"examples/celery/src/task_app/__init__.py","line":30,"symbol":"FlaskTask","kind":"class","lang":"python","code":"class FlaskTask(Task):\n def __call__(self, *args: object, **kwargs: object) -> object:\n with app.app_context():\n return self.run(*args, **kwargs)"} {"repo":"flask","file":"examples/celery/src/task_app/__init__.py","line":31,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, *args: object, **kwargs: object) -> object:\n with app.app_context():\n return self.run(*args, **kwargs)"} {"repo":"flask","file":"examples/celery/src/task_app/tasks.py","line":8,"symbol":"add","kind":"function","lang":"python","code":"def add(a: int, b: int) -> int:\n return a + b"} {"repo":"flask","file":"examples/celery/src/task_app/tasks.py","line":13,"symbol":"block","kind":"function","lang":"python","code":"def block() -> None:\n time.sleep(5)"} {"repo":"flask","file":"examples/celery/src/task_app/tasks.py","line":18,"symbol":"process","kind":"function","lang":"python","code":"def process(self: Task, total: int) -> object:\n for i in range(total):\n self.update_state(state=\"PROGRESS\", meta={\"current\": i + 1, \"total\": total})\n time.sleep(1)\n\n return {\"current\": total, \"total\": total}"} {"repo":"flask","file":"examples/celery/src/task_app/views.py","line":11,"symbol":"result","kind":"function","lang":"python","code":"def result(id: str) -> dict[str, object]:\n result = AsyncResult(id)\n ready = result.ready()\n return {\n \"ready\": ready,\n \"successful\": result.successful() if ready else None,\n \"value\": result.get() if ready else result.result,\n }"} {"repo":"flask","file":"examples/celery/src/task_app/views.py","line":22,"symbol":"add","kind":"function","lang":"python","code":"def add() -> dict[str, object]:\n a = request.form.get(\"a\", type=int)\n b = request.form.get(\"b\", type=int)\n result = tasks.add.delay(a, b)\n return {\"result_id\": result.id}"} {"repo":"flask","file":"examples/celery/src/task_app/views.py","line":30,"symbol":"block","kind":"function","lang":"python","code":"def block() -> dict[str, object]:\n result = tasks.block.delay()\n return {\"result_id\": result.id}"} {"repo":"flask","file":"examples/celery/src/task_app/views.py","line":36,"symbol":"process","kind":"function","lang":"python","code":"def process() -> dict[str, object]:\n result = tasks.process.delay(total=request.form.get(\"total\", type=int))\n return {\"result_id\": result.id}"} {"repo":"flask","file":"examples/javascript/README.rst","line":1,"symbol":"JavaScript Ajax Example","kind":"section","lang":"rst","code":"JavaScript Ajax Example\n======================="} {"repo":"flask","file":"examples/javascript/README.rst","line":21,"symbol":"Install","kind":"section","lang":"rst","code":"Install\n-------"} {"repo":"flask","file":"examples/javascript/README.rst","line":31,"symbol":"Run","kind":"section","lang":"rst","code":"Run\n---"} {"repo":"flask","file":"examples/javascript/README.rst","line":41,"symbol":"Test","kind":"section","lang":"rst","code":"Test\n----"} {"repo":"flask","file":"examples/javascript/js_example/views.py","line":10,"symbol":"index","kind":"function","lang":"python","code":"def index(js):\n return render_template(f\"{js}.html\", js=js)"} {"repo":"flask","file":"examples/javascript/js_example/views.py","line":15,"symbol":"add","kind":"function","lang":"python","code":"def add():\n a = request.form.get(\"a\", 0, type=float)\n b = request.form.get(\"b\", 0, type=float)\n return jsonify(result=a + b)"} {"repo":"flask","file":"examples/javascript/tests/conftest.py","line":7,"symbol":"fixture_app","kind":"function","lang":"python","code":"def fixture_app():\n app.testing = True\n yield app\n app.testing = False"} {"repo":"flask","file":"examples/javascript/tests/conftest.py","line":14,"symbol":"client","kind":"function","lang":"python","code":"def client(app):\n return app.test_client()"} {"repo":"flask","file":"examples/javascript/tests/test_js_example.py","line":14,"symbol":"test_index","kind":"function","lang":"python","code":"def test_index(app, client, path, template_name):\n def check(sender, template, context):\n assert template.name == template_name\n\n with template_rendered.connected_to(check, app):\n client.get(path)"} {"repo":"flask","file":"examples/javascript/tests/test_js_example.py","line":15,"symbol":"check","kind":"function","lang":"python","code":"def check(sender, template, context):\n assert template.name == template_name"} {"repo":"flask","file":"examples/javascript/tests/test_js_example.py","line":25,"symbol":"test_add","kind":"function","lang":"python","code":"def test_add(client, a, b, result):\n response = client.post(\"/add\", data={\"a\": a, \"b\": b})\n assert response.get_json()[\"result\"] == result"} {"repo":"flask","file":"examples/tutorial/README.rst","line":1,"symbol":"Flaskr","kind":"section","lang":"rst","code":"Flaskr\n======"} {"repo":"flask","file":"examples/tutorial/README.rst","line":9,"symbol":"Install","kind":"section","lang":"rst","code":"Install\n-------"} {"repo":"flask","file":"examples/tutorial/README.rst","line":45,"symbol":"Run","kind":"section","lang":"rst","code":"Run\n---"} {"repo":"flask","file":"examples/tutorial/README.rst","line":56,"symbol":"Test","kind":"section","lang":"rst","code":"Test\n----"} {"repo":"flask","file":"examples/tutorial/flaskr/__init__.py","line":6,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n os.makedirs(app.instance_path, exist_ok=True)\n\n @app.route(\"/hello\")\n def hello():\n return \"Hello, World!\"\n\n # register the database commands\n from . import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from . import auth\n from . import blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.rou"} {"repo":"flask","file":"examples/tutorial/flaskr/__init__.py","line":27,"symbol":"hello","kind":"function","lang":"python","code":"def hello():\n return \"Hello, World!\""} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":19,"symbol":"login_required","kind":"function","lang":"python","code":"def login_required(view):\n \"\"\"View decorator that redirects anonymous users to the login page.\"\"\"\n\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)\n\n return wrapped_view"} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":23,"symbol":"wrapped_view","kind":"function","lang":"python","code":"def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)"} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":33,"symbol":"load_logged_in_user","kind":"function","lang":"python","code":"def load_logged_in_user():\n \"\"\"If a user id is stored in the session, load the user object from\n the database into ``g.user``.\"\"\"\n user_id = session.get(\"user_id\")\n\n if user_id is None:\n g.user = None\n else:\n g.user = (\n get_db().execute(\"SELECT * FROM user WHERE id = ?\", (user_id,)).fetchone()\n )"} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":47,"symbol":"register","kind":"function","lang":"python","code":"def register():\n \"\"\"Register a new user.\n\n Validates that the username is not already taken. Hashes the\n password for security.\n \"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n\n if not username:\n error = \"Username is required.\"\n elif not password:\n error = \"Password is required.\"\n\n if error is None:\n try:\n db.execute(\n \"INSERT INTO user (username, password) VALUES (?, ?)\",\n (username, generate_password_hash(password)),\n )\n db.commit()\n except db.IntegrityError:\n # The username was already taken, which caused the\n # commit to fail. Show a validation error.\n error = f\"User {username} is already registered.\"\n else:\n # Success, go to the login page.\n return redirect(url_for(\"auth.login\"))\n\n flash(error)\n\n return render_template(\"auth/register.html\")"} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":85,"symbol":"login","kind":"function","lang":"python","code":"def login():\n \"\"\"Log in a registered user by adding the user id to the session.\"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n user = db.execute(\n \"SELECT * FROM user WHERE username = ?\", (username,)\n ).fetchone()\n\n if user is None:\n error = \"Incorrect username.\"\n elif not check_password_hash(user[\"password\"], password):\n error = \"Incorrect password.\"\n\n if error is None:\n # store the user id in a new session and return to the index\n session.clear()\n session[\"user_id\"] = user[\"id\"]\n return redirect(url_for(\"index\"))\n\n flash(error)\n\n return render_template(\"auth/login.html\")"} {"repo":"flask","file":"examples/tutorial/flaskr/auth.py","line":113,"symbol":"logout","kind":"function","lang":"python","code":"def logout():\n \"\"\"Clear the current session, including the stored user id.\"\"\"\n session.clear()\n return redirect(url_for(\"index\"))"} {"repo":"flask","file":"examples/tutorial/flaskr/blog.py","line":17,"symbol":"index","kind":"function","lang":"python","code":"def index():\n \"\"\"Show all the posts, most recent first.\"\"\"\n db = get_db()\n posts = db.execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY created DESC\"\n ).fetchall()\n return render_template(\"blog/index.html\", posts=posts)"} {"repo":"flask","file":"examples/tutorial/flaskr/blog.py","line":28,"symbol":"get_post","kind":"function","lang":"python","code":"def get_post(id, check_author=True):\n \"\"\"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n \"\"\"\n post = (\n get_db()\n .execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" WHERE p.id = ?\",\n (id,),\n )\n .fetchone()\n )\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post[\"author_id\"] != g.user[\"id\"]:\n abort(403)\n\n return post"} {"repo":"flask","file":"examples/tutorial/flaskr/blog.py","line":62,"symbol":"create","kind":"function","lang":"python","code":"def create():\n \"\"\"Create a new post for the current user.\"\"\"\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)\",\n (title, body, g.user[\"id\"]),\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/create.html\")"} {"repo":"flask","file":"examples/tutorial/flaskr/blog.py","line":88,"symbol":"update","kind":"function","lang":"python","code":"def update(id):\n \"\"\"Update a post if the current user is the author.\"\"\"\n post = get_post(id)\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"UPDATE post SET title = ?, body = ? WHERE id = ?\", (title, body, id)\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/update.html\", post=post)"} {"repo":"flask","file":"examples/tutorial/flaskr/blog.py","line":115,"symbol":"delete","kind":"function","lang":"python","code":"def delete(id):\n \"\"\"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n \"\"\"\n get_post(id)\n db = get_db()\n db.execute(\"DELETE FROM post WHERE id = ?\", (id,))\n db.commit()\n return redirect(url_for(\"blog.index\"))"} {"repo":"flask","file":"examples/tutorial/flaskr/db.py","line":9,"symbol":"get_db","kind":"function","lang":"python","code":"def get_db():\n \"\"\"Connect to the application's configured database. The connection\n is unique for each request and will be reused if this is called\n again.\n \"\"\"\n if \"db\" not in g:\n g.db = sqlite3.connect(\n current_app.config[\"DATABASE\"], detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = sqlite3.Row\n\n return g.db"} {"repo":"flask","file":"examples/tutorial/flaskr/db.py","line":23,"symbol":"close_db","kind":"function","lang":"python","code":"def close_db(e=None):\n \"\"\"If this request connected to the database, close the\n connection.\n \"\"\"\n db = g.pop(\"db\", None)\n\n if db is not None:\n db.close()"} {"repo":"flask","file":"examples/tutorial/flaskr/db.py","line":33,"symbol":"init_db","kind":"function","lang":"python","code":"def init_db():\n \"\"\"Clear existing data and create new tables.\"\"\"\n db = get_db()\n\n with current_app.open_resource(\"schema.sql\") as f:\n db.executescript(f.read().decode(\"utf8\"))"} {"repo":"flask","file":"examples/tutorial/flaskr/db.py","line":42,"symbol":"init_db_command","kind":"function","lang":"python","code":"def init_db_command():\n \"\"\"Clear existing data and create new tables.\"\"\"\n init_db()\n click.echo(\"Initialized the database.\")"} {"repo":"flask","file":"examples/tutorial/flaskr/db.py","line":51,"symbol":"init_app","kind":"function","lang":"python","code":"def init_app(app):\n \"\"\"Register database functions with the Flask app. This is called by\n the application factory.\n \"\"\"\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)"} {"repo":"flask","file":"examples/tutorial/flaskr/schema.sql","line":7,"symbol":"user","kind":"type","lang":"sql","code":"CREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT UNIQUE NOT NULL,\n password TEXT NOT NULL\n)"} {"repo":"flask","file":"examples/tutorial/flaskr/schema.sql","line":13,"symbol":"post","kind":"type","lang":"sql","code":"CREATE TABLE post (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n author_id INTEGER NOT NULL,\n created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n FOREIGN KEY (author_id) REFERENCES user (id)\n)"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":16,"symbol":"app","kind":"function","lang":"python","code":"def app():\n \"\"\"Create and configure a new app instance for each test.\"\"\"\n # create a temporary file to isolate the database for each test\n db_fd, db_path = tempfile.mkstemp()\n # create the app with common test config\n app = create_app({\"TESTING\": True, \"DATABASE\": db_path})\n\n # create the database and load test data\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n # close and remove the temporary database\n os.close(db_fd)\n os.unlink(db_path)"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":36,"symbol":"client","kind":"function","lang":"python","code":"def client(app):\n \"\"\"A test client for the app.\"\"\"\n return app.test_client()"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":42,"symbol":"runner","kind":"function","lang":"python","code":"def runner(app):\n \"\"\"A test runner for the app's Click commands.\"\"\"\n return app.test_cli_runner()"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":47,"symbol":"AuthActions","kind":"class","lang":"python","code":"class AuthActions:\n def __init__(self, client):\n self._client = client\n\n def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )\n\n def logout(self):\n return self._client.get(\"/auth/logout\")"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":48,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, client):\n self._client = client"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":51,"symbol":"login","kind":"function","lang":"python","code":"def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":56,"symbol":"logout","kind":"function","lang":"python","code":"def logout(self):\n return self._client.get(\"/auth/logout\")"} {"repo":"flask","file":"examples/tutorial/tests/conftest.py","line":61,"symbol":"auth","kind":"function","lang":"python","code":"def auth(client):\n return AuthActions(client)"} {"repo":"flask","file":"examples/tutorial/tests/test_auth.py","line":8,"symbol":"test_register","kind":"function","lang":"python","code":"def test_register(client, app):\n # test that viewing the page renders without template errors\n assert client.get(\"/auth/register\").status_code == 200\n\n # test that successful registration redirects to the login page\n response = client.post(\"/auth/register\", data={\"username\": \"a\", \"password\": \"a\"})\n assert response.headers[\"Location\"] == \"/auth/login\"\n\n # test that the user was inserted into the database\n with app.app_context():\n assert (\n get_db().execute(\"SELECT * FROM user WHERE username = 'a'\").fetchone()\n is not None\n )"} {"repo":"flask","file":"examples/tutorial/tests/test_auth.py","line":32,"symbol":"test_register_validate_input","kind":"function","lang":"python","code":"def test_register_validate_input(client, username, password, message):\n response = client.post(\n \"/auth/register\", data={\"username\": username, \"password\": password}\n )\n assert message in response.data"} {"repo":"flask","file":"examples/tutorial/tests/test_auth.py","line":39,"symbol":"test_login","kind":"function","lang":"python","code":"def test_login(client, auth):\n # test that viewing the page renders without template errors\n assert client.get(\"/auth/login\").status_code == 200\n\n # test that successful login redirects to the index page\n response = auth.login()\n assert response.headers[\"Location\"] == \"/\"\n\n # login request set the user_id in the session\n # check that the user is loaded from the session\n with client:\n client.get(\"/\")\n assert session[\"user_id\"] == 1\n assert g.user[\"username\"] == \"test\""} {"repo":"flask","file":"examples/tutorial/tests/test_auth.py","line":59,"symbol":"test_login_validate_input","kind":"function","lang":"python","code":"def test_login_validate_input(auth, username, password, message):\n response = auth.login(username, password)\n assert message in response.data"} {"repo":"flask","file":"examples/tutorial/tests/test_auth.py","line":64,"symbol":"test_logout","kind":"function","lang":"python","code":"def test_logout(client, auth):\n auth.login()\n\n with client:\n auth.logout()\n assert \"user_id\" not in session"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":6,"symbol":"test_index","kind":"function","lang":"python","code":"def test_index(client, auth):\n response = client.get(\"/\")\n assert b\"Log In\" in response.data\n assert b\"Register\" in response.data\n\n auth.login()\n response = client.get(\"/\")\n assert b\"test title\" in response.data\n assert b\"by test on 2018-01-01\" in response.data\n assert b\"test\\nbody\" in response.data\n assert b'href=\"/1/update\"' in response.data"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":20,"symbol":"test_login_required","kind":"function","lang":"python","code":"def test_login_required(client, path):\n response = client.post(path)\n assert response.headers[\"Location\"] == \"/auth/login\""} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":25,"symbol":"test_author_required","kind":"function","lang":"python","code":"def test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db = get_db()\n db.execute(\"UPDATE post SET author_id = 2 WHERE id = 1\")\n db.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post(\"/1/update\").status_code == 403\n assert client.post(\"/1/delete\").status_code == 403\n # current user doesn't see edit link\n assert b'href=\"/1/update\"' not in client.get(\"/\").data"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":41,"symbol":"test_exists_required","kind":"function","lang":"python","code":"def test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":46,"symbol":"test_create","kind":"function","lang":"python","code":"def test_create(client, auth, app):\n auth.login()\n assert client.get(\"/create\").status_code == 200\n client.post(\"/create\", data={\"title\": \"created\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n count = db.execute(\"SELECT COUNT(id) FROM post\").fetchone()[0]\n assert count == 2"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":57,"symbol":"test_update","kind":"function","lang":"python","code":"def test_update(client, auth, app):\n auth.login()\n assert client.get(\"/1/update\").status_code == 200\n client.post(\"/1/update\", data={\"title\": \"updated\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post[\"title\"] == \"updated\""} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":69,"symbol":"test_create_update_validate","kind":"function","lang":"python","code":"def test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={\"title\": \"\", \"body\": \"\"})\n assert b\"Title is required.\" in response.data"} {"repo":"flask","file":"examples/tutorial/tests/test_blog.py","line":75,"symbol":"test_delete","kind":"function","lang":"python","code":"def test_delete(client, auth, app):\n auth.login()\n response = client.post(\"/1/delete\")\n assert response.headers[\"Location\"] == \"/\"\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post is None"} {"repo":"flask","file":"examples/tutorial/tests/test_db.py","line":8,"symbol":"test_get_close_db","kind":"function","lang":"python","code":"def test_get_close_db(app):\n with app.app_context():\n db = get_db()\n assert db is get_db()\n\n with pytest.raises(sqlite3.ProgrammingError) as e:\n db.execute(\"SELECT 1\")\n\n assert \"closed\" in str(e.value)"} {"repo":"flask","file":"examples/tutorial/tests/test_db.py","line":19,"symbol":"test_init_db_command","kind":"function","lang":"python","code":"def test_init_db_command(runner, monkeypatch):\n class Recorder:\n called = False\n\n def fake_init_db():\n Recorder.called = True\n\n monkeypatch.setattr(\"flaskr.db.init_db\", fake_init_db)\n result = runner.invoke(args=[\"init-db\"])\n assert \"Initialized\" in result.output\n assert Recorder.called"} {"repo":"flask","file":"examples/tutorial/tests/test_db.py","line":20,"symbol":"Recorder","kind":"class","lang":"python","code":"class Recorder:\n called = False"} {"repo":"flask","file":"examples/tutorial/tests/test_db.py","line":23,"symbol":"fake_init_db","kind":"function","lang":"python","code":"def fake_init_db():\n Recorder.called = True"} {"repo":"flask","file":"examples/tutorial/tests/test_factory.py","line":4,"symbol":"test_config","kind":"function","lang":"python","code":"def test_config():\n \"\"\"Test create_app without passing test config.\"\"\"\n assert not create_app().testing\n assert create_app({\"TESTING\": True}).testing"} {"repo":"flask","file":"examples/tutorial/tests/test_factory.py","line":10,"symbol":"test_hello","kind":"function","lang":"python","code":"def test_hello(client):\n response = client.get(\"/hello\")\n assert response.data == b\"Hello, World!\""} {"repo":"flask","file":"src/flask/app.py","line":74,"symbol":"_make_timedelta","kind":"function","lang":"python","code":"def _make_timedelta(value: timedelta | int | None) -> timedelta | None:\n if value is None or isinstance(value, timedelta):\n return value\n\n return timedelta(seconds=value)"} {"repo":"flask","file":"src/flask/app.py","line":86,"symbol":"remove_ctx","kind":"function","lang":"python","doc":"Other methods may call the overridden method with the new ctx arg. Remove it and call the method with the remaining args.","code":"def remove_ctx(f: F) -> F:\n def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if args and isinstance(args[0], AppContext):\n args = args[1:]\n\n return f(self, *args, **kwargs)\n\n return update_wrapper(wrapper, f) # type: ignore[return-value]"} {"repo":"flask","file":"src/flask/app.py","line":87,"symbol":"wrapper","kind":"function","lang":"python","code":"def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if args and isinstance(args[0], AppContext):\n args = args[1:]\n\n return f(self, *args, **kwargs)"} {"repo":"flask","file":"src/flask/app.py","line":98,"symbol":"add_ctx","kind":"function","lang":"python","doc":"The overridden method may call super().base_method without the new ctx arg. Add it to the args for the call.","code":"def add_ctx(f: F) -> F:\n def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if not args:\n args = (app_ctx._get_current_object(),)\n elif not isinstance(args[0], AppContext):\n args = (app_ctx._get_current_object(), *args)\n\n return f(self, *args, **kwargs)\n\n return update_wrapper(wrapper, f) # type: ignore[return-value]"} {"repo":"flask","file":"src/flask/app.py","line":99,"symbol":"wrapper","kind":"function","lang":"python","code":"def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if not args:\n args = (app_ctx._get_current_object(),)\n elif not isinstance(args[0], AppContext):\n args = (app_ctx._get_current_object(), *args)\n\n return f(self, *args, **kwargs)"} {"repo":"flask","file":"src/flask/app.py","line":110,"symbol":"Flask","kind":"class","lang":"python","code":"class Flask(App):\n \"\"\"The flask object implements a WSGI application and acts as the central\n object. It is passed the name of the module or package of the\n application. Once it is created it will act as a central registry for\n the view functions, the URL rules, template configuration and much more.\n\n The name of the package is used to resolve resources from inside the\n package or the folder the module is contained in depending on if the\n package parameter resolves to an actual python package (a folder with\n an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n For more information about resource loading, see :func:`open_resource`.\n\n Usually you create a :class:`Flask` instance in your main module or\n in the :file:`__init__.py` file of your package like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n .. admonition:: About the First Parameter\n\n The idea of the first parameter is to give Flask an idea of what\n belongs to your application. This name is used to find resources\n on the filesystem, can be used by extensions to improve debugging\n information and a lot more"} {"repo":"flask","file":"src/flask/app.py","line":255,"symbol":"__init_subclass__","kind":"function","lang":"python","code":"def __init_subclass__(cls, **kwargs: t.Any) -> None:\n import warnings\n\n # These method signatures were updated to take a ctx param. Detect\n # overridden methods in subclasses that still have the old signature.\n # Show a deprecation warning and wrap to call with correct args.\n for method in (\n cls.handle_http_exception,\n cls.handle_user_exception,\n cls.handle_exception,\n cls.log_exception,\n cls.dispatch_request,\n cls.full_dispatch_request,\n cls.finalize_request,\n cls.make_default_options_response,\n cls.preprocess_request,\n cls.process_response,\n cls.do_teardown_request,\n cls.do_teardown_appcontext,\n ):\n base_method = getattr(Flask, method.__name__)\n\n if method is base_method:\n # not overridden\n continue\n\n # get the second parameter (first is self)\n iter_params = iter(inspect.signature(method).parameters.values())\n next(iter_params)\n param = next(iter_params, None)\n\n # must have second parameter named ctx or"} {"repo":"flask","file":"src/flask/app.py","line":311,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n import_name: str,\n static_url_path: str | None = None,\n static_folder: str | os.PathLike[str] | None = \"static\",\n static_host: str | None = None,\n host_matching: bool = False,\n subdomain_matching: bool = False,\n template_folder: str | os.PathLike[str] | None = \"templates\",\n instance_path: str | None = None,\n instance_relative_config: bool = False,\n root_path: str | None = None,\n ):\n super().__init__(\n import_name=import_name,\n static_url_path=static_url_path,\n static_folder=static_folder,\n static_host=static_host,\n host_matching=host_matching,\n subdomain_matching=subdomain_matching,\n template_folder=template_folder,\n instance_path=instance_path,\n instance_relative_config=instance_relative_config,\n root_path=root_path,\n )\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been register"} {"repo":"flask","file":"src/flask/app.py","line":366,"symbol":"get_send_file_max_age","kind":"function","lang":"python","code":"def get_send_file_max_age(self, filename: str | None) -> int | None:\n \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n value for a given file path if it wasn't passed.\n\n By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n the configuration of :data:`~flask.current_app`. This defaults\n to ``None``, which tells the browser to use conditional requests\n instead of a timed cache, which is usually preferable.\n\n Note this is a duplicate of the same method in the Flask\n class.\n\n .. versionchanged:: 2.0\n The default configuration is ``None`` instead of 12 hours.\n\n .. versionadded:: 0.9\n \"\"\"\n value = self.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n if value is None:\n return None\n\n if isinstance(value, timedelta):\n return int(value.total_seconds())\n\n return value # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/app.py","line":393,"symbol":"send_static_file","kind":"function","lang":"python","code":"def send_static_file(self, filename: str) -> Response:\n \"\"\"The view function used to serve files from\n :attr:`static_folder`. A route is automatically registered for\n this view at :attr:`static_url_path` if :attr:`static_folder` is\n set.\n\n Note this is a duplicate of the same method in the Flask\n class.\n\n .. versionadded:: 0.5\n\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n # send_file only knows to call get_send_file_max_age on the app,\n # call it here so it works for blueprints too.\n max_age = self.get_send_file_max_age(filename)\n return send_from_directory(\n t.cast(str, self.static_folder), filename, max_age=max_age\n )"} {"repo":"flask","file":"src/flask/app.py","line":415,"symbol":"open_resource","kind":"function","lang":"python","code":"def open_resource(\n self, resource: str, mode: str = \"rb\", encoding: str | None = None\n ) -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to :attr:`root_path` for reading.\n\n For example, if the file ``schema.sql`` is next to the file\n ``app.py`` where the ``Flask`` app is defined, it can be opened\n with:\n\n .. code-block:: python\n\n with app.open_resource(\"schema.sql\") as f:\n conn.executescript(f.read())\n\n :param resource: Path to the resource relative to :attr:`root_path`.\n :param mode: Open the file in this mode. Only reading is supported,\n valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n :param encoding: Open the file with this encoding when opening in text\n mode. This is ignored when opening in binary mode.\n\n .. versionchanged:: 3.1\n Added the ``encoding`` parameter.\n \"\"\"\n if mode not in {\"r\", \"rt\", \"rb\"}:\n raise ValueError(\"Resources can only be opened for reading.\")\n\n path = os.path.join(self.root_path, resource)\n\n if mode == \"rb\":\n return open(path, mode) # pyright: ignore\n\n retur"} {"repo":"flask","file":"src/flask/app.py","line":448,"symbol":"open_instance_resource","kind":"function","lang":"python","code":"def open_instance_resource(\n self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n ) -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to the application's instance folder\n :attr:`instance_path`. Unlike :meth:`open_resource`, files in the\n instance folder can be opened for writing.\n\n :param resource: Path to the resource relative to :attr:`instance_path`.\n :param mode: Open the file in this mode.\n :param encoding: Open the file with this encoding when opening in text\n mode. This is ignored when opening in binary mode.\n\n .. versionchanged:: 3.1\n Added the ``encoding`` parameter.\n \"\"\"\n path = os.path.join(self.instance_path, resource)\n\n if \"b\" in mode:\n return open(path, mode)\n\n return open(path, mode, encoding=encoding)"} {"repo":"flask","file":"src/flask/app.py","line":470,"symbol":"create_jinja_environment","kind":"function","lang":"python","code":"def create_jinja_environment(self) -> Environment:\n \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n and the various Jinja-related methods of the app. Changing\n :attr:`jinja_options` after this will have no effect. Also adds\n Flask-related globals and filters to the environment.\n\n .. versionchanged:: 0.11\n ``Environment.auto_reload`` set in accordance with\n ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n .. versionadded:: 0.5\n \"\"\"\n options = dict(self.jinja_options)\n\n if \"autoescape\" not in options:\n options[\"autoescape\"] = self.select_jinja_autoescape\n\n if \"auto_reload\" not in options:\n auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n if auto_reload is None:\n auto_reload = self.debug\n\n options[\"auto_reload\"] = auto_reload\n\n rv = self.jinja_environment(self, **options)\n rv.globals.update(\n url_for=self.url_for,\n get_flashed_messages=get_flashed_messages,\n config=self.config,\n # request, session and g are normally added with the\n # context processo"} {"repo":"flask","file":"src/flask/app.py","line":510,"symbol":"create_url_adapter","kind":"function","lang":"python","code":"def create_url_adapter(self, request: Request | None) -> MapAdapter | None:\n \"\"\"Creates a URL adapter for the given request. The URL adapter\n is created at a point where the request context is not yet set\n up so the request is passed explicitly.\n\n .. versionchanged:: 3.1\n If :data:`SERVER_NAME` is set, it does not restrict requests to\n only that domain, for both ``subdomain_matching`` and\n ``host_matching``.\n\n .. versionchanged:: 1.0\n :data:`SERVER_NAME` no longer implicitly enables subdomain\n matching. Use :attr:`subdomain_matching` instead.\n\n .. versionchanged:: 0.9\n This can be called outside a request when the URL adapter is created\n for an application context.\n\n .. versionadded:: 0.6\n \"\"\"\n if request is not None:\n if (trusted_hosts := self.config[\"TRUSTED_HOSTS\"]) is not None:\n request.trusted_hosts = trusted_hosts\n\n # Check trusted_hosts here until bind_to_environ does.\n request.host = get_host(request.environ, request.trusted_hosts) # pyright: ignore\n subdomain = None\n "} {"repo":"flask","file":"src/flask/app.py","line":563,"symbol":"raise_routing_exception","kind":"function","lang":"python","code":"def raise_routing_exception(self, request: Request) -> t.NoReturn:\n \"\"\"Intercept routing exceptions and possibly do something else.\n\n In debug mode, intercept a routing redirect and replace it with\n an error if the body will be discarded.\n\n With modern Werkzeug this shouldn't occur, since it now uses a\n 308 status which tells the browser to resend the method and\n body.\n\n .. versionchanged:: 2.1\n Don't intercept 307 and 308 redirects.\n\n :meta private:\n :internal:\n \"\"\"\n if (\n not self.debug\n or not isinstance(request.routing_exception, RequestRedirect)\n or request.routing_exception.code in {307, 308}\n or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n ):\n raise request.routing_exception # type: ignore[misc]\n\n from .debughelpers import FormDataRoutingRedirect\n\n raise FormDataRoutingRedirect(request)"} {"repo":"flask","file":"src/flask/app.py","line":591,"symbol":"update_template_context","kind":"function","lang":"python","code":"def update_template_context(\n self, ctx: AppContext, context: dict[str, t.Any]\n ) -> None:\n \"\"\"Update the template context with some commonly used variables.\n This injects request, session, config and g into the template\n context as well as everything template context processors want\n to inject. Note that the as of Flask 0.6, the original values\n in the context will not be overridden if a context processor\n decides to return a value with the same key.\n\n :param context: the context as a dictionary that is updated in place\n to add extra variables.\n \"\"\"\n names: t.Iterable[str | None] = (None,)\n\n # A template may be rendered outside a request context.\n if ctx.has_request:\n names = chain(names, reversed(ctx.request.blueprints))\n\n # The values passed to render_template take precedence. Keep a\n # copy to re-apply after all context functions.\n orig_ctx = context.copy()\n\n for name in names:\n if name in self.template_context_processors:\n for func in self.template_context_processors[name]:\n context.up"} {"repo":"flask","file":"src/flask/app.py","line":621,"symbol":"make_shell_context","kind":"function","lang":"python","code":"def make_shell_context(self) -> dict[str, t.Any]:\n \"\"\"Returns the shell context for an interactive shell for this\n application. This runs all the registered shell context\n processors.\n\n .. versionadded:: 0.11\n \"\"\"\n rv = {\"app\": self, \"g\": g}\n for processor in self.shell_context_processors:\n rv.update(processor())\n return rv"} {"repo":"flask","file":"src/flask/app.py","line":633,"symbol":"run","kind":"function","lang":"python","code":"def run(\n self,\n host: str | None = None,\n port: int | None = None,\n debug: bool | None = None,\n load_dotenv: bool = True,\n **options: t.Any,\n ) -> None:\n \"\"\"Runs the application on a local development server.\n\n Do not use ``run()`` in a production setting. It is not intended to\n meet security and performance requirements for a production server.\n Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n If the :attr:`debug` flag is set the server will automatically reload\n for code changes and show a debugger in case an exception happened.\n\n If you want to run the application in debug mode, but disable the\n code execution on the interactive debugger, you can pass\n ``use_evalex=False`` as parameter. This will keep the debugger's\n traceback screen active, but disable code execution.\n\n It is not recommended to use this function for development with\n automatic reloading as this is badly supported. Instead you should\n be using the :command:`flask` command line script's ``run`` support.\n\n .. admonition:: Keep in Mind\n\n F"} {"repo":"flask","file":"src/flask/app.py","line":758,"symbol":"test_client","kind":"function","lang":"python","code":"def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:\n \"\"\"Creates a test client for this application. For information\n about unit testing head over to :doc:`/testing`.\n\n Note that if you are testing for assertions or exceptions in your\n application code, you must set ``app.testing = True`` in order for the\n exceptions to propagate to the test client. Otherwise, the exception\n will be handled by the application (not visible to the test client) and\n the only indication of an AssertionError or other exception will be a\n 500 status code response to the test client. See the :attr:`testing`\n attribute. For example::\n\n app.testing = True\n client = app.test_client()\n\n The test client can be used in a ``with`` block to defer the closing down\n of the context until the end of the ``with`` block. This is useful if\n you want to access the context locals for testing::\n\n with app.test_client() as c:\n rv = c.get('/?vodka=42')\n assert request.args['vodka'] == '42'\n\n Additionally, you may pass optional keyword argume"} {"repo":"flask","file":"src/flask/app.py","line":816,"symbol":"test_cli_runner","kind":"function","lang":"python","code":"def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:\n \"\"\"Create a CLI runner for testing CLI commands.\n See :ref:`testing-cli`.\n\n Returns an instance of :attr:`test_cli_runner_class`, by default\n :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n passed as the first argument.\n\n .. versionadded:: 1.0\n \"\"\"\n cls = self.test_cli_runner_class\n\n if cls is None:\n from .testing import FlaskCliRunner as cls\n\n return cls(self, **kwargs) # type: ignore"} {"repo":"flask","file":"src/flask/app.py","line":833,"symbol":"handle_http_exception","kind":"function","lang":"python","code":"def handle_http_exception(\n self, ctx: AppContext, e: HTTPException\n ) -> HTTPException | ft.ResponseReturnValue:\n \"\"\"Handles an HTTP exception. By default this will invoke the\n registered error handlers and fall back to returning the\n exception as response.\n\n .. versionchanged:: 1.0.3\n ``RoutingException``, used internally for actions such as\n slash redirects during routing, is not passed to error\n handlers.\n\n .. versionchanged:: 1.0\n Exceptions are looked up by code *and* by MRO, so\n ``HTTPException`` subclasses can be handled with a catch-all\n handler for the base ``HTTPException``.\n\n .. versionadded:: 0.3\n \"\"\"\n # Proxy exceptions don't have error codes. We want to always return\n # those unchanged as errors\n if e.code is None:\n return e\n\n # RoutingExceptions are used internally to trigger routing\n # actions, such as slash redirects raising RequestRedirect. They\n # are not raised or handled in user code.\n if isinstance(e, RoutingException):\n return e\n\n handler = self._find_err"} {"repo":"flask","file":"src/flask/app.py","line":868,"symbol":"handle_user_exception","kind":"function","lang":"python","code":"def handle_user_exception(\n self, ctx: AppContext, e: Exception\n ) -> HTTPException | ft.ResponseReturnValue:\n \"\"\"This method is called whenever an exception occurs that\n should be handled. A special case is :class:`~werkzeug\n .exceptions.HTTPException` which is forwarded to the\n :meth:`handle_http_exception` method. This function will either\n return a response value or reraise the exception with the same\n traceback.\n\n .. versionchanged:: 1.0\n Key errors raised from request data like ``form`` show the\n bad key in debug mode rather than a generic bad request\n message.\n\n .. versionadded:: 0.7\n \"\"\"\n if isinstance(e, BadRequestKeyError) and (\n self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n ):\n e.show_exception = True\n\n if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n return self.handle_http_exception(ctx, e)\n\n handler = self._find_error_handler(e, ctx.request.blueprints)\n\n if handler is None:\n raise\n\n return self.ensure_sync(handler)(e) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/app.py","line":900,"symbol":"handle_exception","kind":"function","lang":"python","code":"def handle_exception(self, ctx: AppContext, e: Exception) -> Response:\n \"\"\"Handle an exception that did not have an error handler\n associated with it, or that was raised from an error handler.\n This always causes a 500 ``InternalServerError``.\n\n Always sends the :data:`got_request_exception` signal.\n\n If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n mode, the error will be re-raised so that the debugger can\n display it. Otherwise, the original exception is logged, and\n an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n If an error handler is registered for ``InternalServerError`` or\n ``500``, it will be used. For consistency, the handler will\n always receive the ``InternalServerError``. The original\n unhandled exception is available as ``e.original_exception``.\n\n .. versionchanged:: 1.1.0\n Always passes the ``InternalServerError`` instance to the\n handler, setting ``original_exception`` to the unhandled\n error.\n\n .. versionchanged:: 1.1.0\n ``after_request`` functions and other finalization is done\n even"} {"repo":"flask","file":"src/flask/app.py","line":953,"symbol":"log_exception","kind":"function","lang":"python","code":"def log_exception(\n self,\n ctx: AppContext,\n exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],\n ) -> None:\n \"\"\"Logs an exception. This is called by :meth:`handle_exception`\n if debugging is disabled and right before the handler is called.\n The default implementation logs the exception as error on the\n :attr:`logger`.\n\n .. versionadded:: 0.8\n \"\"\"\n self.logger.error(\n f\"Exception on {ctx.request.path} [{ctx.request.method}]\", exc_info=exc_info\n )"} {"repo":"flask","file":"src/flask/app.py","line":969,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:\n \"\"\"Does the request dispatching. Matches the URL and returns the\n return value of the view or error handler. This does not have to\n be a response object. In order to convert the return value to a\n proper response object, call :func:`make_response`.\n\n .. versionchanged:: 0.7\n This no longer does the exception handling, this code was\n moved to the new :meth:`full_dispatch_request`.\n \"\"\"\n req = ctx.request\n\n if req.routing_exception is not None:\n self.raise_routing_exception(req)\n rule: Rule = req.url_rule # type: ignore[assignment]\n # if we provide automatic options for this URL and the\n # request came with the OPTIONS method, reply automatically\n if (\n getattr(rule, \"provide_automatic_options\", False)\n and req.method == \"OPTIONS\"\n ):\n return self.make_default_options_response(ctx)\n # otherwise dispatch to the handler for that endpoint\n view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]\n return self.ensure_sync(self"} {"repo":"flask","file":"src/flask/app.py","line":995,"symbol":"full_dispatch_request","kind":"function","lang":"python","code":"def full_dispatch_request(self, ctx: AppContext) -> Response:\n \"\"\"Dispatches the request and on top of that performs request\n pre and postprocessing as well as HTTP exception catching and\n error handling.\n\n .. versionadded:: 0.7\n \"\"\"\n if not self._got_first_request and self.should_ignore_error is not None:\n import warnings\n\n warnings.warn(\n \"The 'should_ignore_error' method is deprecated and will\"\n \" be removed in Flask 3.3. Handle errors as needed in\"\n \" teardown handlers instead.\",\n DeprecationWarning,\n stacklevel=1,\n )\n\n self._got_first_request = True\n\n try:\n request_started.send(self, _async_wrapper=self.ensure_sync)\n rv = self.preprocess_request(ctx)\n if rv is None:\n rv = self.dispatch_request(ctx)\n except Exception as e:\n rv = self.handle_user_exception(ctx, e)\n return self.finalize_request(ctx, rv)"} {"repo":"flask","file":"src/flask/app.py","line":1024,"symbol":"finalize_request","kind":"function","lang":"python","code":"def finalize_request(\n self,\n ctx: AppContext,\n rv: ft.ResponseReturnValue | HTTPException,\n from_error_handler: bool = False,\n ) -> Response:\n \"\"\"Given the return value from a view function this finalizes\n the request by converting it into a response and invoking the\n postprocessing functions. This is invoked for both normal\n request dispatching as well as error handlers.\n\n Because this means that it might be called as a result of a\n failure a special safe mode is available which can be enabled\n with the `from_error_handler` flag. If enabled, failures in\n response processing will be logged and otherwise ignored.\n\n :internal:\n \"\"\"\n response = self.make_response(rv)\n try:\n response = self.process_response(ctx, response)\n request_finished.send(\n self, _async_wrapper=self.ensure_sync, response=response\n )\n except Exception:\n if not from_error_handler:\n raise\n self.logger.exception(\n \"Request finalizing failed with an error while handling an error\"\n )\n "} {"repo":"flask","file":"src/flask/app.py","line":1056,"symbol":"make_default_options_response","kind":"function","lang":"python","code":"def make_default_options_response(self, ctx: AppContext) -> Response:\n \"\"\"This method is called to create the default ``OPTIONS`` response.\n This can be changed through subclassing to change the default\n behavior of ``OPTIONS`` responses.\n\n .. versionadded:: 0.7\n \"\"\"\n methods = ctx.url_adapter.allowed_methods() # type: ignore[union-attr]\n rv = self.response_class()\n rv.allow.update(methods)\n return rv"} {"repo":"flask","file":"src/flask/app.py","line":1068,"symbol":"ensure_sync","kind":"function","lang":"python","code":"def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:\n \"\"\"Ensure that the function is synchronous for WSGI workers.\n Plain ``def`` functions are returned as-is. ``async def``\n functions are wrapped to run and wait for the response.\n\n Override this method to change how the app runs async views.\n\n .. versionadded:: 2.0\n \"\"\"\n if iscoroutinefunction(func):\n return self.async_to_sync(func)\n\n return func"} {"repo":"flask","file":"src/flask/app.py","line":1082,"symbol":"async_to_sync","kind":"function","lang":"python","code":"def async_to_sync(\n self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]\n ) -> t.Callable[..., t.Any]:\n \"\"\"Return a sync function that will run the coroutine function.\n\n .. code-block:: python\n\n result = app.async_to_sync(func)(*args, **kwargs)\n\n Override this method to change how the app converts async code\n to be synchronously callable.\n\n .. versionadded:: 2.0\n \"\"\"\n try:\n from asgiref.sync import async_to_sync as asgiref_async_to_sync\n except ImportError:\n raise RuntimeError(\n \"Install Flask with the 'async' extra in order to use async views.\"\n ) from None\n\n return asgiref_async_to_sync(func)"} {"repo":"flask","file":"src/flask/app.py","line":1105,"symbol":"url_for","kind":"function","lang":"python","code":"def url_for(\n self,\n /,\n endpoint: str,\n *,\n _anchor: str | None = None,\n _method: str | None = None,\n _scheme: str | None = None,\n _external: bool | None = None,\n **values: t.Any,\n ) -> str:\n \"\"\"Generate a URL to the given endpoint with the given values.\n\n This is called by :func:`flask.url_for`, and can be called\n directly as well.\n\n An *endpoint* is the name of a URL rule, usually added with\n :meth:`@app.route() `, and usually the same name as the\n view function. A route defined in a :class:`~flask.Blueprint`\n will prepend the blueprint's name separated by a ``.`` to the\n endpoint.\n\n In some cases, such as email messages, you want URLs to include\n the scheme and domain, like ``https://example.com/hello``. When\n not in an active request, URLs will be external by default, but\n this requires setting :data:`SERVER_NAME` so Flask knows what\n domain to use. :data:`APPLICATION_ROOT` and\n :data:`PREFERRED_URL_SCHEME` should also be configured as\n needed. This config is only used when not in an active request.\n\n "} {"repo":"flask","file":"src/flask/app.py","line":1227,"symbol":"make_response","kind":"function","lang":"python","code":"def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n \"\"\"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n Converted to a JSON response.\n\n ``list``\n Converted to a JSON response.\n\n ``generator`` or ``iterator``\n A generator that returns ``str`` or ``bytes`` to be\n streamed as the response.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n "} {"repo":"flask","file":"src/flask/app.py","line":1369,"symbol":"preprocess_request","kind":"function","lang":"python","code":"def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:\n \"\"\"Called before the request is dispatched. Calls\n :attr:`url_value_preprocessors` registered with the app and the\n current blueprint (if any). Then calls :attr:`before_request_funcs`\n registered with the app and the blueprint.\n\n If any :meth:`before_request` handler returns a non-None value, the\n value is handled as if it was the return value from the view, and\n further request handling is stopped.\n \"\"\"\n req = ctx.request\n names = (None, *reversed(req.blueprints))\n\n for name in names:\n if name in self.url_value_preprocessors:\n for url_func in self.url_value_preprocessors[name]:\n url_func(req.endpoint, req.view_args)\n\n for name in names:\n if name in self.before_request_funcs:\n for before_func in self.before_request_funcs[name]:\n rv = self.ensure_sync(before_func)()\n\n if rv is not None:\n return rv # type: ignore[no-any-return]\n\n return None"} {"repo":"flask","file":"src/flask/app.py","line":1397,"symbol":"process_response","kind":"function","lang":"python","code":"def process_response(self, ctx: AppContext, response: Response) -> Response:\n \"\"\"Can be overridden in order to modify the response object\n before it's sent to the WSGI server. By default this will\n call all the :meth:`after_request` decorated functions.\n\n .. versionchanged:: 0.5\n As of Flask 0.5 the functions registered for after request\n execution are called in reverse order of registration.\n\n :param response: a :attr:`response_class` object.\n :return: a new response object or the same, has to be an\n instance of :attr:`response_class`.\n \"\"\"\n for func in ctx._after_request_functions:\n response = self.ensure_sync(func)(response)\n\n for name in chain(ctx.request.blueprints, (None,)):\n if name in self.after_request_funcs:\n for func in reversed(self.after_request_funcs[name]):\n response = self.ensure_sync(func)(response)\n\n if not self.session_interface.is_null_session(ctx._get_session()):\n self.session_interface.save_session(self, ctx._get_session(), response)\n\n return response"} {"repo":"flask","file":"src/flask/app.py","line":1423,"symbol":"do_teardown_request","kind":"function","lang":"python","code":"def do_teardown_request(\n self, ctx: AppContext, exc: BaseException | None = None\n ) -> None:\n \"\"\"Called after the request is dispatched and the response is finalized,\n right before the request context is popped. Called by\n :meth:`.AppContext.pop`.\n\n This calls all functions decorated with :meth:`teardown_request`, and\n :meth:`Blueprint.teardown_request` if a blueprint handled the request.\n Finally, the :data:`request_tearing_down` signal is sent.\n\n :param exc: An unhandled exception raised while dispatching the request.\n Passed to each teardown function.\n\n .. versionchanged:: 3.2\n All callbacks are called rather than stopping on the first error.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n \"\"\"\n collect_errors = _CollectErrors()\n\n for name in chain(ctx.request.blueprints, (None,)):\n if name in self.teardown_request_funcs:\n for func in reversed(self.teardown_request_funcs[name]):\n with collect_errors:\n self.ensure_sync(func)(exc)\n\n with collect_errors:\n request_t"} {"repo":"flask","file":"src/flask/app.py","line":1456,"symbol":"do_teardown_appcontext","kind":"function","lang":"python","code":"def do_teardown_appcontext(\n self, ctx: AppContext, exc: BaseException | None = None\n ) -> None:\n \"\"\"Called right before the application context is popped. Called by\n :meth:`.AppContext.pop`.\n\n This calls all functions decorated with :meth:`teardown_appcontext`.\n Then the :data:`appcontext_tearing_down` signal is sent.\n\n :param exc: An unhandled exception raised while the context was active.\n Passed to each teardown function.\n\n .. versionchanged:: 3.2\n All callbacks are called rather than stopping on the first error.\n\n .. versionadded:: 0.9\n \"\"\"\n collect_errors = _CollectErrors()\n\n for func in reversed(self.teardown_appcontext_funcs):\n with collect_errors:\n self.ensure_sync(func)(exc)\n\n with collect_errors:\n appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n collect_errors.raise_any(\"Errors during app teardown\")"} {"repo":"flask","file":"src/flask/app.py","line":1484,"symbol":"app_context","kind":"function","lang":"python","code":"def app_context(self) -> AppContext:\n \"\"\"Create an :class:`.AppContext`. When the context is pushed,\n :data:`.current_app` and :data:`.g` become available.\n\n A context is automatically pushed when handling each request, and when\n running any ``flask`` CLI command. Use this as a ``with`` block to\n manually push a context outside of those situations, such as during\n setup or testing.\n\n .. code-block:: python\n\n with app.app_context():\n init_db()\n\n See :doc:`/appcontext`.\n\n .. versionadded:: 0.9\n \"\"\"\n return AppContext(self)"} {"repo":"flask","file":"src/flask/app.py","line":1504,"symbol":"request_context","kind":"function","lang":"python","code":"def request_context(self, environ: WSGIEnvironment) -> AppContext:\n \"\"\"Create an :class:`.AppContext` with request information representing\n the given WSGI environment. A context is automatically pushed when\n handling each request. When the context is pushed, :data:`.request`,\n :data:`.session`, :data:`g`, and :data:`.current_app` become available.\n\n This method should not be used in your own code. Creating a valid WSGI\n environ is not trivial. Use :meth:`test_request_context` to correctly\n create a WSGI environ and request context instead.\n\n See :doc:`/appcontext`.\n\n :param environ: A WSGI environment.\n \"\"\"\n return AppContext.from_environ(self, environ)"} {"repo":"flask","file":"src/flask/app.py","line":1520,"symbol":"test_request_context","kind":"function","lang":"python","code":"def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:\n \"\"\"Create an :class:`.AppContext` with request information created from\n the given arguments. When the context is pushed, :data:`.request`,\n :data:`.session`, :data:`g`, and :data:`.current_app` become available.\n\n This is useful during testing to run a function that uses request data\n without dispatching a full request. Use this as a ``with`` block to push\n a context.\n\n .. code-block:: python\n\n with app.test_request_context(...):\n generate_report()\n\n See :doc:`/appcontext`.\n\n Takes the same arguments as Werkzeug's\n :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n the application. See the linked Werkzeug docs for most of the\n available arguments. Flask-specific behavior is listed here.\n\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,\n and :data:`APPLICATION_ROOT`.\n"} {"repo":"flask","file":"src/flask/app.py","line":1569,"symbol":"wsgi_app","kind":"function","lang":"python","code":"def wsgi_app(\n self, environ: WSGIEnvironment, start_response: StartResponse\n ) -> cabc.Iterable[bytes]:\n \"\"\"The actual WSGI application. This is not implemented in\n :meth:`__call__` so that middlewares can be applied without\n losing a reference to the app object. Instead of doing this::\n\n app = MyMiddleware(app)\n\n It's a better idea to do this instead::\n\n app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n Then you still have the original application object around and\n can continue to call methods on it.\n\n .. versionchanged:: 0.7\n Teardown events for the request and app contexts are called\n even if an unhandled error occurs. Other events may not be\n called depending on when an error occurs during dispatch.\n\n :param environ: A WSGI environment.\n :param start_response: A callable accepting a status code,\n a list of headers, and an optional exception context to\n start the response.\n \"\"\"\n ctx = self.request_context(environ)\n error: BaseException | None = None\n try:\n try:\n ctx.push()\n "} {"repo":"flask","file":"src/flask/app.py","line":1621,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(\n self, environ: WSGIEnvironment, start_response: StartResponse\n ) -> cabc.Iterable[bytes]:\n \"\"\"The WSGI server calls the Flask application object as the\n WSGI application. This calls :meth:`wsgi_app`, which can be\n wrapped to apply middleware.\n \"\"\"\n return self.wsgi_app(environ, start_response)"} {"repo":"flask","file":"src/flask/blueprints.py","line":18,"symbol":"Blueprint","kind":"class","lang":"python","code":"class Blueprint(SansioBlueprint):\n def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: str | os.PathLike[str] | None = None,\n static_url_path: str | None = None,\n template_folder: str | os.PathLike[str] | None = None,\n url_prefix: str | None = None,\n subdomain: str | None = None,\n url_defaults: dict[str, t.Any] | None = None,\n root_path: str | None = None,\n cli_group: str | None = _sentinel, # type: ignore\n ) -> None:\n super().__init__(\n name,\n import_name,\n static_folder,\n static_url_path,\n template_folder,\n url_prefix,\n subdomain,\n url_defaults,\n root_path,\n cli_group,\n )\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n # Set the name of the Click group in case someone wants to add\n # the app's commands to another CLI to"} {"repo":"flask","file":"src/flask/blueprints.py","line":19,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: str | os.PathLike[str] | None = None,\n static_url_path: str | None = None,\n template_folder: str | os.PathLike[str] | None = None,\n url_prefix: str | None = None,\n subdomain: str | None = None,\n url_defaults: dict[str, t.Any] | None = None,\n root_path: str | None = None,\n cli_group: str | None = _sentinel, # type: ignore\n ) -> None:\n super().__init__(\n name,\n import_name,\n static_folder,\n static_url_path,\n template_folder,\n url_prefix,\n subdomain,\n url_defaults,\n root_path,\n cli_group,\n )\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n # Set the name of the Click group in case someone wants to add\n # the app's commands to another CLI tool.\n self.cli.name = self.name"} {"repo":"flask","file":"src/flask/blueprints.py","line":55,"symbol":"get_send_file_max_age","kind":"function","lang":"python","code":"def get_send_file_max_age(self, filename: str | None) -> int | None:\n \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n value for a given file path if it wasn't passed.\n\n By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n the configuration of :data:`~flask.current_app`. This defaults\n to ``None``, which tells the browser to use conditional requests\n instead of a timed cache, which is usually preferable.\n\n Note this is a duplicate of the same method in the Flask\n class.\n\n .. versionchanged:: 2.0\n The default configuration is ``None`` instead of 12 hours.\n\n .. versionadded:: 0.9\n \"\"\"\n value = current_app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n if value is None:\n return None\n\n if isinstance(value, timedelta):\n return int(value.total_seconds())\n\n return value # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/blueprints.py","line":82,"symbol":"send_static_file","kind":"function","lang":"python","code":"def send_static_file(self, filename: str) -> Response:\n \"\"\"The view function used to serve files from\n :attr:`static_folder`. A route is automatically registered for\n this view at :attr:`static_url_path` if :attr:`static_folder` is\n set.\n\n Note this is a duplicate of the same method in the Flask\n class.\n\n .. versionadded:: 0.5\n\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n # send_file only knows to call get_send_file_max_age on the app,\n # call it here so it works for blueprints too.\n max_age = self.get_send_file_max_age(filename)\n return send_from_directory(\n t.cast(str, self.static_folder), filename, max_age=max_age\n )"} {"repo":"flask","file":"src/flask/blueprints.py","line":104,"symbol":"open_resource","kind":"function","lang":"python","code":"def open_resource(\n self, resource: str, mode: str = \"rb\", encoding: str | None = \"utf-8\"\n ) -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to :attr:`root_path` for reading. The\n blueprint-relative equivalent of the app's :meth:`~.Flask.open_resource`\n method.\n\n :param resource: Path to the resource relative to :attr:`root_path`.\n :param mode: Open the file in this mode. Only reading is supported,\n valid values are ``\"r\"`` (or ``\"rt\"``) and ``\"rb\"``.\n :param encoding: Open the file with this encoding when opening in text\n mode. This is ignored when opening in binary mode.\n\n .. versionchanged:: 3.1\n Added the ``encoding`` parameter.\n \"\"\"\n if mode not in {\"r\", \"rt\", \"rb\"}:\n raise ValueError(\"Resources can only be opened for reading.\")\n\n path = os.path.join(self.root_path, resource)\n\n if mode == \"rb\":\n return open(path, mode) # pyright: ignore\n\n return open(path, mode, encoding=encoding)"} {"repo":"flask","file":"src/flask/cli.py","line":37,"symbol":"NoAppException","kind":"class","lang":"python","code":"class NoAppException(click.UsageError):\n \"\"\"Raised if an application cannot be found or loaded.\"\"\""} {"repo":"flask","file":"src/flask/cli.py","line":41,"symbol":"find_best_app","kind":"function","lang":"python","code":"def find_best_app(module: ModuleType) -> Flask:\n \"\"\"Given a module instance this tries to find the best possible\n application in the module or raises an exception.\n \"\"\"\n from . import Flask\n\n # Search for the most common names first.\n for attr_name in (\"app\", \"application\"):\n app = getattr(module, attr_name, None)\n\n if isinstance(app, Flask):\n return app\n\n # Otherwise find the only object that is a Flask instance.\n matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]\n\n if len(matches) == 1:\n return matches[0]\n elif len(matches) > 1:\n raise NoAppException(\n \"Detected multiple Flask applications in module\"\n f\" '{module.__name__}'. Use '{module.__name__}:name'\"\n \" to specify the correct one.\"\n )\n\n # Search for app factory functions.\n for attr_name in (\"create_app\", \"make_app\"):\n app_factory = getattr(module, attr_name, None)\n\n if inspect.isfunction(app_factory):\n try:\n app = app_factory()\n\n if isinstance(app, Flask):\n return app\n except TypeError as e:\n i"} {"repo":"flask","file":"src/flask/cli.py","line":94,"symbol":"_called_with_wrong_args","kind":"function","lang":"python","code":"def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool:\n \"\"\"Check whether calling a function raised a ``TypeError`` because\n the call failed or because something in the factory raised the\n error.\n\n :param f: The function that was called.\n :return: ``True`` if the call failed.\n \"\"\"\n tb = sys.exc_info()[2]\n\n try:\n while tb is not None:\n if tb.tb_frame.f_code is f.__code__:\n # In the function, it was called successfully.\n return False\n\n tb = tb.tb_next\n\n # Didn't reach the function.\n return True\n finally:\n # Delete tb to break a circular reference.\n # https://docs.python.org/2/library/sys.html#sys.exc_info\n del tb"} {"repo":"flask","file":"src/flask/cli.py","line":120,"symbol":"find_app_by_string","kind":"function","lang":"python","code":"def find_app_by_string(module: ModuleType, app_name: str) -> Flask:\n \"\"\"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n \"\"\"\n from . import Flask\n\n # Parse app_name as a single expression to determine if it's a valid\n # attribute name or function call.\n try:\n expr = ast.parse(app_name.strip(), mode=\"eval\").body\n except SyntaxError:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n ) from None\n\n if isinstance(expr, ast.Name):\n name = expr.id\n args = []\n kwargs = {}\n elif isinstance(expr, ast.Call):\n # Ensure the function name is an attribute name only.\n if not isinstance(expr.func, ast.Name):\n raise NoAppException(\n f\"Function reference must be a simple name: {app_name!r}.\"\n )\n\n name = expr.func.id\n\n # Parse the positional and keyword arguments as literals.\n try:\n args = [ast.literal_eval(arg) for arg in expr.args]\n kwargs = {\n kw.arg: ast.literal_eval(kw.value)\n "} {"repo":"flask","file":"src/flask/cli.py","line":200,"symbol":"prepare_import","kind":"function","lang":"python","code":"def prepare_import(path: str) -> str:\n \"\"\"Given a filename this will try to calculate the python path, add it\n to the search path and return the actual module name that is expected.\n \"\"\"\n path = os.path.realpath(path)\n\n fname, ext = os.path.splitext(path)\n if ext == \".py\":\n path = fname\n\n if os.path.basename(path) == \"__init__\":\n path = os.path.dirname(path)\n\n module_name = []\n\n # move up until outside package structure (no __init__.py)\n while True:\n path, name = os.path.split(path)\n module_name.append(name)\n\n if not os.path.exists(os.path.join(path, \"__init__.py\")):\n break\n\n if sys.path[0] != path:\n sys.path.insert(0, path)\n\n return \".\".join(module_name[::-1])"} {"repo":"flask","file":"src/flask/cli.py","line":230,"symbol":"locate_app","kind":"function","lang":"python","code":"def locate_app(\n module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True\n) -> Flask: ..."} {"repo":"flask","file":"src/flask/cli.py","line":236,"symbol":"locate_app","kind":"function","lang":"python","code":"def locate_app(\n module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...\n) -> Flask | None: ..."} {"repo":"flask","file":"src/flask/cli.py","line":241,"symbol":"locate_app","kind":"function","lang":"python","code":"def locate_app(\n module_name: str, app_name: str | None, raise_if_not_found: bool = True\n) -> Flask | None:\n try:\n __import__(module_name)\n except ImportError:\n # Reraise the ImportError if it occurred within the imported module.\n # Determine this by checking whether the trace has a depth > 1.\n if sys.exc_info()[2].tb_next: # type: ignore[union-attr]\n raise NoAppException(\n f\"While importing {module_name!r}, an ImportError was\"\n f\" raised:\\n\\n{traceback.format_exc()}\"\n ) from None\n elif raise_if_not_found:\n raise NoAppException(f\"Could not import {module_name!r}.\") from None\n else:\n return None\n\n module = sys.modules[module_name]\n\n if app_name is None:\n return find_best_app(module)\n else:\n return find_app_by_string(module, app_name)"} {"repo":"flask","file":"src/flask/cli.py","line":267,"symbol":"get_version","kind":"function","lang":"python","code":"def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:\n if not value or ctx.resilient_parsing:\n return\n\n flask_version = importlib.metadata.version(\"flask\")\n werkzeug_version = importlib.metadata.version(\"werkzeug\")\n\n click.echo(\n f\"Python {platform.python_version()}\\n\"\n f\"Flask {flask_version}\\n\"\n f\"Werkzeug {werkzeug_version}\",\n color=ctx.color,\n )\n ctx.exit()"} {"repo":"flask","file":"src/flask/cli.py","line":293,"symbol":"ScriptInfo","kind":"class","lang":"python","code":"class ScriptInfo:\n \"\"\"Helper object to deal with Flask applications. This is usually not\n necessary to interface with as it's used internally in the dispatching\n to click. In future versions of Flask this object will most likely play\n a bigger role. Typically it's created automatically by the\n :class:`FlaskGroup` but you can also manually create it and pass it\n onwards as click object.\n\n .. versionchanged:: 3.1\n Added the ``load_dotenv_defaults`` parameter and attribute.\n \"\"\"\n\n def __init__(\n self,\n app_import_path: str | None = None,\n create_app: t.Callable[..., Flask] | None = None,\n set_debug_flag: bool = True,\n load_dotenv_defaults: bool = True,\n ) -> None:\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data: dict[t.Any, t.Any] = {}\n self.set_debug_flag = set_debug_flag"} {"repo":"flask","file":"src/flask/cli.py","line":305,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n app_import_path: str | None = None,\n create_app: t.Callable[..., Flask] | None = None,\n set_debug_flag: bool = True,\n load_dotenv_defaults: bool = True,\n ) -> None:\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data: dict[t.Any, t.Any] = {}\n self.set_debug_flag = set_debug_flag\n\n self.load_dotenv_defaults = get_load_dotenv(load_dotenv_defaults)\n \"\"\"Whether default ``.flaskenv`` and ``.env`` files should be loaded.\n\n ``ScriptInfo`` doesn't load anything, this is for reference when doing\n the load elsewhere during processing.\n\n .. versionadded:: 3.1\n \"\"\"\n\n self._loaded_app: Flask | None = None"} {"repo":"flask","file":"src/flask/cli.py","line":333,"symbol":"load_app","kind":"function","lang":"python","code":"def load_app(self) -> Flask:\n \"\"\"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n \"\"\"\n if self._loaded_app is not None:\n return self._loaded_app\n app: Flask | None = None\n if self.create_app is not None:\n app = self.create_app()\n else:\n if self.app_import_path:\n path, name = (\n re.split(r\":(?![\\\\/])\", self.app_import_path, maxsplit=1) + [None]\n )[:2]\n import_name = prepare_import(path)\n app = locate_app(import_name, name)\n else:\n for path in (\"wsgi.py\", \"app.py\"):\n import_name = prepare_import(path)\n app = locate_app(import_name, None, raise_if_not_found=False)\n\n if app is not None:\n break\n\n if app is None:\n raise NoAppException(\n \"Could not locate a Flask application. Use the\"\n \" 'flask --app' option, 'FLASK_APP' environment\"\n \" variable, or a 'wsgi.py' "} {"repo":"flask","file":"src/flask/cli.py","line":380,"symbol":"with_appcontext","kind":"function","lang":"python","code":"def with_appcontext(f: F) -> F:\n \"\"\"Wraps a callback so that it's guaranteed to be executed with the\n script's application context.\n\n Custom commands (and their options) registered under ``app.cli`` or\n ``blueprint.cli`` will always have an app context available, this\n decorator is not required in that case.\n\n .. versionchanged:: 2.2\n The app context is active for subcommands as well as the\n decorated callback. The app context is always available to\n ``app.cli`` command and parameter callbacks.\n \"\"\"\n\n @click.pass_context\n def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if not current_app:\n app = ctx.ensure_object(ScriptInfo).load_app()\n ctx.with_resource(app.app_context())\n\n return ctx.invoke(f, *args, **kwargs)\n\n return update_wrapper(decorator, f) # type: ignore[return-value]"} {"repo":"flask","file":"src/flask/cli.py","line":395,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if not current_app:\n app = ctx.ensure_object(ScriptInfo).load_app()\n ctx.with_resource(app.app_context())\n\n return ctx.invoke(f, *args, **kwargs)"} {"repo":"flask","file":"src/flask/cli.py","line":405,"symbol":"AppGroup","kind":"class","lang":"python","code":"class AppGroup(click.Group):\n \"\"\"This works similar to a regular click :class:`~click.Group` but it\n changes the behavior of the :meth:`command` decorator so that it\n automatically wraps the functions in :func:`with_appcontext`.\n\n Not to be confused with :class:`FlaskGroup`.\n \"\"\"\n\n def command( # type: ignore[override]\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n if wrap_for_ctx:\n f = with_appcontext(f)\n return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]\n\n return decorator\n\n def group( # type: ignore[override]\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n \"\"\"This works exactly like the method of the "} {"repo":"flask","file":"src/flask/cli.py","line":413,"symbol":"command","kind":"function","lang":"python","code":"def command( # type: ignore[override]\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n if wrap_for_ctx:\n f = with_appcontext(f)\n return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]\n\n return decorator"} {"repo":"flask","file":"src/flask/cli.py","line":422,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: t.Callable[..., t.Any]) -> click.Command:\n if wrap_for_ctx:\n f = with_appcontext(f)\n return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/cli.py","line":429,"symbol":"group","kind":"function","lang":"python","code":"def group( # type: ignore[override]\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n \"\"\"\n kwargs.setdefault(\"cls\", AppGroup)\n return super().group(*args, **kwargs) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/cli.py","line":440,"symbol":"_set_app","kind":"function","lang":"python","code":"def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:\n if value is None:\n return None\n\n info = ctx.ensure_object(ScriptInfo)\n info.app_import_path = value\n return value"} {"repo":"flask","file":"src/flask/cli.py","line":468,"symbol":"_set_debug","kind":"function","lang":"python","code":"def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:\n # If the flag isn't provided, it will default to False. Don't use\n # that, let debug be set by env in that case.\n source = ctx.get_parameter_source(param.name)\n\n if source is not None and source in (\n ParameterSource.DEFAULT,\n ParameterSource.DEFAULT_MAP,\n ):\n return None\n\n # Set with env var instead of ScriptInfo.load so that it can be\n # accessed early during a factory function.\n os.environ[\"FLASK_DEBUG\"] = \"1\" if value else \"0\"\n return value"} {"repo":"flask","file":"src/flask/cli.py","line":493,"symbol":"_env_file_callback","kind":"function","lang":"python","code":"def _env_file_callback(\n ctx: click.Context, param: click.Option, value: str | None\n) -> str | None:\n try:\n import dotenv # noqa: F401\n except ImportError:\n # Only show an error if a value was passed, otherwise we still want to\n # call load_dotenv and show a message without exiting.\n if value is not None:\n raise click.BadParameter(\n \"python-dotenv must be installed to load an env file.\",\n ctx=ctx,\n param=param,\n ) from None\n\n # Load if a value was passed, or we want to load default files, or both.\n if value is not None or ctx.obj.load_dotenv_defaults:\n load_dotenv(value, load_defaults=ctx.obj.load_dotenv_defaults)\n\n return value"} {"repo":"flask","file":"src/flask/cli.py","line":531,"symbol":"FlaskGroup","kind":"class","lang":"python","code":"class FlaskGroup(AppGroup):\n \"\"\"Special subclass of the :class:`AppGroup` group that supports\n loading more commands from the configured Flask app. Normally a\n developer does not have to interface with this class but there are\n some very advanced use cases for which it makes sense to create an\n instance of this. see :ref:`custom-scripts`.\n\n :param add_default_commands: if this is True then the default run and\n shell commands will be added.\n :param add_version_option: adds the ``--version`` option.\n :param create_app: an optional callback that is passed the script info and\n returns the loaded app.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param set_debug_flag: Set the app's debug flag.\n\n .. versionchanged:: 3.1\n ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.\n\n .. versionchanged:: 2.2\n Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.\n\n .. versionchanged:: 2.2\n An app context is pushed "} {"repo":"flask","file":"src/flask/cli.py","line":563,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n add_default_commands: bool = True,\n create_app: t.Callable[..., Flask] | None = None,\n add_version_option: bool = True,\n load_dotenv: bool = True,\n set_debug_flag: bool = True,\n **extra: t.Any,\n ) -> None:\n params: list[click.Parameter] = list(extra.pop(\"params\", None) or ())\n # Processing is done with option callbacks instead of a group\n # callback. This allows users to make a custom group callback\n # without losing the behavior. --env-file must come first so\n # that it is eagerly evaluated before --app.\n params.extend((_env_file_option, _app_option, _debug_option))\n\n if add_version_option:\n params.append(version_option)\n\n if \"context_settings\" not in extra:\n extra[\"context_settings\"] = {}\n\n extra[\"context_settings\"].setdefault(\"auto_envvar_prefix\", \"FLASK\")\n\n super().__init__(params=params, **extra)\n\n self.create_app = create_app\n self.load_dotenv = load_dotenv\n self.set_debug_flag = set_debug_flag\n\n if add_default_commands:\n self.add_command(run_command)\n self.add_co"} {"repo":"flask","file":"src/flask/cli.py","line":600,"symbol":"_load_plugin_commands","kind":"function","lang":"python","code":"def _load_plugin_commands(self) -> None:\n if self._loaded_plugin_commands:\n return\n\n for ep in importlib.metadata.entry_points(group=\"flask.commands\"):\n self.add_command(ep.load(), ep.name)\n\n self._loaded_plugin_commands = True"} {"repo":"flask","file":"src/flask/cli.py","line":609,"symbol":"get_command","kind":"function","lang":"python","code":"def get_command(self, ctx: click.Context, name: str) -> click.Command | None:\n self._load_plugin_commands()\n # Look up built-in and plugin commands, which should be\n # available even if the app fails to load.\n rv = super().get_command(ctx, name)\n\n if rv is not None:\n return rv\n\n info = ctx.ensure_object(ScriptInfo)\n\n # Look up commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n app = info.load_app()\n except NoAppException as e:\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n return None\n\n # Push an app context for the loaded app unless it is already\n # active somehow. This makes the context available to parameter\n # and command callbacks without needing @with_appcontext.\n if not current_app or current_app._get_current_object() is not app:\n ctx.with_resource(app.app_context())\n\n return app.cli.get_command(ctx, name)"} {"repo":"flask","file":"src/flask/cli.py","line":636,"symbol":"list_commands","kind":"function","lang":"python","code":"def list_commands(self, ctx: click.Context) -> list[str]:\n self._load_plugin_commands()\n # Start with the built-in and plugin commands.\n rv = set(super().list_commands(ctx))\n info = ctx.ensure_object(ScriptInfo)\n\n # Add commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n rv.update(info.load_app().cli.list_commands(ctx))\n except NoAppException as e:\n # When an app couldn't be loaded, show the error message\n # without the traceback.\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n except Exception:\n # When any other errors occurred during loading, show the\n # full traceback.\n click.secho(f\"{traceback.format_exc()}\\n\", err=True, fg=\"red\")\n\n return sorted(rv)"} {"repo":"flask","file":"src/flask/cli.py","line":657,"symbol":"make_context","kind":"function","lang":"python","code":"def make_context(\n self,\n info_name: str | None,\n args: list[str],\n parent: click.Context | None = None,\n **extra: t.Any,\n ) -> click.Context:\n # Set a flag to tell app.run to become a no-op. If app.run was\n # not in a __name__ == __main__ guard, it would start the server\n # when importing, blocking whatever command is being called.\n os.environ[\"FLASK_RUN_FROM_CLI\"] = \"true\"\n\n if \"obj\" not in extra and \"obj\" not in self.context_settings:\n extra[\"obj\"] = ScriptInfo(\n create_app=self.create_app,\n set_debug_flag=self.set_debug_flag,\n load_dotenv_defaults=self.load_dotenv,\n )\n\n return super().make_context(info_name, args, parent=parent, **extra)"} {"repo":"flask","file":"src/flask/cli.py","line":678,"symbol":"parse_args","kind":"function","lang":"python","code":"def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:\n if (not args and self.no_args_is_help) or (\n len(args) == 1 and args[0] in self.get_help_option_names(ctx)\n ):\n # Attempt to load --env-file and --app early in case they\n # were given as env vars. Otherwise no_args_is_help will not\n # see commands from app.cli.\n _env_file_option.handle_parse_result(ctx, {}, [])\n _app_option.handle_parse_result(ctx, {}, [])\n\n return super().parse_args(ctx, args)"} {"repo":"flask","file":"src/flask/cli.py","line":691,"symbol":"_path_is_ancestor","kind":"function","lang":"python","code":"def _path_is_ancestor(path: str, other: str) -> bool:\n \"\"\"Take ``other`` and remove the length of ``path`` from it. Then join it\n to ``path``. If it is the original value, ``path`` is an ancestor of\n ``other``.\"\"\"\n return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other"} {"repo":"flask","file":"src/flask/cli.py","line":698,"symbol":"load_dotenv","kind":"function","lang":"python","code":"def load_dotenv(\n path: str | os.PathLike[str] | None = None, load_defaults: bool = True\n) -> bool:\n \"\"\"Load \"dotenv\" files to set environment variables. A given path takes\n precedence over ``.env``, which takes precedence over ``.flaskenv``. After\n loading and combining these files, values are only set if the key is not\n already set in ``os.environ``.\n\n This is a no-op if `python-dotenv`_ is not installed.\n\n .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n\n :param path: Load the file at this location.\n :param load_defaults: Search for and load the default ``.flaskenv`` and\n ``.env`` files.\n :return: ``True`` if at least one env var was loaded.\n\n .. versionchanged:: 3.1\n Added the ``load_defaults`` parameter. A given path takes precedence\n over default files.\n\n .. versionchanged:: 2.0\n The current directory is not changed to the location of the\n loaded file.\n\n .. versionchanged:: 2.0\n When loading the env files, set the default encoding to UTF-8.\n\n .. versionchanged:: 1.1.0\n Returns ``False`` when python-dotenv is not installed, or when\n the given path isn't a file"} {"repo":"flask","file":"src/flask/cli.py","line":766,"symbol":"show_server_banner","kind":"function","lang":"python","code":"def show_server_banner(debug: bool, app_import_path: str | None) -> None:\n \"\"\"Show extra startup messages the first time the server is run,\n ignoring the reloader.\n \"\"\"\n if is_running_from_reloader():\n return\n\n if app_import_path is not None:\n click.echo(f\" * Serving Flask app '{app_import_path}'\")\n\n if debug is not None:\n click.echo(f\" * Debug mode: {'on' if debug else 'off'}\")"} {"repo":"flask","file":"src/flask/cli.py","line":780,"symbol":"CertParamType","kind":"class","lang":"python","code":"class CertParamType(click.ParamType): # type: ignore[type-arg]\n \"\"\"Click option type for the ``--cert`` option. Allows either an\n existing file, the string ``'adhoc'``, or an import for a\n :class:`~ssl.SSLContext` object.\n \"\"\"\n\n name = \"path\"\n\n def __init__(self) -> None:\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n def convert(\n self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n ) -> t.Any:\n try:\n import ssl\n except ImportError:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n ) from None\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower() # type: ignore[union-attr]\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptog"} {"repo":"flask","file":"src/flask/cli.py","line":788,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)"} {"repo":"flask","file":"src/flask/cli.py","line":791,"symbol":"convert","kind":"function","lang":"python","code":"def convert(\n self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n ) -> t.Any:\n try:\n import ssl\n except ImportError:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n ) from None\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower() # type: ignore[union-attr]\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptography library.\",\n ctx,\n param,\n ) from None\n\n return value\n\n obj = import_string(value, silent=True)\n\n if isinstance(obj, ssl.SSLContext):\n return obj\n\n raise"} {"repo":"flask","file":"src/flask/cli.py","line":828,"symbol":"_validate_key","kind":"function","lang":"python","code":"def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any:\n \"\"\"The ``--key`` option must be specified when ``--cert`` is a file.\n Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.\n \"\"\"\n cert = ctx.params.get(\"cert\")\n is_adhoc = cert == \"adhoc\"\n\n try:\n import ssl\n except ImportError:\n is_context = False\n else:\n is_context = isinstance(cert, ssl.SSLContext)\n\n if value is not None:\n if is_adhoc:\n raise click.BadParameter(\n 'When \"--cert\" is \"adhoc\", \"--key\" is not used.', ctx, param\n )\n\n if is_context:\n raise click.BadParameter(\n 'When \"--cert\" is an SSLContext object, \"--key\" is not used.',\n ctx,\n param,\n )\n\n if not cert:\n raise click.BadParameter('\"--cert\" must also be specified.', ctx, param)\n\n ctx.params[\"cert\"] = cert, value\n\n else:\n if cert and not (is_adhoc or is_context):\n raise click.BadParameter('Required when using \"--cert\".', ctx, param)\n\n return value"} {"repo":"flask","file":"src/flask/cli.py","line":867,"symbol":"SeparatedPathType","kind":"class","lang":"python","code":"class SeparatedPathType(click.Path):\n \"\"\"Click option type that accepts a list of values separated by the\n OS's path separator (``:``, ``;`` on Windows). Each value is\n validated as a :class:`click.Path` type.\n \"\"\"\n\n def convert(\n self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n ) -> t.Any:\n items = self.split_envvar_value(value)\n # can't call no-arg super() inside list comprehension until Python 3.12\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]"} {"repo":"flask","file":"src/flask/cli.py","line":873,"symbol":"convert","kind":"function","lang":"python","code":"def convert(\n self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None\n ) -> t.Any:\n items = self.split_envvar_value(value)\n # can't call no-arg super() inside list comprehension until Python 3.12\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]"} {"repo":"flask","file":"src/flask/cli.py","line":935,"symbol":"run_command","kind":"function","lang":"python","code":"def run_command(\n info: ScriptInfo,\n host: str,\n port: int,\n reload: bool,\n debugger: bool,\n with_threads: bool,\n cert: ssl.SSLContext | tuple[str, str | None] | t.Literal[\"adhoc\"] | None,\n extra_files: list[str] | None,\n exclude_patterns: list[str] | None,\n) -> None:\n \"\"\"Run a local development server.\n\n This server is for development purposes only. It does not provide\n the stability, security, or performance of production WSGI servers.\n\n The reloader and debugger are enabled by default with the '--debug'\n option.\n \"\"\"\n try:\n app: WSGIApplication = info.load_app() # pyright: ignore\n except Exception as e:\n if is_running_from_reloader():\n # When reloading, print out the error immediately, but raise\n # it later so the debugger or server can handle it.\n traceback.print_exc()\n err = e\n\n def app(\n environ: WSGIEnvironment, start_response: StartResponse\n ) -> cabc.Iterable[bytes]:\n raise err from None\n\n else:\n # When not reloading, raise the error immediately so the\n # command fails.\n rai"} {"repo":"flask","file":"src/flask/cli.py","line":963,"symbol":"app","kind":"function","lang":"python","code":"def app(\n environ: WSGIEnvironment, start_response: StartResponse\n ) -> cabc.Iterable[bytes]:\n raise err from None"} {"repo":"flask","file":"src/flask/cli.py","line":1001,"symbol":"shell_command","kind":"function","lang":"python","code":"def shell_command() -> None:\n \"\"\"Run an interactive Python shell in the context of a given\n Flask application. The application will populate the default\n namespace of this shell according to its configuration.\n\n This is useful for executing small snippets of management code\n without having to manually configure the application.\n \"\"\"\n import code\n\n banner = (\n f\"Python {sys.version} on {sys.platform}\\n\"\n f\"App: {current_app.import_name}\\n\"\n f\"Instance: {current_app.instance_path}\"\n )\n ctx: dict[str, t.Any] = {}\n\n # Support the regular Python interpreter startup script if someone\n # is using it.\n startup = os.environ.get(\"PYTHONSTARTUP\")\n if startup and os.path.isfile(startup):\n with open(startup) as f:\n eval(compile(f.read(), startup, \"exec\"), ctx)\n\n ctx.update(current_app.make_shell_context())\n\n # Site, customize, or startup script can set a hook to call when\n # entering interactive mode. The default one sets up readline with\n # tab and history completion.\n interactive_hook = getattr(sys, \"__interactivehook__\", None)\n\n if interactive_hook is not None:\n try:\n import "} {"repo":"flask","file":"src/flask/cli.py","line":1061,"symbol":"routes_command","kind":"function","lang":"python","code":"def routes_command(sort: str, all_methods: bool) -> None:\n \"\"\"Show all registered routes with endpoints and methods.\"\"\"\n rules = list(current_app.url_map.iter_rules())\n\n if not rules:\n click.echo(\"No routes were registered.\")\n return\n\n ignored_methods = set() if all_methods else {\"HEAD\", \"OPTIONS\"}\n host_matching = current_app.url_map.host_matching\n has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules)\n rows = []\n\n for rule in rules:\n row = [\n rule.endpoint,\n \", \".join(sorted((rule.methods or set()) - ignored_methods)),\n ]\n\n if has_domain:\n row.append((rule.host if host_matching else rule.subdomain) or \"\")\n\n row.append(rule.rule)\n rows.append(row)\n\n headers = [\"Endpoint\", \"Methods\"]\n sorts = [\"endpoint\", \"methods\"]\n\n if has_domain:\n headers.append(\"Host\" if host_matching else \"Subdomain\")\n sorts.append(\"domain\")\n\n headers.append(\"Rule\")\n sorts.append(\"rule\")\n\n try:\n rows.sort(key=itemgetter(sorts.index(sort)))\n except ValueError:\n pass\n\n rows.insert(0, headers)\n widths = [max(len(row[i]) for row"} {"repo":"flask","file":"src/flask/cli.py","line":1122,"symbol":"main","kind":"function","lang":"python","code":"def main() -> None:\n cli.main()"} {"repo":"flask","file":"src/flask/config.py","line":20,"symbol":"ConfigAttribute","kind":"class","lang":"python","code":"class ConfigAttribute(t.Generic[T]):\n \"\"\"Makes an attribute forward to the config\"\"\"\n\n def __init__(\n self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n ) -> None:\n self.__name__ = name\n self.get_converter = get_converter\n\n @t.overload\n def __get__(self, obj: None, owner: None) -> te.Self: ...\n\n @t.overload\n def __get__(self, obj: App, owner: type[App]) -> T: ...\n\n def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n if obj is None:\n return self\n\n rv = obj.config[self.__name__]\n\n if self.get_converter is not None:\n rv = self.get_converter(rv)\n\n return rv # type: ignore[no-any-return]\n\n def __set__(self, obj: App, value: t.Any) -> None:\n obj.config[self.__name__] = value"} {"repo":"flask","file":"src/flask/config.py","line":23,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self, name: str, get_converter: t.Callable[[t.Any], T] | None = None\n ) -> None:\n self.__name__ = name\n self.get_converter = get_converter"} {"repo":"flask","file":"src/flask/config.py","line":30,"symbol":"__get__","kind":"function","lang":"python","code":"def __get__(self, obj: None, owner: None) -> te.Self: ..."} {"repo":"flask","file":"src/flask/config.py","line":33,"symbol":"__get__","kind":"function","lang":"python","code":"def __get__(self, obj: App, owner: type[App]) -> T: ..."} {"repo":"flask","file":"src/flask/config.py","line":35,"symbol":"__get__","kind":"function","lang":"python","code":"def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:\n if obj is None:\n return self\n\n rv = obj.config[self.__name__]\n\n if self.get_converter is not None:\n rv = self.get_converter(rv)\n\n return rv # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/config.py","line":46,"symbol":"__set__","kind":"function","lang":"python","code":"def __set__(self, obj: App, value: t.Any) -> None:\n obj.config[self.__name__] = value"} {"repo":"flask","file":"src/flask/config.py","line":50,"symbol":"Config","kind":"class","lang":"python","code":"class Config(dict): # type: ignore[type-arg]\n \"\"\"Works exactly like a dict but provides ways to fill it from files\n or special dictionaries. There are two common patterns to populate the\n config.\n\n Either you can fill the config from a config file::\n\n app.config.from_pyfile('yourconfig.cfg')\n\n Or alternatively you can define the configuration options in the\n module that calls :meth:`from_object` or provide an import path to\n a module that should be loaded. It is also possible to tell it to\n use the same module and with that provide the configuration values\n just before the call::\n\n DEBUG = True\n SECRET_KEY = 'development key'\n app.config.from_object(__name__)\n\n In both cases (loading from any Python file or loading from modules),\n only uppercase keys are added to the config. This makes it possible to use\n lowercase values in the config file for temporary values that are not added\n to the config or to define the config keys in the same file that implements\n the application.\n\n Probably the most interesting way to load configurations is from an\n environment variable pointing to a file::\n\n app.config"} {"repo":"flask","file":"src/flask/config.py","line":94,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n root_path: str | os.PathLike[str],\n defaults: dict[str, t.Any] | None = None,\n ) -> None:\n super().__init__(defaults or {})\n self.root_path = root_path"} {"repo":"flask","file":"src/flask/config.py","line":102,"symbol":"from_envvar","kind":"function","lang":"python","code":"def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n \"\"\"Loads a configuration from an environment variable pointing to\n a configuration file. This is basically just a shortcut with nicer\n error messages for this line of code::\n\n app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n :param variable_name: name of the environment variable\n :param silent: set to ``True`` if you want silent failure for missing\n files.\n :return: ``True`` if the file was loaded successfully.\n \"\"\"\n rv = os.environ.get(variable_name)\n if not rv:\n if silent:\n return False\n raise RuntimeError(\n f\"The environment variable {variable_name!r} is not set\"\n \" and as such configuration could not be loaded. Set\"\n \" this variable and make it point to a configuration\"\n \" file\"\n )\n return self.from_pyfile(rv, silent=silent)"} {"repo":"flask","file":"src/flask/config.py","line":126,"symbol":"from_prefixed_env","kind":"function","lang":"python","code":"def from_prefixed_env(\n self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n ) -> bool:\n \"\"\"Load any environment variables that start with ``FLASK_``,\n dropping the prefix from the env key for the config key. Values\n are passed through a loading function to attempt to convert them\n to more specific types than strings.\n\n Keys are loaded in :func:`sorted` order.\n\n The default loading function attempts to parse values as any\n valid JSON type, including dicts and lists.\n\n Specific items in nested dicts can be set by separating the\n keys with double underscores (``__``). If an intermediate key\n doesn't exist, it will be initialized to an empty dict.\n\n :param prefix: Load env vars that start with this prefix,\n separated with an underscore (``_``).\n :param loads: Pass each string value to this function and use\n the returned value as the config value. If any error is\n raised it is ignored and the value remains a string. The\n default is :func:`json.loads`.\n\n .. versionadded:: 2.1\n \"\"\"\n prefix = f\"{prefix}_\"\n\n "} {"repo":"flask","file":"src/flask/config.py","line":187,"symbol":"from_pyfile","kind":"function","lang":"python","code":"def from_pyfile(\n self, filename: str | os.PathLike[str], silent: bool = False\n ) -> bool:\n \"\"\"Updates the values in the config from a Python file. This function\n behaves as if the file was imported as module with the\n :meth:`from_object` function.\n\n :param filename: the filename of the config. This can either be an\n absolute filename or a filename relative to the\n root path.\n :param silent: set to ``True`` if you want silent failure for missing\n files.\n :return: ``True`` if the file was loaded successfully.\n\n .. versionadded:: 0.7\n `silent` parameter.\n \"\"\"\n filename = os.path.join(self.root_path, filename)\n d = types.ModuleType(\"config\")\n d.__file__ = filename\n try:\n with open(filename, mode=\"rb\") as config_file:\n exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n except OSError as e:\n if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n return False\n e.strerror = f\"Unable to load configuration file ({e.stre"} {"repo":"flask","file":"src/flask/config.py","line":218,"symbol":"from_object","kind":"function","lang":"python","code":"def from_object(self, obj: object | str) -> None:\n \"\"\"Updates the values from the given object. An object can be of one\n of the following two types:\n\n - a string: in this case the object with that name will be imported\n - an actual object reference: that object is used directly\n\n Objects are usually either modules or classes. :meth:`from_object`\n loads only the uppercase attributes of the module/class. A ``dict``\n object will not work with :meth:`from_object` because the keys of a\n ``dict`` are not attributes of the ``dict`` class.\n\n Example of module-based configuration::\n\n app.config.from_object('yourapplication.default_config')\n from yourapplication import default_config\n app.config.from_object(default_config)\n\n Nothing is done to the object before loading. If the object is a\n class and has ``@property`` attributes, it needs to be\n instantiated before being passed to this method.\n\n You should not use this function to load the actual configuration but\n rather configuration defaults. The actual config should be loaded\n with :meth:`from_pyf"} {"repo":"flask","file":"src/flask/config.py","line":256,"symbol":"from_file","kind":"function","lang":"python","code":"def from_file(\n self,\n filename: str | os.PathLike[str],\n load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],\n silent: bool = False,\n text: bool = True,\n ) -> bool:\n \"\"\"Update the values in the config from a file that is loaded\n using the ``load`` parameter. The loaded data is passed to the\n :meth:`from_mapping` method.\n\n .. code-block:: python\n\n import json\n app.config.from_file(\"config.json\", load=json.load)\n\n import tomllib\n app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n :param filename: The path to the data file. This can be an\n absolute path or relative to the config root path.\n :param load: A callable that takes a file handle and returns a\n mapping of loaded data from the file.\n :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n implements a ``read`` method.\n :param silent: Ignore the file if it doesn't exist.\n :param text: Open the file in text or binary mode.\n :return: ``True`` if the file was loaded successfully.\n\n .. versionchanged:: 2.3\n "} {"repo":"flask","file":"src/flask/config.py","line":304,"symbol":"from_mapping","kind":"function","lang":"python","code":"def from_mapping(\n self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any\n ) -> bool:\n \"\"\"Updates the config like :meth:`update` ignoring items with\n non-upper keys.\n\n :return: Always returns ``True``.\n\n .. versionadded:: 0.11\n \"\"\"\n mappings: dict[str, t.Any] = {}\n if mapping is not None:\n mappings.update(mapping)\n mappings.update(kwargs)\n for key, value in mappings.items():\n if key.isupper():\n self[key] = value\n return True"} {"repo":"flask","file":"src/flask/config.py","line":323,"symbol":"get_namespace","kind":"function","lang":"python","code":"def get_namespace(\n self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n ) -> dict[str, t.Any]:\n \"\"\"Returns a dictionary containing a subset of configuration options\n that match the specified namespace/prefix. Example usage::\n\n app.config['IMAGE_STORE_TYPE'] = 'fs'\n app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n The resulting dictionary `image_store_config` would look like::\n\n {\n 'type': 'fs',\n 'path': '/var/app/images',\n 'base_url': 'http://img.website.com'\n }\n\n This is often useful when configuration options map directly to\n keyword arguments in functions or class constructors.\n\n :param namespace: a configuration namespace\n :param lowercase: a flag indicating if the keys of the resulting\n dictionary should be lowercase\n :param trim_namespace: a flag indicating if the keys of the resulting\n dictionary shoul"} {"repo":"flask","file":"src/flask/config.py","line":366,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<{type(self).__name__} {dict.__repr__(self)}>\""} {"repo":"flask","file":"src/flask/ctx.py","line":30,"symbol":"_AppCtxGlobals","kind":"class","lang":"python","code":"class _AppCtxGlobals:\n \"\"\"A plain object. Used as a namespace for storing data during an\n application context.\n\n Creating an app context automatically creates this object, which is\n made available as the :data:`.g` proxy.\n\n .. describe:: 'key' in g\n\n Check whether an attribute is present.\n\n .. versionadded:: 0.10\n\n .. describe:: iter(g)\n\n Return an iterator over the attribute names.\n\n .. versionadded:: 0.10\n \"\"\"\n\n # Define attr methods to let mypy know this is a namespace object\n # that has arbitrary attributes.\n\n def __getattr__(self, name: str) -> t.Any:\n try:\n return self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None\n\n def __setattr__(self, name: str, value: t.Any) -> None:\n self.__dict__[name] = value\n\n def __delattr__(self, name: str) -> None:\n try:\n del self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None\n\n def get(self, name: str, default: t.Any | None = None) -> t.Any:\n \"\"\"Get an attribute by name, or a default value. Like\n :meth:`dict.get`.\n\n :param name: Name o"} {"repo":"flask","file":"src/flask/ctx.py","line":53,"symbol":"__getattr__","kind":"function","lang":"python","code":"def __getattr__(self, name: str) -> t.Any:\n try:\n return self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None"} {"repo":"flask","file":"src/flask/ctx.py","line":59,"symbol":"__setattr__","kind":"function","lang":"python","code":"def __setattr__(self, name: str, value: t.Any) -> None:\n self.__dict__[name] = value"} {"repo":"flask","file":"src/flask/ctx.py","line":62,"symbol":"__delattr__","kind":"function","lang":"python","code":"def __delattr__(self, name: str) -> None:\n try:\n del self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None"} {"repo":"flask","file":"src/flask/ctx.py","line":68,"symbol":"get","kind":"function","lang":"python","code":"def get(self, name: str, default: t.Any | None = None) -> t.Any:\n \"\"\"Get an attribute by name, or a default value. Like\n :meth:`dict.get`.\n\n :param name: Name of attribute to get.\n :param default: Value to return if the attribute is not present.\n\n .. versionadded:: 0.10\n \"\"\"\n return self.__dict__.get(name, default)"} {"repo":"flask","file":"src/flask/ctx.py","line":79,"symbol":"pop","kind":"function","lang":"python","code":"def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:\n \"\"\"Get and remove an attribute by name. Like :meth:`dict.pop`.\n\n :param name: Name of attribute to pop.\n :param default: Value to return if the attribute is not present,\n instead of raising a ``KeyError``.\n\n .. versionadded:: 0.11\n \"\"\"\n if default is _sentinel:\n return self.__dict__.pop(name)\n else:\n return self.__dict__.pop(name, default)"} {"repo":"flask","file":"src/flask/ctx.py","line":93,"symbol":"setdefault","kind":"function","lang":"python","code":"def setdefault(self, name: str, default: t.Any = None) -> t.Any:\n \"\"\"Get the value of an attribute if it is present, otherwise\n set and return a default value. Like :meth:`dict.setdefault`.\n\n :param name: Name of attribute to get.\n :param default: Value to set and return if the attribute is not\n present.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.__dict__.setdefault(name, default)"} {"repo":"flask","file":"src/flask/ctx.py","line":105,"symbol":"__contains__","kind":"function","lang":"python","code":"def __contains__(self, item: str) -> bool:\n return item in self.__dict__"} {"repo":"flask","file":"src/flask/ctx.py","line":108,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> t.Iterator[str]:\n return iter(self.__dict__)"} {"repo":"flask","file":"src/flask/ctx.py","line":111,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n ctx = _cv_app.get(None)\n if ctx is not None:\n return f\"\"\n return object.__repr__(self)"} {"repo":"flask","file":"src/flask/ctx.py","line":118,"symbol":"after_this_request","kind":"function","lang":"python","code":"def after_this_request(\n f: ft.AfterRequestCallable[t.Any],\n) -> ft.AfterRequestCallable[t.Any]:\n \"\"\"Decorate a function to run after the current request. The behavior is the\n same as :meth:`.Flask.after_request`, except it only applies to the current\n request, rather than every request. Therefore, it must be used within a\n request context, rather than during setup.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n @after_this_request\n def add_header(response):\n response.headers[\"X-Foo\"] = \"Parachute\"\n return response\n\n return \"Hello, World!\"\n\n .. versionadded:: 0.9\n \"\"\"\n ctx = _cv_app.get(None)\n\n if ctx is None or not ctx.has_request:\n raise RuntimeError(\n \"'after_this_request' can only be used when a request\"\n \" context is active, such as in a view function.\"\n )\n\n ctx._after_request_functions.append(f)\n return f"} {"repo":"flask","file":"src/flask/ctx.py","line":154,"symbol":"copy_current_request_context","kind":"function","lang":"python","code":"def copy_current_request_context(f: F) -> F:\n \"\"\"Decorate a function to run inside the current request context. This can\n be used when starting a background task, otherwise it will not see the app\n and request objects that were active in the parent.\n\n .. warning::\n\n Due to the following caveats, it is often safer (and simpler) to pass\n the data you need when starting the task, rather than using this and\n relying on the context objects.\n\n In order to avoid execution switching partially though reading data, either\n read the request body (access ``form``, ``json``, ``data``, etc) before\n starting the task, or use a lock. This can be an issue when using threading,\n but shouldn't be an issue when using greenlet/gevent or asyncio.\n\n If the task will access ``session``, be sure to do so in the parent as well\n so that the ``Vary: cookie`` header will be set. Modifying ``session`` in\n the task should be avoided, as it may execute after the response cookie has\n already been written.\n\n .. code-block:: python\n\n import gevent\n from flask import copy_current_request_context\n\n @app.route('/')\n def index():\n "} {"repo":"flask","file":"src/flask/ctx.py","line":201,"symbol":"wrapper","kind":"function","lang":"python","code":"def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:\n # Copy the context before pushing, so each worker acts independently.\n with original.copy() as ctx:\n return ctx.app.ensure_sync(f)(*args, **kwargs)"} {"repo":"flask","file":"src/flask/ctx.py","line":209,"symbol":"has_request_context","kind":"function","lang":"python","code":"def has_request_context() -> bool:\n \"\"\"Test if an app context is active and if it has request information.\n\n .. code-block:: python\n\n from flask import has_request_context, request\n\n if has_request_context():\n remote_addr = request.remote_addr\n\n If a request context is active, the :data:`.request` and :data:`.session`\n context proxies will available and ``True``, otherwise ``False``. You can\n use that to test the data you use, rather than using this function.\n\n .. code-block:: python\n\n from flask import request\n\n if request:\n remote_addr = request.remote_addr\n\n .. versionadded:: 0.7\n \"\"\"\n return (ctx := _cv_app.get(None)) is not None and ctx.has_request"} {"repo":"flask","file":"src/flask/ctx.py","line":235,"symbol":"has_app_context","kind":"function","lang":"python","code":"def has_app_context() -> bool:\n \"\"\"Test if an app context is active. Unlike :func:`has_request_context`\n this can be true outside a request, such as in a CLI command.\n\n .. code-block:: python\n\n from flask import has_app_context, g\n\n if has_app_context():\n g.cached_data = ...\n\n If an app context is active, the :data:`.g` and :data:`.current_app` context\n proxies will available and ``True``, otherwise ``False``. You can use that\n to test the data you use, rather than using this function.\n\n from flask import g\n\n if g:\n g.cached_data = ...\n\n .. versionadded:: 0.9\n \"\"\"\n return _cv_app.get(None) is not None"} {"repo":"flask","file":"src/flask/ctx.py","line":260,"symbol":"AppContext","kind":"class","lang":"python","code":"class AppContext:\n \"\"\"An app context contains information about an app, and about the request\n when handling a request. A context is pushed at the beginning of each\n request and CLI command, and popped at the end. The context is referred to\n as a \"request context\" if it has request information, and an \"app context\"\n if not.\n\n Do not use this class directly. Use :meth:`.Flask.app_context` to create an\n app context if needed during setup, and :meth:`.Flask.test_request_context`\n to create a request context if needed during tests.\n\n When the context is popped, it will evaluate all the teardown functions\n registered with :meth:`~flask.Flask.teardown_request` (if handling a\n request) then :meth:`.Flask.teardown_appcontext`.\n\n When using the interactive debugger, the context will be restored so\n ``request`` is still accessible. Similarly, the test client can preserve the\n context after the request ends. However, teardown functions may already have\n closed some resources such as database connections, and will run again when\n the restored context is popped.\n\n :param app: The application this context represents.\n :param request: The requ"} {"repo":"flask","file":"src/flask/ctx.py","line":300,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n app: Flask,\n *,\n request: Request | None = None,\n session: SessionMixin | None = None,\n ) -> None:\n self.app = app\n \"\"\"The application represented by this context. Accessed through\n :data:`.current_app`.\n \"\"\"\n\n self.g: _AppCtxGlobals = app.app_ctx_globals_class()\n \"\"\"The global data for this context. Accessed through :data:`.g`.\"\"\"\n\n self.url_adapter: MapAdapter | None = None\n \"\"\"The URL adapter bound to the request, or the app if not in a request.\n May be ``None`` if binding failed.\n \"\"\"\n\n self._request: Request | None = request\n self._session: SessionMixin | None = session\n self._flashes: list[tuple[str, str]] | None = None\n self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []\n\n try:\n self.url_adapter = app.create_url_adapter(self._request)\n except HTTPException as e:\n if self._request is not None:\n self._request.routing_exception = e\n\n self._cv_token: contextvars.Token[AppContext] | None = None\n \"\"\"The previous state to restore when popping"} {"repo":"flask","file":"src/flask/ctx.py","line":340,"symbol":"from_environ","kind":"function","lang":"python","code":"def from_environ(cls, app: Flask, environ: WSGIEnvironment, /) -> te.Self:\n \"\"\"Create an app context with request data from the given WSGI environ.\n\n :param app: The application this context represents.\n :param environ: The request data this context represents.\n \"\"\"\n request = app.request_class(environ)\n request.json_module = app.json\n return cls(app, request=request)"} {"repo":"flask","file":"src/flask/ctx.py","line":351,"symbol":"has_request","kind":"function","lang":"python","code":"def has_request(self) -> bool:\n \"\"\"True if this context was created with request data.\"\"\"\n return self._request is not None"} {"repo":"flask","file":"src/flask/ctx.py","line":355,"symbol":"copy","kind":"function","lang":"python","code":"def copy(self) -> te.Self:\n \"\"\"Create a new context with the same data objects as this context. See\n :func:`.copy_current_request_context`.\n\n .. versionchanged:: 1.1\n The current session data is used instead of reloading the original data.\n\n .. versionadded:: 0.10\n \"\"\"\n return self.__class__(\n self.app,\n request=self._request,\n session=self._session,\n )"} {"repo":"flask","file":"src/flask/ctx.py","line":371,"symbol":"request","kind":"function","lang":"python","code":"def request(self) -> Request:\n \"\"\"The request object associated with this context. Accessed through\n :data:`.request`. Only available in request contexts, otherwise raises\n :exc:`RuntimeError`.\n \"\"\"\n if self._request is None:\n raise RuntimeError(\"There is no request in this context.\")\n\n return self._request"} {"repo":"flask","file":"src/flask/ctx.py","line":381,"symbol":"_get_session","kind":"function","lang":"python","code":"def _get_session(self) -> SessionMixin:\n \"\"\"Open the session if it is not already open for this request context.\"\"\"\n if self._request is None:\n raise RuntimeError(\"There is no request in this context.\")\n\n if self._session is None:\n si = self.app.session_interface\n self._session = si.open_session(self.app, self.request)\n\n if self._session is None:\n self._session = si.make_null_session(self.app)\n\n return self._session"} {"repo":"flask","file":"src/flask/ctx.py","line":396,"symbol":"session","kind":"function","lang":"python","code":"def session(self) -> SessionMixin:\n \"\"\"The session object associated with this context. Accessed through\n :data:`.session`. Only available in request contexts, otherwise raises\n :exc:`RuntimeError`. Accessing this sets :attr:`.SessionMixin.accessed`.\n \"\"\"\n session = self._get_session()\n session.accessed = True\n return session"} {"repo":"flask","file":"src/flask/ctx.py","line":405,"symbol":"match_request","kind":"function","lang":"python","code":"def match_request(self) -> None:\n \"\"\"Apply routing to the current request, storing either the matched\n endpoint and args, or a routing exception.\n \"\"\"\n try:\n result = self.url_adapter.match(return_rule=True) # type: ignore[union-attr]\n except HTTPException as e:\n self._request.routing_exception = e # type: ignore[union-attr]\n else:\n self._request.url_rule, self._request.view_args = result # type: ignore[union-attr]"} {"repo":"flask","file":"src/flask/ctx.py","line":416,"symbol":"push","kind":"function","lang":"python","code":"def push(self) -> None:\n \"\"\"Push this context so that it is the active context. If this is a\n request context, calls :meth:`match_request` to perform routing with\n the context active.\n\n Typically, this is not used directly. Instead, use a ``with`` block\n to manage the context.\n\n In some situations, such as streaming or testing, the context may be\n pushed multiple times. It will only trigger matching and signals if it\n is not currently pushed.\n \"\"\"\n self._push_count += 1\n\n if self._cv_token is not None:\n return\n\n self._cv_token = _cv_app.set(self)\n appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)\n\n if self._request is not None:\n # Open the session at the moment that the request context is available.\n # This allows a custom open_session method to use the request context.\n self._get_session()\n\n # Match the request URL after loading the session, so that the\n # session is available in custom URL converters.\n if self.url_adapter is not None:\n self.match_request()"} {"repo":"flask","file":"src/flask/ctx.py","line":446,"symbol":"pop","kind":"function","lang":"python","code":"def pop(self, exc: BaseException | None = None) -> None:\n \"\"\"Pop this context so that it is no longer the active context. Then\n call teardown functions and signals.\n\n Typically, this is not used directly. Instead, use a ``with`` block\n to manage the context.\n\n This context must currently be the active context, otherwise a\n :exc:`RuntimeError` is raised. In some situations, such as streaming or\n testing, the context may have been pushed multiple times. It will only\n trigger cleanup once it has been popped as many times as it was pushed.\n Until then, it will remain the active context.\n\n :param exc: An unhandled exception that was raised while the context was\n active. Passed to teardown functions.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n \"\"\"\n if self._cv_token is None:\n raise RuntimeError(f\"Cannot pop this context ({self!r}), it is not pushed.\")\n\n ctx = _cv_app.get(None)\n\n if ctx is None or self._cv_token is None:\n raise RuntimeError(\n f\"Cannot pop this context ({self!r}), there is no active context.\"\n "} {"repo":"flask","file":"src/flask/ctx.py","line":506,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self) -> te.Self:\n self.push()\n return self"} {"repo":"flask","file":"src/flask/ctx.py","line":510,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc_value: BaseException | None,\n tb: TracebackType | None,\n ) -> None:\n self.pop(exc_value)"} {"repo":"flask","file":"src/flask/ctx.py","line":518,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n if self._request is not None:\n return (\n f\"<{type(self).__name__} {id(self)} of {self.app.name},\"\n f\" {self.request.method} {self.request.url!r}>\"\n )\n\n return f\"<{type(self).__name__} {id(self)} of {self.app.name}>\""} {"repo":"flask","file":"src/flask/ctx.py","line":528,"symbol":"__getattr__","kind":"function","lang":"python","code":"def __getattr__(name: str) -> t.Any:\n import warnings\n\n if name == \"RequestContext\":\n warnings.warn(\n \"'RequestContext' has merged with 'AppContext', and will be removed\"\n \" in Flask 4.0. Use 'AppContext' instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return AppContext\n\n raise AttributeError(name)"} {"repo":"flask","file":"src/flask/debughelpers.py","line":17,"symbol":"UnexpectedUnicodeError","kind":"class","lang":"python","code":"class UnexpectedUnicodeError(AssertionError, UnicodeError):\n \"\"\"Raised in places where we want some better error reporting for\n unexpected unicode or binary data.\n \"\"\""} {"repo":"flask","file":"src/flask/debughelpers.py","line":23,"symbol":"DebugFilesKeyError","kind":"class","lang":"python","code":"class DebugFilesKeyError(KeyError, AssertionError):\n \"\"\"Raised from request.files during debugging. The idea is that it can\n provide a better error message than just a generic KeyError/BadRequest.\n \"\"\"\n\n def __init__(self, request: Request, key: str) -> None:\n form_matches = request.form.getlist(key)\n buf = [\n f\"You tried to access the file {key!r} in the request.files\"\n \" dictionary but it does not exist. The mimetype for the\"\n f\" request is {request.mimetype!r} instead of\"\n \" 'multipart/form-data' which means that no file contents\"\n \" were transmitted. To fix this error you should provide\"\n ' enctype=\"multipart/form-data\" in your form.'\n ]\n if form_matches:\n names = \", \".join(repr(x) for x in form_matches)\n buf.append(\n \"\\n\\nThe browser instead transmitted some file names. \"\n f\"This was submitted: {names}\"\n )\n self.msg = \"\".join(buf)\n\n def __str__(self) -> str:\n return self.msg"} {"repo":"flask","file":"src/flask/debughelpers.py","line":28,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, request: Request, key: str) -> None:\n form_matches = request.form.getlist(key)\n buf = [\n f\"You tried to access the file {key!r} in the request.files\"\n \" dictionary but it does not exist. The mimetype for the\"\n f\" request is {request.mimetype!r} instead of\"\n \" 'multipart/form-data' which means that no file contents\"\n \" were transmitted. To fix this error you should provide\"\n ' enctype=\"multipart/form-data\" in your form.'\n ]\n if form_matches:\n names = \", \".join(repr(x) for x in form_matches)\n buf.append(\n \"\\n\\nThe browser instead transmitted some file names. \"\n f\"This was submitted: {names}\"\n )\n self.msg = \"\".join(buf)"} {"repo":"flask","file":"src/flask/debughelpers.py","line":46,"symbol":"__str__","kind":"function","lang":"python","code":"def __str__(self) -> str:\n return self.msg"} {"repo":"flask","file":"src/flask/debughelpers.py","line":50,"symbol":"FormDataRoutingRedirect","kind":"class","lang":"python","code":"class FormDataRoutingRedirect(AssertionError):\n \"\"\"This exception is raised in debug mode if a routing redirect\n would cause the browser to drop the method or body. This happens\n when method is not GET, HEAD or OPTIONS and the status code is not\n 307 or 308.\n \"\"\"\n\n def __init__(self, request: Request) -> None:\n exc = request.routing_exception\n assert isinstance(exc, RequestRedirect)\n buf = [\n f\"A request was sent to '{request.url}', but routing issued\"\n f\" a redirect to the canonical URL '{exc.new_url}'.\"\n ]\n\n if f\"{request.base_url}/\" == exc.new_url.partition(\"?\")[0]:\n buf.append(\n \" The URL was defined with a trailing slash. Flask\"\n \" will redirect to the URL with a trailing slash if it\"\n \" was accessed without one.\"\n )\n\n buf.append(\n \" Send requests to the canonical URL, or use 307 or 308 for\"\n \" routing redirects. Otherwise, browsers will drop form\"\n \" data.\\n\\n\"\n \"This exception is only raised in debug mode.\"\n )\n super().__init__(\"\".join(buf))"} {"repo":"flask","file":"src/flask/debughelpers.py","line":57,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, request: Request) -> None:\n exc = request.routing_exception\n assert isinstance(exc, RequestRedirect)\n buf = [\n f\"A request was sent to '{request.url}', but routing issued\"\n f\" a redirect to the canonical URL '{exc.new_url}'.\"\n ]\n\n if f\"{request.base_url}/\" == exc.new_url.partition(\"?\")[0]:\n buf.append(\n \" The URL was defined with a trailing slash. Flask\"\n \" will redirect to the URL with a trailing slash if it\"\n \" was accessed without one.\"\n )\n\n buf.append(\n \" Send requests to the canonical URL, or use 307 or 308 for\"\n \" routing redirects. Otherwise, browsers will drop form\"\n \" data.\\n\\n\"\n \"This exception is only raised in debug mode.\"\n )\n super().__init__(\"\".join(buf))"} {"repo":"flask","file":"src/flask/debughelpers.py","line":81,"symbol":"attach_enctype_error_multidict","kind":"function","lang":"python","code":"def attach_enctype_error_multidict(request: Request) -> None:\n \"\"\"Patch ``request.files.__getitem__`` to raise a descriptive error\n about ``enctype=multipart/form-data``.\n\n :param request: The request to patch.\n :meta private:\n \"\"\"\n oldcls = request.files.__class__\n\n class newcls(oldcls): # type: ignore[valid-type, misc]\n def __getitem__(self, key: str) -> t.Any:\n try:\n return super().__getitem__(key)\n except KeyError as e:\n if key not in request.form:\n raise\n\n raise DebugFilesKeyError(request, key).with_traceback(\n e.__traceback__\n ) from None\n\n newcls.__name__ = oldcls.__name__\n newcls.__module__ = oldcls.__module__\n request.files.__class__ = newcls"} {"repo":"flask","file":"src/flask/debughelpers.py","line":90,"symbol":"newcls","kind":"class","lang":"python","code":"class newcls(oldcls): # type: ignore[valid-type, misc]\n def __getitem__(self, key: str) -> t.Any:\n try:\n return super().__getitem__(key)\n except KeyError as e:\n if key not in request.form:\n raise\n\n raise DebugFilesKeyError(request, key).with_traceback(\n e.__traceback__\n ) from None"} {"repo":"flask","file":"src/flask/debughelpers.py","line":91,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, key: str) -> t.Any:\n try:\n return super().__getitem__(key)\n except KeyError as e:\n if key not in request.form:\n raise\n\n raise DebugFilesKeyError(request, key).with_traceback(\n e.__traceback__\n ) from None"} {"repo":"flask","file":"src/flask/debughelpers.py","line":107,"symbol":"_dump_loader_info","kind":"function","lang":"python","code":"def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:\n yield f\"class: {type(loader).__module__}.{type(loader).__name__}\"\n for key, value in sorted(loader.__dict__.items()):\n if key.startswith(\"_\"):\n continue\n if isinstance(value, (tuple, list)):\n if not all(isinstance(x, str) for x in value):\n continue\n yield f\"{key}:\"\n for item in value:\n yield f\" - {item}\"\n continue\n elif not isinstance(value, (str, int, float, bool)):\n continue\n yield f\"{key}: {value!r}\""} {"repo":"flask","file":"src/flask/debughelpers.py","line":124,"symbol":"explain_template_loading_attempts","kind":"function","lang":"python","code":"def explain_template_loading_attempts(\n app: App,\n template: str,\n attempts: list[\n tuple[\n BaseLoader,\n Scaffold,\n tuple[str, str | None, t.Callable[[], bool] | None] | None,\n ]\n ],\n) -> None:\n \"\"\"This should help developers understand what failed\"\"\"\n info = [f\"Locating template {template!r}:\"]\n total_found = 0\n blueprint = None\n\n if (ctx := _cv_app.get(None)) is not None and ctx.has_request:\n blueprint = ctx.request.blueprint\n\n for idx, (loader, srcobj, triple) in enumerate(attempts):\n if isinstance(srcobj, App):\n src_info = f\"application {srcobj.import_name!r}\"\n elif isinstance(srcobj, Blueprint):\n src_info = f\"blueprint {srcobj.name!r} ({srcobj.import_name})\"\n else:\n src_info = repr(srcobj)\n\n info.append(f\"{idx + 1:5}: trying loader of {src_info}\")\n\n for line in _dump_loader_info(loader):\n info.append(f\" {line}\")\n\n if triple is None:\n detail = \"no match\"\n else:\n detail = f\"found ({triple[1] or ''!r})\"\n total_found += 1\n info.append(f\" -> {detail"} {"repo":"flask","file":"src/flask/globals.py","line":17,"symbol":"ProxyMixin","kind":"class","lang":"python","code":"class ProxyMixin(t.Protocol[T]):\n def _get_current_object(self) -> T: ..."} {"repo":"flask","file":"src/flask/globals.py","line":18,"symbol":"_get_current_object","kind":"function","lang":"python","code":"def _get_current_object(self) -> T: ..."} {"repo":"flask","file":"src/flask/globals.py","line":22,"symbol":"FlaskProxy","kind":"class","lang":"python","doc":"These subclasses inform type checkers that the proxy objects look like the proxied type along with the _get_current_object method.","code":"class FlaskProxy(ProxyMixin[Flask], Flask): ..."} {"repo":"flask","file":"src/flask/globals.py","line":24,"symbol":"AppContextProxy","kind":"class","lang":"python","code":"class AppContextProxy(ProxyMixin[AppContext], AppContext): ..."} {"repo":"flask","file":"src/flask/globals.py","line":26,"symbol":"_AppCtxGlobalsProxy","kind":"class","lang":"python","code":"class _AppCtxGlobalsProxy(ProxyMixin[_AppCtxGlobals], _AppCtxGlobals): ..."} {"repo":"flask","file":"src/flask/globals.py","line":28,"symbol":"RequestProxy","kind":"class","lang":"python","code":"class RequestProxy(ProxyMixin[Request], Request): ..."} {"repo":"flask","file":"src/flask/globals.py","line":30,"symbol":"SessionMixinProxy","kind":"class","lang":"python","code":"class SessionMixinProxy(ProxyMixin[SessionMixin], SessionMixin): ..."} {"repo":"flask","file":"src/flask/globals.py","line":65,"symbol":"__getattr__","kind":"function","lang":"python","code":"def __getattr__(name: str) -> t.Any:\n import warnings\n\n if name == \"request_ctx\":\n warnings.warn(\n \"'request_ctx' has merged with 'app_ctx', and will be removed\"\n \" in Flask 4.0. Use 'app_ctx' instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return app_ctx\n\n raise AttributeError(name)"} {"repo":"flask","file":"src/flask/helpers.py","line":28,"symbol":"get_debug_flag","kind":"function","lang":"python","code":"def get_debug_flag() -> bool:\n \"\"\"Get whether debug mode should be enabled for the app, indicated by the\n :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.\n \"\"\"\n val = os.environ.get(\"FLASK_DEBUG\")\n return bool(val and val.lower() not in {\"0\", \"false\", \"no\"})"} {"repo":"flask","file":"src/flask/helpers.py","line":36,"symbol":"get_load_dotenv","kind":"function","lang":"python","code":"def get_load_dotenv(default: bool = True) -> bool:\n \"\"\"Get whether the user has disabled loading default dotenv files by\n setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load\n the files.\n\n :param default: What to return if the env var isn't set.\n \"\"\"\n val = os.environ.get(\"FLASK_SKIP_DOTENV\")\n\n if not val:\n return default\n\n return val.lower() in (\"0\", \"false\", \"no\")"} {"repo":"flask","file":"src/flask/helpers.py","line":52,"symbol":"stream_with_context","kind":"function","lang":"python","code":"def stream_with_context(\n generator_or_function: t.Iterator[t.AnyStr],\n) -> t.Iterator[t.AnyStr]: ..."} {"repo":"flask","file":"src/flask/helpers.py","line":58,"symbol":"stream_with_context","kind":"function","lang":"python","code":"def stream_with_context(\n generator_or_function: t.Callable[..., t.Iterator[t.AnyStr]],\n) -> t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]: ..."} {"repo":"flask","file":"src/flask/helpers.py","line":63,"symbol":"stream_with_context","kind":"function","lang":"python","code":"def stream_with_context(\n generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],\n) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]:\n \"\"\"Wrap a response generator function so that it runs inside the current\n request context. This keeps :data:`.request`, :data:`.session`, and :data:`.g`\n available, even though at the point the generator runs the request context\n will typically have ended.\n\n .. warning::\n\n Due to the following caveat, it is often safer to pass the data you\n need as arguments to the generator, rather than relying on the context\n objects.\n\n More headers cannot be sent after the body has begun. Therefore, you must\n make sure all headers are set before starting the response. In particular,\n if the generator will access ``session``, be sure to do so in the view as\n well so that the ``Vary: cookie`` header will be set. Do not modify the\n session in the generator, as the ``Set-Cookie`` header will already be sent.\n\n Use it as a decorator on a generator function:\n\n .. code-block:: python\n\n from flask import stream_with_context, request, Response\n"} {"repo":"flask","file":"src/flask/helpers.py","line":120,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:\n gen = generator_or_function(*args, **kwargs) # type: ignore[operator]\n return stream_with_context(gen)"} {"repo":"flask","file":"src/flask/helpers.py","line":126,"symbol":"generator","kind":"function","lang":"python","code":"def generator() -> t.Iterator[t.AnyStr]:\n if (ctx := _cv_app.get(None)) is None:\n raise RuntimeError(\n \"'stream_with_context' can only be used when a request\"\n \" context is active, such as in a view function.\"\n )\n\n with ctx:\n yield None # type: ignore[misc]\n\n try:\n yield from gen\n finally:\n # Clean up in case the user wrapped a WSGI iterator.\n if hasattr(gen, \"close\"):\n gen.close()"} {"repo":"flask","file":"src/flask/helpers.py","line":151,"symbol":"make_response","kind":"function","lang":"python","code":"def make_response(*args: t.Any) -> Response:\n \"\"\"Sometimes it is necessary to set additional headers in a view. Because\n views do not have to return response objects but can return a value that\n is converted into a response object by Flask itself, it becomes tricky to\n add headers to it. This function can be called instead of using a return\n and you will get a response object which you can use to attach headers.\n\n If view looked like this and you want to add a new header::\n\n def index():\n return render_template('index.html', foo=42)\n\n You can now do something like this::\n\n def index():\n response = make_response(render_template('index.html', foo=42))\n response.headers['X-Parachutes'] = 'parachutes are cool'\n return response\n\n This function accepts the very same arguments you can return from a\n view function. This for example creates a response with a 404 error\n code::\n\n response = make_response(render_template('not_found.html'), 404)\n\n The other use case of this function is to force the return value of a\n view function into a response which is helpful with view\n decorators::\n\n "} {"repo":"flask","file":"src/flask/helpers.py","line":200,"symbol":"url_for","kind":"function","lang":"python","code":"def url_for(\n endpoint: str,\n *,\n _anchor: str | None = None,\n _method: str | None = None,\n _scheme: str | None = None,\n _external: bool | None = None,\n **values: t.Any,\n) -> str:\n \"\"\"Generate a URL to the given endpoint with the given values.\n\n This requires an active request or application context, and calls\n :meth:`current_app.url_for() `. See that method\n for full documentation.\n\n :param endpoint: The endpoint name associated with the URL to\n generate. If this starts with a ``.``, the current blueprint\n name (if any) will be used.\n :param _anchor: If given, append this as ``#anchor`` to the URL.\n :param _method: If given, generate the URL associated with this\n method for the endpoint.\n :param _scheme: If given, the URL will have this scheme if it is\n external.\n :param _external: If given, prefer the URL to be internal (False) or\n require it to be external (True). External URLs include the\n scheme and domain. When not in an active request, URLs are\n external by default.\n :param values: Values to use for the variable parts of the URL rule.\n Unknown keys "} {"repo":"flask","file":"src/flask/helpers.py","line":254,"symbol":"redirect","kind":"function","lang":"python","code":"def redirect(\n location: str, code: int = 303, Response: type[BaseResponse] | None = None\n) -> BaseResponse:\n \"\"\"Create a redirect response object.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`~flask.Flask.redirect` method, otherwise it will use\n :func:`werkzeug.utils.redirect`.\n\n :param location: The URL to redirect to.\n :param code: The status code for the redirect.\n :param Response: The response class to use. Not used when\n ``current_app`` is active, which uses ``app.response_class``.\n\n .. versionchanged:: 3.2\n ``code`` defaults to ``303`` instead of ``302``.\n\n .. versionadded:: 2.2\n Calls ``current_app.redirect`` if available instead of always\n using Werkzeug's default ``redirect``.\n \"\"\"\n if (ctx := _cv_app.get(None)) is not None:\n return ctx.app.redirect(location, code=code)\n\n return _wz_redirect(location, code=code, Response=Response)"} {"repo":"flask","file":"src/flask/helpers.py","line":281,"symbol":"abort","kind":"function","lang":"python","code":"def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n \"\"\"Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given\n status code.\n\n If :data:`~flask.current_app` is available, it will call its\n :attr:`~flask.Flask.aborter` object, otherwise it will use\n :func:`werkzeug.exceptions.abort`.\n\n :param code: The status code for the exception, which must be\n registered in ``app.aborter``.\n :param args: Passed to the exception.\n :param kwargs: Passed to the exception.\n\n .. versionadded:: 2.2\n Calls ``current_app.aborter`` if available instead of always\n using Werkzeug's default ``abort``.\n \"\"\"\n if (ctx := _cv_app.get(None)) is not None:\n ctx.app.aborter(code, *args, **kwargs)\n\n _wz_abort(code, *args, **kwargs)"} {"repo":"flask","file":"src/flask/helpers.py","line":304,"symbol":"get_template_attribute","kind":"function","lang":"python","code":"def get_template_attribute(template_name: str, attribute: str) -> t.Any:\n \"\"\"Loads a macro (or variable) a template exports. This can be used to\n invoke a macro from within Python code. If you for example have a\n template named :file:`_cider.html` with the following contents:\n\n .. sourcecode:: html+jinja\n\n {% macro hello(name) %}Hello {{ name }}!{% endmacro %}\n\n You can access this from Python code like this::\n\n hello = get_template_attribute('_cider.html', 'hello')\n return hello('World')\n\n .. versionadded:: 0.2\n\n :param template_name: the name of the template\n :param attribute: the name of the variable of macro to access\n \"\"\"\n return getattr(current_app.jinja_env.get_template(template_name).module, attribute)"} {"repo":"flask","file":"src/flask/helpers.py","line":326,"symbol":"flash","kind":"function","lang":"python","code":"def flash(message: str, category: str = \"message\") -> None:\n \"\"\"Flashes a message to the next request. In order to remove the\n flashed message from the session and to display it to the user,\n the template has to call :func:`get_flashed_messages`.\n\n .. versionchanged:: 0.3\n `category` parameter added.\n\n :param message: the message to be flashed.\n :param category: the category for the message. The following values\n are recommended: ``'message'`` for any kind of message,\n ``'error'`` for errors, ``'info'`` for information\n messages and ``'warning'`` for warnings. However any\n kind of string can be used as category.\n \"\"\"\n # Original implementation:\n #\n # session.setdefault('_flashes', []).append((category, message))\n #\n # This assumed that changes made to mutable structures in the session are\n # always in sync with the session object, which is not true for session\n # implementations that use external storage for keeping their keys/values.\n flashes = session.get(\"_flashes\", [])\n flashes.append((category, message))\n session[\"_flashes\"] = flashes\n"} {"repo":"flask","file":"src/flask/helpers.py","line":360,"symbol":"get_flashed_messages","kind":"function","lang":"python","code":"def get_flashed_messages(\n with_categories: bool = False, category_filter: t.Iterable[str] = ()\n) -> list[str] | list[tuple[str, str]]:\n \"\"\"Pulls all flashed messages from the session and returns them.\n Further calls in the same request to the function will return\n the same messages. By default just the messages are returned,\n but when `with_categories` is set to ``True``, the return value will\n be a list of tuples in the form ``(category, message)`` instead.\n\n Filter the flashed messages to one or more categories by providing those\n categories in `category_filter`. This allows rendering categories in\n separate html blocks. The `with_categories` and `category_filter`\n arguments are distinct:\n\n * `with_categories` controls whether categories are returned with message\n text (``True`` gives a tuple, where ``False`` gives just the message text).\n * `category_filter` filters the messages down to only those matching the\n provided categories.\n\n See :doc:`/patterns/flashing` for examples.\n\n .. versionchanged:: 0.3\n `with_categories` parameter added.\n\n .. versionchanged:: 0.9\n `category_filter` parameter added.\n\n :par"} {"repo":"flask","file":"src/flask/helpers.py","line":402,"symbol":"_prepare_send_file_kwargs","kind":"function","lang":"python","code":"def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:\n ctx = app_ctx._get_current_object()\n\n if kwargs.get(\"max_age\") is None:\n kwargs[\"max_age\"] = ctx.app.get_send_file_max_age\n\n kwargs.update(\n environ=ctx.request.environ,\n use_x_sendfile=ctx.app.config[\"USE_X_SENDFILE\"],\n response_class=ctx.app.response_class,\n _root_path=ctx.app.root_path,\n )\n return kwargs"} {"repo":"flask","file":"src/flask/helpers.py","line":417,"symbol":"send_file","kind":"function","lang":"python","code":"def send_file(\n path_or_file: os.PathLike[t.AnyStr] | str | t.IO[bytes],\n mimetype: str | None = None,\n as_attachment: bool = False,\n download_name: str | None = None,\n conditional: bool = True,\n etag: bool | str = True,\n last_modified: datetime | int | float | None = None,\n max_age: None | (int | t.Callable[[str | None], int | None]) = None,\n) -> Response:\n \"\"\"Send the contents of a file to the client.\n\n The first argument can be a file path or a file-like object. Paths\n are preferred in most cases because Werkzeug can manage the file and\n get extra information from the path. Passing a file-like object\n requires that the file is opened in binary mode, and is mostly\n useful when building a file in memory with :class:`io.BytesIO`.\n\n Never pass file paths provided by a user. The path is assumed to be\n trusted, so a user could craft a path to access a file you didn't\n intend. Use :func:`send_from_directory` to safely serve\n user-requested paths from within a directory.\n\n If the WSGI server sets a ``file_wrapper`` in ``environ``, it is\n used, otherwise Werkzeug's built-in wrapper is used. Alternatively,\n if the HTTP server "} {"repo":"flask","file":"src/flask/helpers.py","line":543,"symbol":"send_from_directory","kind":"function","lang":"python","code":"def send_from_directory(\n directory: os.PathLike[str] | str,\n path: os.PathLike[str] | str,\n **kwargs: t.Any,\n) -> Response:\n \"\"\"Send a file from within a directory using :func:`send_file`.\n\n .. code-block:: python\n\n @app.route(\"/uploads/\")\n def download_file(name):\n return send_from_directory(\n app.config['UPLOAD_FOLDER'], name, as_attachment=True\n )\n\n This is a secure way to serve files from a folder, such as static\n files or uploads. Uses :func:`~werkzeug.security.safe_join` to\n ensure the path coming from the client is not maliciously crafted to\n point outside the specified directory.\n\n If the final path does not point to an existing regular file,\n raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.\n\n :param directory: The directory that ``path`` must be located under,\n relative to the current application's root path. This *must not*\n be a value provided by the client, otherwise it becomes insecure.\n :param path: The path to the file to send, relative to\n ``directory``.\n :param kwargs: Arguments to pass to :func:`send_file`.\n\n .. versionchanged:: "} {"repo":"flask","file":"src/flask/helpers.py","line":587,"symbol":"get_root_path","kind":"function","lang":"python","code":"def get_root_path(import_name: str) -> str:\n \"\"\"Find the root path of a package, or the path that contains a\n module. If it cannot be found, returns the current working\n directory.\n\n Not to be confused with the value returned by :func:`find_package`.\n\n :meta private:\n \"\"\"\n # Module already imported and has a file attribute. Use that first.\n mod = sys.modules.get(import_name)\n\n if mod is not None and hasattr(mod, \"__file__\") and mod.__file__ is not None:\n return os.path.dirname(os.path.abspath(mod.__file__))\n\n # Next attempt: check the loader.\n try:\n spec = importlib.util.find_spec(import_name)\n\n if spec is None:\n raise ValueError\n except (ImportError, ValueError):\n loader = None\n else:\n loader = spec.loader\n\n # Loader does not exist or we're referring to an unloaded main\n # module or a main module without path (interactive sessions), go\n # with the current working directory.\n if loader is None:\n return os.getcwd()\n\n if hasattr(loader, \"get_filename\"):\n filepath = loader.get_filename(import_name) # pyright: ignore\n else:\n # Fall back to imports.\n __impo"} {"repo":"flask","file":"src/flask/helpers.py","line":645,"symbol":"_split_blueprint_path","kind":"function","lang":"python","code":"def _split_blueprint_path(name: str) -> list[str]:\n out: list[str] = [name]\n\n if \".\" in name:\n out.extend(_split_blueprint_path(name.rpartition(\".\")[0]))\n\n return out"} {"repo":"flask","file":"src/flask/helpers.py","line":654,"symbol":"_CollectErrors","kind":"class","lang":"python","code":"class _CollectErrors:\n \"\"\"A context manager that records and silences an error raised within it.\n Used to run all teardown functions, then raise any errors afterward.\n \"\"\"\n\n def __init__(self) -> None:\n self.errors: list[BaseException] = []\n\n def __enter__(self) -> None:\n pass\n\n def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc_val: BaseException | None,\n exc_tb: TracebackType | None,\n ) -> bool:\n if exc_val is not None:\n self.errors.append(exc_val)\n\n return True\n\n def raise_any(self, message: str) -> None:\n \"\"\"Raise if any errors were collected.\"\"\"\n if self.errors:\n if sys.version_info >= (3, 11):\n raise BaseExceptionGroup(message, self.errors) # noqa: F821\n else:\n raise self.errors[0]"} {"repo":"flask","file":"src/flask/helpers.py","line":659,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.errors: list[BaseException] = []"} {"repo":"flask","file":"src/flask/helpers.py","line":662,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self) -> None:\n pass"} {"repo":"flask","file":"src/flask/helpers.py","line":665,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc_val: BaseException | None,\n exc_tb: TracebackType | None,\n ) -> bool:\n if exc_val is not None:\n self.errors.append(exc_val)\n\n return True"} {"repo":"flask","file":"src/flask/helpers.py","line":676,"symbol":"raise_any","kind":"function","lang":"python","code":"def raise_any(self, message: str) -> None:\n \"\"\"Raise if any errors were collected.\"\"\"\n if self.errors:\n if sys.version_info >= (3, 11):\n raise BaseExceptionGroup(message, self.errors) # noqa: F821\n else:\n raise self.errors[0]"} {"repo":"flask","file":"src/flask/json/__init__.py","line":13,"symbol":"dumps","kind":"function","lang":"python","code":"def dumps(obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dumps() `\n method, otherwise it will use :func:`json.dumps`.\n\n :param obj: The data to serialize.\n :param kwargs: Arguments passed to the ``dumps`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dumps``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.dumps(obj, **kwargs)\n\n kwargs.setdefault(\"default\", _default)\n return _json.dumps(obj, **kwargs)"} {"repo":"flask","file":"src/flask/json/__init__.py","line":47,"symbol":"dump","kind":"function","lang":"python","code":"def dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dump() `\n method, otherwise it will use :func:`json.dump`.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: Arguments passed to the ``dump`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dump``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, will be\n removed in Flask 2.1.\n \"\"\"\n if current_app:\n current_app.json.dump(obj, fp, **kwargs)\n else:\n kwargs.setdefault(\"default\", _default)\n _json.dump(obj, fp, **kwargs)"} {"repo":"flask","file":"src/flask/json/__init__.py","line":77,"symbol":"loads","kind":"function","lang":"python","code":"def loads(s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.loads() `\n method, otherwise it will use :func:`json.loads`.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``loads`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.loads``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The data must be a\n string or UTF-8 bytes.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.loads(s, **kwargs)\n\n return _json.loads(s, **kwargs)"} {"repo":"flask","file":"src/flask/json/__init__.py","line":108,"symbol":"load","kind":"function","lang":"python","code":"def load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.load() `\n method, otherwise it will use :func:`json.load`.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``load`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.load``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.2\n The ``app`` parameter will be removed in Flask 2.3.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The file must be text\n mode, or binary mode with UTF-8 bytes.\n \"\"\"\n if current_app:\n return current_app.json.load(fp, **kwargs)\n\n return _json.load(fp, **kwargs)"} {"repo":"flask","file":"src/flask/json/__init__.py","line":138,"symbol":"jsonify","kind":"function","lang":"python","code":"def jsonify(*args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype. A dict or list returned from a view will be converted to a\n JSON response automatically without needing to call this.\n\n This requires an active app context, and calls\n :meth:`app.json.response() `.\n\n In debug mode, the output is formatted with indentation to make it\n easier to read. This may also be controlled by the provider.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.response``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 0.11\n Added support for serializing top-level arrays. This was a\n securi"} {"repo":"flask","file":"src/flask/json/provider.py","line":19,"symbol":"JSONProvider","kind":"class","lang":"python","code":"class JSONProvider:\n \"\"\"A standard set of JSON operations for an application. Subclasses\n of this can be used to customize JSON behavior or use different\n JSON libraries.\n\n To implement a provider for a specific library, subclass this base\n class and implement at least :meth:`dumps` and :meth:`loads`. All\n other methods have default implementations.\n\n To use a different provider, either subclass ``Flask`` and set\n :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n :attr:`app.json ` to an instance of the class.\n\n :param app: An application instance. This will be stored as a\n :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n .. versionadded:: 2.2\n \"\"\"\n\n def __init__(self, app: App) -> None:\n self._app: App = weakref.proxy(app)\n\n def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError\n\n def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write "} {"repo":"flask","file":"src/flask/json/provider.py","line":38,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, app: App) -> None:\n self._app: App = weakref.proxy(app)"} {"repo":"flask","file":"src/flask/json/provider.py","line":41,"symbol":"dumps","kind":"function","lang":"python","code":"def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/json/provider.py","line":49,"symbol":"dump","kind":"function","lang":"python","code":"def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n fp.write(self.dumps(obj, **kwargs))"} {"repo":"flask","file":"src/flask/json/provider.py","line":59,"symbol":"loads","kind":"function","lang":"python","code":"def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/json/provider.py","line":67,"symbol":"load","kind":"function","lang":"python","code":"def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n return self.loads(fp.read(), **kwargs)"} {"repo":"flask","file":"src/flask/json/provider.py","line":75,"symbol":"_prepare_response_obj","kind":"function","lang":"python","code":"def _prepare_response_obj(\n self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n ) -> t.Any:\n if args and kwargs:\n raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n if not args and not kwargs:\n return None\n\n if len(args) == 1:\n return args[0]\n\n return args or kwargs"} {"repo":"flask","file":"src/flask/json/provider.py","line":89,"symbol":"response","kind":"function","lang":"python","code":"def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype.\n\n The :func:`~flask.json.jsonify` function calls this method for\n the current application.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n \"\"\"\n obj = self._prepare_response_obj(args, kwargs)\n return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")"} {"repo":"flask","file":"src/flask/json/provider.py","line":108,"symbol":"_default","kind":"function","lang":"python","code":"def _default(o: t.Any) -> t.Any:\n if isinstance(o, date):\n return http_date(o)\n\n if isinstance(o, (decimal.Decimal, uuid.UUID)):\n return str(o)\n\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o) # type: ignore[arg-type]\n\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n\n raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")"} {"repo":"flask","file":"src/flask/json/provider.py","line":124,"symbol":"DefaultJSONProvider","kind":"class","lang":"python","code":"class DefaultJSONProvider(JSONProvider):\n \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n library. Serializes the following additional data types:\n\n - :class:`datetime.datetime` and :class:`datetime.date` are\n serialized to :rfc:`822` strings. This is the same as the HTTP\n date format.\n - :class:`uuid.UUID` is serialized to a string.\n - :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n - :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n \"\"\"\n\n default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n \"\"\"Apply this function to any object that :meth:`json.dumps` does\n not know how to serialize. It should return a valid JSON type or\n raise a ``TypeError``.\n \"\"\"\n\n ensure_ascii = True\n \"\"\"Replace non-ASCII characters with escape sequences. This may be\n more compatible with some clients, but can be disabled for better\n performance and size.\n \"\"\"\n\n sort_keys = True\n \"\"\"Sort the keys in any serialized dicts. This may be useful for\n some caching situations, but can be disabled for "} {"repo":"flask","file":"src/flask/json/provider.py","line":166,"symbol":"dumps","kind":"function","lang":"python","code":"def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON to a string.\n\n Keyword arguments are passed to :func:`json.dumps`. Sets some\n parameter defaults from the :attr:`default`,\n :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n :param obj: The data to serialize.\n :param kwargs: Passed to :func:`json.dumps`.\n \"\"\"\n kwargs.setdefault(\"default\", self.default)\n kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n kwargs.setdefault(\"sort_keys\", self.sort_keys)\n return json.dumps(obj, **kwargs)"} {"repo":"flask","file":"src/flask/json/provider.py","line":181,"symbol":"loads","kind":"function","lang":"python","code":"def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON from a string or bytes.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: Passed to :func:`json.loads`.\n \"\"\"\n return json.loads(s, **kwargs)"} {"repo":"flask","file":"src/flask/json/provider.py","line":189,"symbol":"response","kind":"function","lang":"python","code":"def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with it. The response mimetype\n will be \"application/json\" and can be changed with\n :attr:`mimetype`.\n\n If :attr:`compact` is ``False`` or debug mode is enabled, the\n output will be formatted to be easier to read.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n \"\"\"\n obj = self._prepare_response_obj(args, kwargs)\n dump_args: dict[str, t.Any] = {}\n\n if (self.compact is None and self._app.debug) or self.compact is False:\n dump_args.setdefault(\"indent\", 2)\n else:\n dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n return self._app.response_class(\n f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n )"} {"repo":"flask","file":"src/flask/json/tag.py","line":60,"symbol":"JSONTag","kind":"class","lang":"python","code":"class JSONTag:\n \"\"\"Base class for defining type tags for :class:`TaggedJSONSerializer`.\"\"\"\n\n __slots__ = (\"serializer\",)\n\n #: The tag to mark the serialized object with. If empty, this tag is\n #: only used as an intermediate step during tagging.\n key: str = \"\"\n\n def __init__(self, serializer: TaggedJSONSerializer) -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer\n\n def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError\n\n def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError\n\n def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) -> dict[str, t.Any]:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}"} {"repo":"flask","file":"src/flask/json/tag.py","line":69,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, serializer: TaggedJSONSerializer) -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer"} {"repo":"flask","file":"src/flask/json/tag.py","line":73,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/json/tag.py","line":77,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/json/tag.py","line":82,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/json/tag.py","line":87,"symbol":"tag","kind":"function","lang":"python","code":"def tag(self, value: t.Any) -> dict[str, t.Any]:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}"} {"repo":"flask","file":"src/flask/json/tag.py","line":93,"symbol":"TagDict","kind":"class","lang":"python","code":"class TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}"} {"repo":"flask","file":"src/flask/json/tag.py","line":103,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )"} {"repo":"flask","file":"src/flask/json/tag.py","line":110,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}"} {"repo":"flask","file":"src/flask/json/tag.py","line":114,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}"} {"repo":"flask","file":"src/flask/json/tag.py","line":119,"symbol":"PassDict","kind":"class","lang":"python","code":"class PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json"} {"repo":"flask","file":"src/flask/json/tag.py","line":122,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)"} {"repo":"flask","file":"src/flask/json/tag.py","line":125,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}"} {"repo":"flask","file":"src/flask/json/tag.py","line":133,"symbol":"TagTuple","kind":"class","lang":"python","code":"class TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":137,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)"} {"repo":"flask","file":"src/flask/json/tag.py","line":140,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]"} {"repo":"flask","file":"src/flask/json/tag.py","line":143,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":147,"symbol":"PassList","kind":"class","lang":"python","code":"class PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json"} {"repo":"flask","file":"src/flask/json/tag.py","line":150,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, list)"} {"repo":"flask","file":"src/flask/json/tag.py","line":153,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]"} {"repo":"flask","file":"src/flask/json/tag.py","line":159,"symbol":"TagBytes","kind":"class","lang":"python","code":"class TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":163,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)"} {"repo":"flask","file":"src/flask/json/tag.py","line":166,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")"} {"repo":"flask","file":"src/flask/json/tag.py","line":169,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":173,"symbol":"TagMarkup","kind":"class","lang":"python","code":"class TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":181,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))"} {"repo":"flask","file":"src/flask/json/tag.py","line":184,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())"} {"repo":"flask","file":"src/flask/json/tag.py","line":187,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":191,"symbol":"TagUUID","kind":"class","lang":"python","code":"class TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) -> t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":195,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)"} {"repo":"flask","file":"src/flask/json/tag.py","line":198,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return value.hex"} {"repo":"flask","file":"src/flask/json/tag.py","line":201,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":205,"symbol":"TagDateTime","kind":"class","lang":"python","code":"class TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":209,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)"} {"repo":"flask","file":"src/flask/json/tag.py","line":212,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":215,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)"} {"repo":"flask","file":"src/flask/json/tag.py","line":219,"symbol":"TaggedJSONSerializer","kind":"class","lang":"python","code":"class TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) -> None:\n self.tags: dict[str, JSONTag] = {}\n self.order: list[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: type[JSONTag],\n force: bool = False,\n index: int | None = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated "} {"repo":"flask","file":"src/flask/json/tag.py","line":249,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.tags: dict[str, JSONTag] = {}\n self.order: list[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)"} {"repo":"flask","file":"src/flask/json/tag.py","line":256,"symbol":"register","kind":"function","lang":"python","code":"def register(\n self,\n tag_class: type[JSONTag],\n force: bool = False,\n index: int | None = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)"} {"repo":"flask","file":"src/flask/json/tag.py","line":289,"symbol":"tag","kind":"function","lang":"python","code":"def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert a value to a tagged representation if necessary.\"\"\"\n for tag in self.order:\n if tag.check(value):\n return tag.tag(value)\n\n return value"} {"repo":"flask","file":"src/flask/json/tag.py","line":297,"symbol":"untag","kind":"function","lang":"python","code":"def untag(self, value: dict[str, t.Any]) -> t.Any:\n \"\"\"Convert a tagged representation back to the original type.\"\"\"\n if len(value) != 1:\n return value\n\n key = next(iter(value))\n\n if key not in self.tags:\n return value\n\n return self.tags[key].to_python(value[key])"} {"repo":"flask","file":"src/flask/json/tag.py","line":309,"symbol":"_untag_scan","kind":"function","lang":"python","code":"def _untag_scan(self, value: t.Any) -> t.Any:\n if isinstance(value, dict):\n # untag each item recursively\n value = {k: self._untag_scan(v) for k, v in value.items()}\n # untag the dict itself\n value = self.untag(value)\n elif isinstance(value, list):\n # untag each item recursively\n value = [self._untag_scan(item) for item in value]\n\n return value"} {"repo":"flask","file":"src/flask/json/tag.py","line":321,"symbol":"dumps","kind":"function","lang":"python","code":"def dumps(self, value: t.Any) -> str:\n \"\"\"Tag the value and dump it to a compact JSON string.\"\"\"\n return dumps(self.tag(value), separators=(\",\", \":\"))"} {"repo":"flask","file":"src/flask/json/tag.py","line":325,"symbol":"loads","kind":"function","lang":"python","code":"def loads(self, value: str) -> t.Any:\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return self._untag_scan(loads(value))"} {"repo":"flask","file":"src/flask/logging.py","line":16,"symbol":"wsgi_errors_stream","kind":"function","lang":"python","code":"def wsgi_errors_stream() -> t.TextIO:\n \"\"\"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n \"\"\"\n if request:\n return request.environ[\"wsgi.errors\"] # type: ignore[no-any-return]\n\n return sys.stderr"} {"repo":"flask","file":"src/flask/logging.py","line":31,"symbol":"has_level_handler","kind":"function","lang":"python","code":"def has_level_handler(logger: logging.Logger) -> bool:\n \"\"\"Check if there is a handler in the logging chain that will handle the\n given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.\n \"\"\"\n level = logger.getEffectiveLevel()\n current = logger\n\n while current:\n if any(handler.level <= level for handler in current.handlers):\n return True\n\n if not current.propagate:\n break\n\n current = current.parent # type: ignore\n\n return False"} {"repo":"flask","file":"src/flask/logging.py","line":58,"symbol":"create_logger","kind":"function","lang":"python","code":"def create_logger(app: App) -> logging.Logger:\n \"\"\"Get the Flask app's logger and configure it if needed.\n\n The logger name will be the same as\n :attr:`app.import_name `.\n\n When :attr:`~flask.Flask.debug` is enabled, set the logger level to\n :data:`logging.DEBUG` if it is not set.\n\n If there is no handler for the logger's effective level, add a\n :class:`~logging.StreamHandler` for\n :func:`~flask.logging.wsgi_errors_stream` with a basic format.\n \"\"\"\n logger = logging.getLogger(app.name)\n\n if app.debug and not logger.level:\n logger.setLevel(logging.DEBUG)\n\n if not has_level_handler(logger):\n logger.addHandler(default_handler)\n\n return logger"} {"repo":"flask","file":"src/flask/sansio/app.py","line":52,"symbol":"_make_timedelta","kind":"function","lang":"python","code":"def _make_timedelta(value: timedelta | int | None) -> timedelta | None:\n if value is None or isinstance(value, timedelta):\n return value\n\n return timedelta(seconds=value)"} {"repo":"flask","file":"src/flask/sansio/app.py","line":59,"symbol":"App","kind":"class","lang":"python","code":"class App(Scaffold):\n \"\"\"The flask object implements a WSGI application and acts as the central\n object. It is passed the name of the module or package of the\n application. Once it is created it will act as a central registry for\n the view functions, the URL rules, template configuration and much more.\n\n The name of the package is used to resolve resources from inside the\n package or the folder the module is contained in depending on if the\n package parameter resolves to an actual python package (a folder with\n an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n For more information about resource loading, see :func:`open_resource`.\n\n Usually you create a :class:`Flask` instance in your main module or\n in the :file:`__init__.py` file of your package like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n .. admonition:: About the First Parameter\n\n The idea of the first parameter is to give Flask an idea of what\n belongs to your application. This name is used to find resources\n on the filesystem, can be used by extensions to improve debugging\n information and a lot m"} {"repo":"flask","file":"src/flask/sansio/app.py","line":279,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n import_name: str,\n static_url_path: str | None = None,\n static_folder: str | os.PathLike[str] | None = \"static\",\n static_host: str | None = None,\n host_matching: bool = False,\n subdomain_matching: bool = False,\n template_folder: str | os.PathLike[str] | None = \"templates\",\n instance_path: str | None = None,\n instance_relative_config: bool = False,\n root_path: str | None = None,\n ) -> None:\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if instance_path is None:\n instance_path = self.auto_find_instance_path()\n elif not os.path.isabs(instance_path):\n raise ValueError(\n \"If an instance path is provided it must be absolute.\"\n \" A relative path was given instead.\"\n )\n\n #: Holds the path to the instance folder.\n #:\n #: .. versionadded:: 0.8\n self.instance_path = instance_path\n\n #: The conf"} {"repo":"flask","file":"src/flask/sansio/app.py","line":410,"symbol":"_check_setup_finished","kind":"function","lang":"python","code":"def _check_setup_finished(self, f_name: str) -> None:\n if self._got_first_request:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called\"\n \" on the application. It has already handled its first\"\n \" request, any changes will not be applied\"\n \" consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc.\"\n \" needed to set up the application are done before\"\n \" running it.\"\n )"} {"repo":"flask","file":"src/flask/sansio/app.py","line":423,"symbol":"name","kind":"function","lang":"python","code":"def name(self) -> str:\n \"\"\"The name of the application. This is usually the import name\n with the difference that it's guessed from the run file if the\n import name is main. This name is used as a display name when\n Flask needs the name of the application. It can be set and overridden\n to change the value.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.import_name == \"__main__\":\n fn: str | None = getattr(sys.modules[\"__main__\"], \"__file__\", None)\n if fn is None:\n return \"__main__\"\n return os.path.splitext(os.path.basename(fn))[0]\n return self.import_name"} {"repo":"flask","file":"src/flask/sansio/app.py","line":440,"symbol":"logger","kind":"function","lang":"python","code":"def logger(self) -> logging.Logger:\n \"\"\"A standard Python :class:`~logging.Logger` for the app, with\n the same name as :attr:`name`.\n\n In debug mode, the logger's :attr:`~logging.Logger.level` will\n be set to :data:`~logging.DEBUG`.\n\n If there are no handlers configured, a default handler will be\n added. See :doc:`/logging` for more information.\n\n .. versionchanged:: 1.1.0\n The logger takes the same name as :attr:`name` rather than\n hard-coding ``\"flask.app\"``.\n\n .. versionchanged:: 1.0.0\n Behavior was simplified. The logger is always named\n ``\"flask.app\"``. The level is only set during configuration,\n it doesn't check ``app.debug`` each time. Only one format is\n used, not different ones depending on ``app.debug``. No\n handlers are removed, and a handler is only added if no\n handlers are already configured.\n\n .. versionadded:: 0.3\n \"\"\"\n return create_logger(self)"} {"repo":"flask","file":"src/flask/sansio/app.py","line":467,"symbol":"jinja_env","kind":"function","lang":"python","code":"def jinja_env(self) -> Environment:\n \"\"\"The Jinja environment used to load templates.\n\n The environment is created the first time this property is\n accessed. Changing :attr:`jinja_options` after that will have no\n effect.\n \"\"\"\n return self.create_jinja_environment()"} {"repo":"flask","file":"src/flask/sansio/app.py","line":476,"symbol":"create_jinja_environment","kind":"function","lang":"python","code":"def create_jinja_environment(self) -> Environment:\n raise NotImplementedError()"} {"repo":"flask","file":"src/flask/sansio/app.py","line":479,"symbol":"make_config","kind":"function","lang":"python","code":"def make_config(self, instance_relative: bool = False) -> Config:\n \"\"\"Used to create the config attribute by the Flask constructor.\n The `instance_relative` parameter is passed in from the constructor\n of Flask (there named `instance_relative_config`) and indicates if\n the config should be relative to the instance path or the root path\n of the application.\n\n .. versionadded:: 0.8\n \"\"\"\n root_path = self.root_path\n if instance_relative:\n root_path = self.instance_path\n defaults = dict(self.default_config)\n defaults[\"DEBUG\"] = get_debug_flag()\n return self.config_class(root_path, defaults)"} {"repo":"flask","file":"src/flask/sansio/app.py","line":495,"symbol":"make_aborter","kind":"function","lang":"python","code":"def make_aborter(self) -> Aborter:\n \"\"\"Create the object to assign to :attr:`aborter`. That object\n is called by :func:`flask.abort` to raise HTTP errors, and can\n be called directly as well.\n\n By default, this creates an instance of :attr:`aborter_class`,\n which defaults to :class:`werkzeug.exceptions.Aborter`.\n\n .. versionadded:: 2.2\n \"\"\"\n return self.aborter_class()"} {"repo":"flask","file":"src/flask/sansio/app.py","line":507,"symbol":"auto_find_instance_path","kind":"function","lang":"python","code":"def auto_find_instance_path(self) -> str:\n \"\"\"Tries to locate the instance path if it was not provided to the\n constructor of the application class. It will basically calculate\n the path to a folder named ``instance`` next to your main file or\n the package.\n\n .. versionadded:: 0.8\n \"\"\"\n prefix, package_path = find_package(self.import_name)\n if prefix is None:\n return os.path.join(package_path, \"instance\")\n return os.path.join(prefix, \"var\", f\"{self.name}-instance\")"} {"repo":"flask","file":"src/flask/sansio/app.py","line":520,"symbol":"create_global_jinja_loader","kind":"function","lang":"python","code":"def create_global_jinja_loader(self) -> DispatchingJinjaLoader:\n \"\"\"Creates the loader for the Jinja environment. Can be used to\n override just the loader and keeping the rest unchanged. It's\n discouraged to override this function. Instead one should override\n the :meth:`jinja_loader` function instead.\n\n The global loader dispatches between the loaders of the application\n and the individual blueprints.\n\n .. versionadded:: 0.7\n \"\"\"\n return DispatchingJinjaLoader(self)"} {"repo":"flask","file":"src/flask/sansio/app.py","line":533,"symbol":"select_jinja_autoescape","kind":"function","lang":"python","code":"def select_jinja_autoescape(self, filename: str | None) -> bool:\n \"\"\"Returns ``True`` if autoescaping should be active for the given\n template name. If no template name is given, returns `True`.\n\n .. versionchanged:: 3.2\n Use case-insensitive comparison instead of only lower case.\n\n .. versionchanged:: 2.2\n Autoescaping is now enabled by default for ``.svg`` files.\n\n .. versionadded:: 0.5\n \"\"\"\n if filename is None:\n return True\n return filename.lower().endswith((\".html\", \".htm\", \".xml\", \".xhtml\", \".svg\"))"} {"repo":"flask","file":"src/flask/sansio/app.py","line":550,"symbol":"debug","kind":"function","lang":"python","code":"def debug(self) -> bool:\n \"\"\"Whether debug mode is enabled. When using ``flask run`` to start the\n development server, an interactive debugger will be shown for unhandled\n exceptions, and the server will be reloaded when code changes. This maps to the\n :data:`DEBUG` config key. It may not behave as expected if set late.\n\n **Do not enable debug mode when deploying in production.**\n\n Default: ``False``\n \"\"\"\n return self.config[\"DEBUG\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sansio/app.py","line":563,"symbol":"debug","kind":"function","lang":"python","code":"def debug(self, value: bool) -> None:\n self.config[\"DEBUG\"] = value\n\n if self.config[\"TEMPLATES_AUTO_RELOAD\"] is None:\n self.jinja_env.auto_reload = value"} {"repo":"flask","file":"src/flask/sansio/app.py","line":570,"symbol":"register_blueprint","kind":"function","lang":"python","code":"def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on the application. Keyword\n arguments passed to this method will override the defaults set on the\n blueprint.\n\n Calls the blueprint's :meth:`~flask.Blueprint.register` method after\n recording the blueprint in the application's :attr:`blueprints`.\n\n :param blueprint: The blueprint to register.\n :param url_prefix: Blueprint routes will be prefixed with this.\n :param subdomain: Blueprint routes will match on this subdomain.\n :param url_defaults: Blueprint routes will use these default values for\n view arguments.\n :param options: Additional keyword arguments are passed to\n :class:`~flask.blueprints.BlueprintSetupState`. They can be\n accessed in :meth:`~flask.Blueprint.record` callbacks.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n\n "} {"repo":"flask","file":"src/flask/sansio/app.py","line":597,"symbol":"iter_blueprints","kind":"function","lang":"python","code":"def iter_blueprints(self) -> t.ValuesView[Blueprint]:\n \"\"\"Iterates over all blueprints by the order they were registered.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.blueprints.values()"} {"repo":"flask","file":"src/flask/sansio/app.py","line":605,"symbol":"add_url_rule","kind":"function","lang":"python","code":"def add_url_rule(\n self,\n rule: str,\n endpoint: str | None = None,\n view_func: ft.RouteCallable | None = None,\n provide_automatic_options: bool | None = None,\n **options: t.Any,\n ) -> None:\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n options[\"endpoint\"] = endpoint\n methods = options.pop(\"methods\", None)\n\n # if the methods are not given and the view_func object knows its\n # methods we can use that instead. If neither exists, we go with\n # a tuple of only ``GET`` as default.\n if methods is None:\n methods = getattr(view_func, \"methods\", None) or (\"GET\",)\n if isinstance(methods, str):\n raise TypeError(\n \"Allowed methods must be a list of strings, for\"\n ' example: @app.route(..., methods=[\"POST\"])'\n )\n methods = {item.upper() for item in methods}\n\n # Methods that should always be added\n required_methods: set[str] = set(getattr(view_func, \"required_methods\", ()))\n\n if provide_automatic_options is None:\n provide_automatic_options = get"} {"repo":"flask","file":"src/flask/sansio/app.py","line":664,"symbol":"template_filter","kind":"function","lang":"python","code":"def template_filter(self, name: T_template_filter) -> T_template_filter: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":666,"symbol":"template_filter","kind":"function","lang":"python","code":"def template_filter(\n self, name: str | None = None\n ) -> t.Callable[[T_template_filter], T_template_filter]: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":670,"symbol":"template_filter","kind":"function","lang":"python","code":"def template_filter(\n self, name: T_template_filter | str | None = None\n ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n is optional. The decorator may be used without parentheses.\n\n .. code-block:: python\n\n @app.template_filter(\"reverse\")\n def reverse_filter(s):\n return reversed(s)\n\n The :meth:`add_template_filter` method may be used to register a\n function later rather than decorating.\n\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n \"\"\"\n if callable(name):\n self.add_template_filter(name)\n return name\n\n def decorator(f: T_template_filter) -> T_template_filter:\n self.add_template_filter(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/app.py","line":692,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_filter) -> T_template_filter:\n self.add_template_filter(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":699,"symbol":"add_template_filter","kind":"function","lang":"python","code":"def add_template_filter(\n self, f: ft.TemplateFilterCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja filter.\n\n The :meth:`template_filter` decorator can be used to register a function\n by decorating instead.\n\n :param f: The function to register.\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n \"\"\"\n self.jinja_env.filters[name or f.__name__] = f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":714,"symbol":"template_test","kind":"function","lang":"python","code":"def template_test(self, name: T_template_test) -> T_template_test: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":716,"symbol":"template_test","kind":"function","lang":"python","code":"def template_test(\n self, name: str | None = None\n ) -> t.Callable[[T_template_test], T_template_test]: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":720,"symbol":"template_test","kind":"function","lang":"python","code":"def template_test(\n self, name: T_template_test | str | None = None\n ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n \"\"\"Decorate a function to register it as a custom Jinja test. The name\n is optional. The decorator may be used without parentheses.\n\n .. code-block:: python\n\n @app.template_test(\"prime\")\n def is_prime_test(n):\n if n == 2:\n return True\n for i in range(2, int(math.ceil(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True\n\n The :meth:`add_template_test` method may be used to register a function\n later rather than decorating.\n\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n if callable(name):\n self.add_template_test(name)\n return name\n\n def decorator(f: T_template_test) -> T_template_test:\n self.add_template_test(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/app.py","line":749,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_test) -> T_template_test:\n self.add_template_test(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":756,"symbol":"add_template_test","kind":"function","lang":"python","code":"def add_template_test(\n self, f: ft.TemplateTestCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja test.\n\n The :meth:`template_test` decorator can be used to register a function\n by decorating instead.\n\n :param f: The function to register.\n :param name: The name to register the test as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n self.jinja_env.tests[name or f.__name__] = f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":773,"symbol":"template_global","kind":"function","lang":"python","code":"def template_global(self, name: T_template_global) -> T_template_global: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":775,"symbol":"template_global","kind":"function","lang":"python","code":"def template_global(\n self, name: str | None = None\n ) -> t.Callable[[T_template_global], T_template_global]: ..."} {"repo":"flask","file":"src/flask/sansio/app.py","line":779,"symbol":"template_global","kind":"function","lang":"python","code":"def template_global(\n self, name: T_template_global | str | None = None\n ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n \"\"\"Decorate a function to register it as a custom Jinja global. The name\n is optional. The decorator may be used without parentheses.\n\n .. code-block:: python\n\n @app.template_global\n def double(n):\n return 2 * n\n\n The :meth:`add_template_global` method may be used to register a\n function later rather than decorating.\n\n :param name: The name to register the global as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n if callable(name):\n self.add_template_global(name)\n return name\n\n def decorator(f: T_template_global) -> T_template_global:\n self.add_template_global(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/app.py","line":803,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_global) -> T_template_global:\n self.add_template_global(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":810,"symbol":"add_template_global","kind":"function","lang":"python","code":"def add_template_global(\n self, f: ft.TemplateGlobalCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja global.\n\n The :meth:`template_global` decorator can be used to register a function\n by decorating instead.\n\n :param f: The function to register.\n :param name: The name to register the global as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n self.jinja_env.globals[name or f.__name__] = f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":827,"symbol":"teardown_appcontext","kind":"function","lang":"python","code":"def teardown_appcontext(self, f: T_teardown) -> T_teardown:\n \"\"\"Registers a function to be called when the app context is popped. The\n context is popped at the end of a request, CLI command, or manual ``with``\n block.\n\n .. code-block:: python\n\n with app.app_context():\n ...\n\n When the ``with`` block exits (or ``ctx.pop()`` is called), the\n teardown functions are called just before the app context is\n made inactive.\n\n When a teardown function was called because of an unhandled\n exception it will be passed an error object. If an\n :meth:`errorhandler` is registered, it will handle the exception\n and the teardown will not receive it.\n\n Teardown functions must avoid raising exceptions. If they\n execute code that might fail they must surround that code with a\n ``try``/``except`` block and log any errors.\n\n The return values of teardown functions are ignored.\n\n .. versionadded:: 0.9\n \"\"\"\n self.teardown_appcontext_funcs.append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":858,"symbol":"shell_context_processor","kind":"function","lang":"python","code":"def shell_context_processor(\n self, f: T_shell_context_processor\n ) -> T_shell_context_processor:\n \"\"\"Registers a shell context processor function.\n\n .. versionadded:: 0.11\n \"\"\"\n self.shell_context_processors.append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/app.py","line":868,"symbol":"_find_error_handler","kind":"function","lang":"python","code":"def _find_error_handler(\n self, e: Exception, blueprints: list[str]\n ) -> ft.ErrorHandlerCallable | None:\n \"\"\"Return a registered error handler for an exception in this order:\n blueprint handler for a specific code, app handler for a specific code,\n blueprint handler for an exception class, app handler for an exception\n class, or ``None`` if a suitable handler is not found.\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(type(e))\n names = (*blueprints, None)\n\n for c in (code, None) if code is not None else (None,):\n for name in names:\n handler_map = self.error_handler_spec[name][c]\n\n if not handler_map:\n continue\n\n for cls in exc_class.__mro__:\n handler = handler_map.get(cls)\n\n if handler is not None:\n return handler\n return None"} {"repo":"flask","file":"src/flask/sansio/app.py","line":893,"symbol":"trap_http_exception","kind":"function","lang":"python","code":"def trap_http_exception(self, e: Exception) -> bool:\n \"\"\"Checks if an HTTP exception should be trapped or not. By default\n this will return ``False`` for all exceptions except for a bad request\n key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It\n also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.\n\n This is called for all HTTP exceptions raised by a view function.\n If it returns ``True`` for any exception the error handler for this\n exception is not called and it shows up as regular exception in the\n traceback. This is helpful for debugging implicitly raised HTTP\n exceptions.\n\n .. versionchanged:: 1.0\n Bad request errors are not trapped by default in debug mode.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.config[\"TRAP_HTTP_EXCEPTIONS\"]:\n return True\n\n trap_bad_request = self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n\n # if unset, trap key errors in debug mode\n if (\n trap_bad_request is None\n and self.debug\n and isinstance(e, BadRequestKeyError)\n ):\n return True\n\n if trap_ba"} {"repo":"flask","file":"src/flask/sansio/app.py","line":939,"symbol":"redirect","kind":"function","lang":"python","code":"def redirect(self, location: str, code: int = 303) -> BaseResponse:\n \"\"\"Create a redirect response object.\n\n This is called by :func:`flask.redirect`, and can be called\n directly as well.\n\n :param location: The URL to redirect to.\n :param code: The status code for the redirect.\n\n .. versionchanged:: 3.2\n ``code`` defaults to ``303`` instead of ``302``.\n\n .. versionadded:: 2.2\n Moved from ``flask.redirect``, which calls this method.\n \"\"\"\n return _wz_redirect(\n location,\n code=code,\n Response=self.response_class, # type: ignore[arg-type]\n )"} {"repo":"flask","file":"src/flask/sansio/app.py","line":960,"symbol":"inject_url_defaults","kind":"function","lang":"python","code":"def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None:\n \"\"\"Injects the URL defaults for the given endpoint directly into\n the values dictionary passed. This is used internally and\n automatically called on URL building.\n\n .. versionadded:: 0.7\n \"\"\"\n names: t.Iterable[str | None] = (None,)\n\n # url_for may be called outside a request context, parse the\n # passed endpoint instead of using request.blueprints.\n if \".\" in endpoint:\n names = chain(\n names, reversed(_split_blueprint_path(endpoint.rpartition(\".\")[0]))\n )\n\n for name in names:\n if name in self.url_default_functions:\n for func in self.url_default_functions[name]:\n func(endpoint, values)"} {"repo":"flask","file":"src/flask/sansio/app.py","line":981,"symbol":"handle_url_build_error","kind":"function","lang":"python","code":"def handle_url_build_error(\n self, error: BuildError, endpoint: str, values: dict[str, t.Any]\n ) -> str:\n \"\"\"Called by :meth:`.url_for` if a\n :exc:`~werkzeug.routing.BuildError` was raised. If this returns\n a value, it will be returned by ``url_for``, otherwise the error\n will be re-raised.\n\n Each function in :attr:`url_build_error_handlers` is called with\n ``error``, ``endpoint`` and ``values``. If a function returns\n ``None`` or raises a ``BuildError``, it is skipped. Otherwise,\n its return value is returned by ``url_for``.\n\n :param error: The active ``BuildError`` being handled.\n :param endpoint: The endpoint being built.\n :param values: The keyword arguments passed to ``url_for``.\n \"\"\"\n for handler in self.url_build_error_handlers:\n try:\n rv = handler(error, endpoint, values)\n except BuildError as e:\n # make error available outside except block\n error = e\n else:\n if rv is not None:\n return rv\n\n # Re-raise if called with an active exception, otherwise raise\n "} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":34,"symbol":"BlueprintSetupState","kind":"class","lang":"python","code":"class BlueprintSetupState:\n \"\"\"Temporary holder object for registering a blueprint with the\n application. An instance of this class is created by the\n :meth:`~flask.Blueprint.make_setup_state` method and later passed\n to all register callback functions.\n \"\"\"\n\n def __init__(\n self,\n blueprint: Blueprint,\n app: App,\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.b"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":41,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n blueprint: Blueprint,\n app: App,\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":87,"symbol":"add_url_rule","kind":"function","lang":"python","code":"def add_url_rule(\n self,\n rule: str,\n endpoint: str | None = None,\n view_func: ft.RouteCallable | None = None,\n **options: t.Any,\n ) -> None:\n \"\"\"A helper method to register a rule (and optionally a view function)\n to the application. The endpoint is automatically prefixed with the\n blueprint's name.\n \"\"\"\n if self.url_prefix is not None:\n if rule:\n rule = \"/\".join((self.url_prefix.rstrip(\"/\"), rule.lstrip(\"/\")))\n else:\n rule = self.url_prefix\n options.setdefault(\"subdomain\", self.subdomain)\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n defaults = self.url_defaults\n if \"defaults\" in options:\n defaults = dict(defaults, **options.pop(\"defaults\"))\n\n self.app.add_url_rule(\n rule,\n f\"{self.name_prefix}.{self.name}.{endpoint}\".lstrip(\".\"),\n view_func,\n defaults=defaults,\n **options,\n )"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":119,"symbol":"Blueprint","kind":"class","lang":"python","code":"class Blueprint(Scaffold):\n \"\"\"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":174,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: str | os.PathLike[str] | None = None,\n static_url_path: str | None = None,\n template_folder: str | os.PathLike[str] | None = None,\n url_prefix: str | None = None,\n subdomain: str | None = None,\n url_defaults: dict[str, t.Any] | None = None,\n root_path: str | None = None,\n cli_group: str | None = _sentinel, # type: ignore[assignment]\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if not name:\n raise ValueError(\"'name' may not be empty.\")\n\n if \".\" in name:\n raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: list[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_g"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":213,"symbol":"_check_setup_finished","kind":"function","lang":"python","code":"def _check_setup_finished(self, f_name: str) -> None:\n if self._got_registered_once:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n f\" '{self.name}'. It has already been registered at least once, any\"\n \" changes will not be applied consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc. needed to set up\"\n \" the blueprint are done before registering it.\"\n )"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":224,"symbol":"record","kind":"function","lang":"python","code":"def record(self, func: DeferredSetupFunction) -> None:\n \"\"\"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n \"\"\"\n self.deferred_functions.append(func)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":233,"symbol":"record_once","kind":"function","lang":"python","code":"def record_once(self, func: DeferredSetupFunction) -> None:\n \"\"\"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n \"\"\"\n\n def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)\n\n self.record(update_wrapper(wrapper, func))"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":240,"symbol":"wrapper","kind":"function","lang":"python","code":"def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":246,"symbol":"make_setup_state","kind":"function","lang":"python","code":"def make_setup_state(\n self, app: App, options: dict[str, t.Any], first_registration: bool = False\n ) -> BlueprintSetupState:\n \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n \"\"\"\n return BlueprintSetupState(self, app, options, first_registration)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":256,"symbol":"register_blueprint","kind":"function","lang":"python","code":"def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n\n .. versionadded:: 2.0\n \"\"\"\n if blueprint is self:\n raise ValueError(\"Cannot register a blueprint on itself\")\n self._blueprints.append((blueprint, options))"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":273,"symbol":"register","kind":"function","lang":"python","code":"def register(self, app: App, options: dict[str, t.Any]) -> None:\n \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n views and callbacks registered on the blueprint with the\n application. Creates a :class:`.BlueprintSetupState` and calls\n each :meth:`record` callback with it.\n\n :param app: The application this blueprint is being registered\n with.\n :param options: Keyword arguments forwarded from\n :meth:`~Flask.register_blueprint`.\n\n .. versionchanged:: 2.3\n Nested blueprints now correctly apply subdomains.\n\n .. versionchanged:: 2.1\n Registering the same blueprint with the same name multiple\n times is an error.\n\n .. versionchanged:: 2.0.1\n Nested blueprints are registered with their dotted name.\n This allows different blueprints with the same name to be\n nested at different locations.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with uniqu"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":379,"symbol":"_merge_blueprint_funcs","kind":"function","lang":"python","code":"def _merge_blueprint_funcs(self, app: App, name: str) -> None:\n def extend(\n bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n ) -> None:\n for key, values in bp_dict.items():\n key = name if key is None else f\"{name}.{key}\"\n parent_dict[key].extend(values)\n\n for key, value in self.error_handler_spec.items():\n key = name if key is None else f\"{name}.{key}\"\n value = defaultdict(\n dict,\n {\n code: {exc_class: func for exc_class, func in code_values.items()}\n for code, code_values in value.items()\n },\n )\n app.error_handler_spec[key] = value\n\n for endpoint, func in self.view_functions.items():\n app.view_functions[endpoint] = func\n\n extend(self.before_request_funcs, app.before_request_funcs)\n extend(self.after_request_funcs, app.after_request_funcs)\n extend(\n self.teardown_request_funcs,\n app.teardown_request_funcs,\n )\n extend(self.url_default_functions,"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":380,"symbol":"extend","kind":"function","lang":"python","code":"def extend(\n bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],\n ) -> None:\n for key, values in bp_dict.items():\n key = name if key is None else f\"{name}.{key}\"\n parent_dict[key].extend(values)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":413,"symbol":"add_url_rule","kind":"function","lang":"python","code":"def add_url_rule(\n self,\n rule: str,\n endpoint: str | None = None,\n view_func: ft.RouteCallable | None = None,\n provide_automatic_options: bool | None = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n full documentation.\n\n The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n used with :func:`url_for`, is prefixed with the blueprint's name.\n \"\"\"\n if endpoint and \".\" in endpoint:\n raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n self.record(\n lambda s: s.add_url_rule(\n rule,\n endpoint,\n view_func,\n provide_automatic_options=provide_automatic_options,\n **options,\n )\n )"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":444,"symbol":"app_template_filter","kind":"function","lang":"python","code":"def app_template_filter(self, name: T_template_filter) -> T_template_filter: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":446,"symbol":"app_template_filter","kind":"function","lang":"python","code":"def app_template_filter(\n self, name: str | None = None\n ) -> t.Callable[[T_template_filter], T_template_filter]: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":450,"symbol":"app_template_filter","kind":"function","lang":"python","code":"def app_template_filter(\n self, name: T_template_filter | str | None = None\n ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:\n \"\"\"Decorate a function to register it as a custom Jinja filter. The name\n is optional. The decorator may be used without parentheses.\n\n The :meth:`add_app_template_filter` method may be used to register a\n function later rather than decorating.\n\n The filter is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.template_filter`.\n\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n \"\"\"\n if callable(name):\n self.add_app_template_filter(name)\n return name\n\n def decorator(f: T_template_filter) -> T_template_filter:\n self.add_app_template_filter(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":469,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_filter) -> T_template_filter:\n self.add_app_template_filter(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":476,"symbol":"add_app_template_filter","kind":"function","lang":"python","code":"def add_app_template_filter(\n self, f: ft.TemplateFilterCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja filter.\n\n The :meth:`app_template_filter` decorator can be used to register a\n function by decorating instead.\n\n The filter is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.add_template_filter`.\n\n :param f: The function to register.\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n \"\"\"\n\n def register_template_filter(state: BlueprintSetupState) -> None:\n state.app.add_template_filter(f, name=name)\n\n self.record_once(register_template_filter)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":492,"symbol":"register_template_filter","kind":"function","lang":"python","code":"def register_template_filter(state: BlueprintSetupState) -> None:\n state.app.add_template_filter(f, name=name)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":498,"symbol":"app_template_test","kind":"function","lang":"python","code":"def app_template_test(self, name: T_template_test) -> T_template_test: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":500,"symbol":"app_template_test","kind":"function","lang":"python","code":"def app_template_test(\n self, name: str | None = None\n ) -> t.Callable[[T_template_test], T_template_test]: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":504,"symbol":"app_template_test","kind":"function","lang":"python","code":"def app_template_test(\n self, name: T_template_test | str | None = None\n ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:\n \"\"\"Decorate a function to register it as a custom Jinja test. The name\n is optional. The decorator may be used without parentheses.\n\n The :meth:`add_app_template_test` method may be used to register a\n function later rather than decorating.\n\n The test is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.template_test`.\n\n :param name: The name to register the filter as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n if callable(name):\n self.add_app_template_test(name)\n return name\n\n def decorator(f: T_template_test) -> T_template_test:\n self.add_app_template_test(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":525,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_test) -> T_template_test:\n self.add_app_template_test(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":532,"symbol":"add_app_template_test","kind":"function","lang":"python","code":"def add_app_template_test(\n self, f: ft.TemplateTestCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja test.\n\n The :meth:`app_template_test` decorator can be used to register a\n function by decorating instead.\n\n The test is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.add_template_test`.\n\n :param f: The function to register.\n :param name: The name to register the test as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n\n def register_template_test(state: BlueprintSetupState) -> None:\n state.app.add_template_test(f, name=name)\n\n self.record_once(register_template_test)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":550,"symbol":"register_template_test","kind":"function","lang":"python","code":"def register_template_test(state: BlueprintSetupState) -> None:\n state.app.add_template_test(f, name=name)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":556,"symbol":"app_template_global","kind":"function","lang":"python","code":"def app_template_global(self, name: T_template_global) -> T_template_global: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":558,"symbol":"app_template_global","kind":"function","lang":"python","code":"def app_template_global(\n self, name: str | None = None\n ) -> t.Callable[[T_template_global], T_template_global]: ..."} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":562,"symbol":"app_template_global","kind":"function","lang":"python","code":"def app_template_global(\n self, name: T_template_global | str | None = None\n ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:\n \"\"\"Decorate a function to register it as a custom Jinja global. The name\n is optional. The decorator may be used without parentheses.\n\n The :meth:`add_app_template_global` method may be used to register a\n function later rather than decorating.\n\n The global is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.template_global`.\n\n :param name: The name to register the global as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n if callable(name):\n self.add_app_template_global(name)\n return name\n\n def decorator(f: T_template_global) -> T_template_global:\n self.add_app_template_global(f, name=name)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":583,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_template_global) -> T_template_global:\n self.add_app_template_global(f, name=name)\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":590,"symbol":"add_app_template_global","kind":"function","lang":"python","code":"def add_app_template_global(\n self, f: ft.TemplateGlobalCallable, name: str | None = None\n ) -> None:\n \"\"\"Register a function to use as a custom Jinja global.\n\n The :meth:`app_template_global` decorator can be used to register a function\n by decorating instead.\n\n The global is available in all templates, not only those under this\n blueprint. Equivalent to :meth:`.Flask.add_template_global`.\n\n :param f: The function to register.\n :param name: The name to register the global as. If not given, uses the\n function's name.\n\n .. versionadded:: 0.10\n \"\"\"\n\n def register_template_global(state: BlueprintSetupState) -> None:\n state.app.add_template_global(f, name=name)\n\n self.record_once(register_template_global)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":608,"symbol":"register_template_global","kind":"function","lang":"python","code":"def register_template_global(state: BlueprintSetupState) -> None:\n state.app.add_template_global(f, name=name)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":614,"symbol":"before_app_request","kind":"function","lang":"python","code":"def before_app_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":624,"symbol":"after_app_request","kind":"function","lang":"python","code":"def after_app_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":634,"symbol":"teardown_app_request","kind":"function","lang":"python","code":"def teardown_app_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":644,"symbol":"app_context_processor","kind":"function","lang":"python","code":"def app_context_processor(\n self, f: T_template_context_processor\n ) -> T_template_context_processor:\n \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":656,"symbol":"app_errorhandler","kind":"function","lang":"python","code":"def app_errorhandler(\n self, code: type[Exception] | int\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n \"\"\"\n\n def decorator(f: T_error_handler) -> T_error_handler:\n def from_blueprint(state: BlueprintSetupState) -> None:\n state.app.errorhandler(code)(f)\n\n self.record_once(from_blueprint)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":663,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_error_handler) -> T_error_handler:\n def from_blueprint(state: BlueprintSetupState) -> None:\n state.app.errorhandler(code)(f)\n\n self.record_once(from_blueprint)\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":664,"symbol":"from_blueprint","kind":"function","lang":"python","code":"def from_blueprint(state: BlueprintSetupState) -> None:\n state.app.errorhandler(code)(f)"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":673,"symbol":"app_url_value_preprocessor","kind":"function","lang":"python","code":"def app_url_value_preprocessor(\n self, f: T_url_value_preprocessor\n ) -> T_url_value_preprocessor:\n \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/blueprints.py","line":685,"symbol":"app_url_defaults","kind":"function","lang":"python","code":"def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n )\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":42,"symbol":"setupmethod","kind":"function","lang":"python","code":"def setupmethod(f: F) -> F:\n f_name = f.__name__\n\n def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any:\n self._check_setup_finished(f_name)\n return f(self, *args, **kwargs)\n\n return t.cast(F, update_wrapper(wrapper_func, f))"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":45,"symbol":"wrapper_func","kind":"function","lang":"python","code":"def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any:\n self._check_setup_finished(f_name)\n return f(self, *args, **kwargs)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":52,"symbol":"Scaffold","kind":"class","lang":"python","code":"class Scaffold:\n \"\"\"Common behavior shared between :class:`~flask.Flask` and\n :class:`~flask.blueprints.Blueprint`.\n\n :param import_name: The import name of the module where this object\n is defined. Usually :attr:`__name__` should be used.\n :param static_folder: Path to a folder of static files to serve.\n If this is set, a static route will be added.\n :param static_url_path: URL prefix for the static route.\n :param template_folder: Path to a folder containing template files.\n for rendering. If this is set, a Jinja loader will be added.\n :param root_path: The path that static, template, and resource files\n are relative to. Typically not set, it is discovered based on\n the ``import_name``.\n\n .. versionadded:: 2.0\n \"\"\"\n\n cli: Group\n name: str\n _static_folder: str | None = None\n _static_url_path: str | None = None\n\n def __init__(\n self,\n import_name: str,\n static_folder: str | os.PathLike[str] | None = None,\n static_url_path: str | None = None,\n template_folder: str | os.PathLike[str] | None = None,\n root_path: str | None = None,\n ):\n #: The name of the packa"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":75,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n import_name: str,\n static_folder: str | os.PathLike[str] | None = None,\n static_url_path: str | None = None,\n template_folder: str | os.PathLike[str] | None = None,\n root_path: str | None = None,\n ):\n #: The name of the package or module that this object belongs\n #: to. Do not change this once it is set by the constructor.\n self.import_name = import_name\n\n self.static_folder = static_folder\n self.static_url_path = static_url_path\n\n #: The path to the templates folder, relative to\n #: :attr:`root_path`, to add to the template loader. ``None`` if\n #: templates should not be added.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Absolute path to the package on the filesystem. Used to look\n #: up resources contained in the package.\n self.root_path = root_path\n\n #: A dictionary mapping endpoint names to view functions.\n #:\n #: To register a view function, use the :meth:`route` decorator.\n #:\n #: This data structure is int"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":217,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<{type(self).__name__} {self.name!r}>\""} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":220,"symbol":"_check_setup_finished","kind":"function","lang":"python","code":"def _check_setup_finished(self, f_name: str) -> None:\n raise NotImplementedError"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":224,"symbol":"static_folder","kind":"function","lang":"python","code":"def static_folder(self) -> str | None:\n \"\"\"The absolute path to the configured static folder. ``None``\n if no static folder is set.\n \"\"\"\n if self._static_folder is not None:\n return os.path.join(self.root_path, self._static_folder)\n else:\n return None"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":234,"symbol":"static_folder","kind":"function","lang":"python","code":"def static_folder(self, value: str | os.PathLike[str] | None) -> None:\n if value is not None:\n value = os.fspath(value).rstrip(r\"\\/\")\n\n self._static_folder = value"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":241,"symbol":"has_static_folder","kind":"function","lang":"python","code":"def has_static_folder(self) -> bool:\n \"\"\"``True`` if :attr:`static_folder` is set.\n\n .. versionadded:: 0.5\n \"\"\"\n return self.static_folder is not None"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":249,"symbol":"static_url_path","kind":"function","lang":"python","code":"def static_url_path(self) -> str | None:\n \"\"\"The URL prefix that the static route will be accessible from.\n\n If it was not configured during init, it is derived from\n :attr:`static_folder`.\n \"\"\"\n if self._static_url_path is not None:\n return self._static_url_path\n\n if self.static_folder is not None:\n basename = os.path.basename(self.static_folder)\n return f\"/{basename}\".rstrip(\"/\")\n\n return None"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":265,"symbol":"static_url_path","kind":"function","lang":"python","code":"def static_url_path(self, value: str | None) -> None:\n if value is not None:\n value = value.rstrip(\"/\")\n\n self._static_url_path = value"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":272,"symbol":"jinja_loader","kind":"function","lang":"python","code":"def jinja_loader(self) -> BaseLoader | None:\n \"\"\"The Jinja loader for this object's templates. By default this\n is a class :class:`jinja2.loaders.FileSystemLoader` to\n :attr:`template_folder` if it is set.\n\n .. versionadded:: 0.5\n \"\"\"\n if self.template_folder is not None:\n return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n else:\n return None"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":284,"symbol":"_method_route","kind":"function","lang":"python","code":"def _method_route(\n self,\n method: str,\n rule: str,\n options: dict[str, t.Any],\n ) -> t.Callable[[T_route], T_route]:\n if \"methods\" in options:\n raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n return self.route(rule, methods=[method], **options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":296,"symbol":"get","kind":"function","lang":"python","code":"def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"GET\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":304,"symbol":"query","kind":"function","lang":"python","code":"def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"QUERY\"]``.\n\n .. versionadded:: 3.2\n \"\"\"\n return self._method_route(\"QUERY\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":312,"symbol":"post","kind":"function","lang":"python","code":"def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"POST\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":320,"symbol":"put","kind":"function","lang":"python","code":"def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PUT\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":328,"symbol":"delete","kind":"function","lang":"python","code":"def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"DELETE\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":336,"symbol":"patch","kind":"function","lang":"python","code":"def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PATCH\", rule, options)"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":344,"symbol":"route","kind":"function","lang":"python","code":"def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Decorate a view function to register it with the given URL\n rule and options. Calls :meth:`add_url_rule`, which has more\n details about the implementation.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n ``OPTIONS`` are added automatically.\n\n :param rule: The URL rule string.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n\n def decorator(f: T_route) -> T_route:\n endpoint = options.pop(\"endpoint\", None)\n self.add_url_rule(rule, endpoint, f, **options)\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":368,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_route) -> T_route:\n endpoint = options.pop(\"endpoint\", None)\n self.add_url_rule(rule, endpoint, f, **options)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":376,"symbol":"add_url_rule","kind":"function","lang":"python","code":"def add_url_rule(\n self,\n rule: str,\n endpoint: str | None = None,\n view_func: ft.RouteCallable | None = None,\n provide_automatic_options: bool | None = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a rule for routing incoming requests and building\n URLs. The :meth:`route` decorator is a shortcut to call this\n with the ``view_func`` argument. These are equivalent:\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n ...\n\n .. code-block:: python\n\n def index():\n ...\n\n app.add_url_rule(\"/\", view_func=index)\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed. An error\n will be raised if a function has already been registered for the\n endpoint.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n always added automatically, and ``OPTIONS`` is added\n automatically by default.\n\n ``view_func`` does not necessarily need to be passed, but if the\n "} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":444,"symbol":"endpoint","kind":"function","lang":"python","code":"def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n \"\"\"Decorate a view function to register it for the given\n endpoint. Used if a rule is added without a ``view_func`` with\n :meth:`add_url_rule`.\n\n .. code-block:: python\n\n app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n @app.endpoint(\"example\")\n def example():\n ...\n\n :param endpoint: The endpoint name to associate with the view\n function.\n \"\"\"\n\n def decorator(f: F) -> F:\n self.view_functions[endpoint] = f\n return f\n\n return decorator"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":461,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: F) -> F:\n self.view_functions[endpoint] = f\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":468,"symbol":"before_request","kind":"function","lang":"python","code":"def before_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Register a function to run before each request.\n\n For example, this can be used to open a database connection, or\n to load the logged in user from the session.\n\n .. code-block:: python\n\n @app.before_request\n def load_user():\n if \"user_id\" in session:\n g.user = db.session.get(session[\"user_id\"])\n\n The function will be called without any arguments. If it returns\n a non-``None`` value, the value is handled as if it was the\n return value from the view, and further request handling is\n stopped.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes before every request. When used on a blueprint, this executes before\n every request that the blueprint handles. To register with a blueprint and\n execute before every request, use :meth:`.Blueprint.before_app_request`.\n \"\"\"\n self.before_request_funcs.setdefault(None, []).append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":495,"symbol":"after_request","kind":"function","lang":"python","code":"def after_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Register a function to run after each request to this object.\n\n The function is called with the response object, and must return\n a response object. This allows the functions to modify or\n replace the response before it is sent.\n\n If a function raises an exception, any remaining\n ``after_request`` functions will not be called. Therefore, this\n should not be used for actions that must execute, such as to\n close resources. Use :meth:`teardown_request` for that.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n every request that the blueprint handles. To register with a blueprint and\n execute after every request, use :meth:`.Blueprint.after_app_request`.\n \"\"\"\n self.after_request_funcs.setdefault(None, []).append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":516,"symbol":"teardown_request","kind":"function","lang":"python","code":"def teardown_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Register a function to be called when the request context is\n popped. Typically, this happens at the end of each request, but\n contexts may be pushed manually during testing.\n\n .. code-block:: python\n\n with app.test_request_context():\n ...\n\n When the ``with`` block exits (or ``ctx.pop()`` is called), the\n teardown functions are called just before the request context is\n made inactive.\n\n When a teardown function was called because of an unhandled\n exception it will be passed an error object. If an\n :meth:`errorhandler` is registered, it will handle the exception\n and the teardown will not receive it.\n\n Teardown functions must avoid raising exceptions. If they\n execute code that might fail they must surround that code with a\n ``try``/``except`` block and log any errors.\n\n The return values of teardown functions are ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n "} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":550,"symbol":"context_processor","kind":"function","lang":"python","code":"def context_processor(\n self,\n f: T_template_context_processor,\n ) -> T_template_context_processor:\n \"\"\"Registers a template context processor function. These functions run before\n rendering a template. The keys of the returned dict are added as variables\n available in the template.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every rendered template. When used on a blueprint, this is called\n for templates rendered from the blueprint's views. To register with a blueprint\n and affect every template, use :meth:`.Blueprint.app_context_processor`.\n \"\"\"\n self.template_context_processors[None].append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":567,"symbol":"url_value_preprocessor","kind":"function","lang":"python","code":"def url_value_preprocessor(\n self,\n f: T_url_value_preprocessor,\n ) -> T_url_value_preprocessor:\n \"\"\"Register a URL value preprocessor function for all view\n functions in the application. These functions will be called before the\n :meth:`before_request` functions.\n\n The function can modify the values captured from the matched url before\n they are passed to the view. For example, this can be used to pop a\n common language code value and place it in ``g`` rather than pass it to\n every view.\n\n The function is passed the endpoint name and values dict. The return\n value is ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n \"\"\"\n self.url_value_preprocessors[None].append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":592,"symbol":"url_defaults","kind":"function","lang":"python","code":"def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Callback function for URL defaults for all view functions of the\n application. It's called with the endpoint and values and should\n update the values passed in place.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_defaults`.\n \"\"\"\n self.url_default_functions[None].append(f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":606,"symbol":"errorhandler","kind":"function","lang":"python","code":"def errorhandler(\n self, code_or_exception: type[Exception] | int\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Register a function to handle errors by code or exception class.\n\n A decorator that is used to register a function given an\n error code. Example::\n\n @app.errorhandler(404)\n def page_not_found(error):\n return 'This page does not exist', 404\n\n You can also register handlers for arbitrary exceptions::\n\n @app.errorhandler(DatabaseError)\n def special_exception_handler(error):\n return 'Database connection failed', 500\n\n This is available on both app and blueprint objects. When used on an app, this\n can handle errors from every request. When used on a blueprint, this can handle\n errors from requests that the blueprint handles. To register with a blueprint\n and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n .. versionadded:: 0.7\n Use :meth:`register_error_handler` instead of modifying\n :attr:`error_handler_spec` directly, for application wide error\n handlers.\n\n .. v"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":643,"symbol":"decorator","kind":"function","lang":"python","code":"def decorator(f: T_error_handler) -> T_error_handler:\n self.register_error_handler(code_or_exception, f)\n return f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":650,"symbol":"register_error_handler","kind":"function","lang":"python","code":"def register_error_handler(\n self,\n code_or_exception: type[Exception] | int,\n f: ft.ErrorHandlerCallable,\n ) -> None:\n \"\"\"Alternative error attach function to the :meth:`errorhandler`\n decorator that is more straightforward to use for non decorator\n usage.\n\n .. versionadded:: 0.7\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(code_or_exception)\n self.error_handler_spec[None][code][exc_class] = f"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":665,"symbol":"_get_exc_class_and_code","kind":"function","lang":"python","code":"def _get_exc_class_and_code(\n exc_class_or_code: type[Exception] | int,\n ) -> tuple[type[Exception], int | None]:\n \"\"\"Get the exception class being handled. For HTTP status codes\n or ``HTTPException`` subclasses, return both the exception and\n status code.\n\n :param exc_class_or_code: Any exception class, or an HTTP status\n code as an integer.\n \"\"\"\n exc_class: type[Exception]\n\n if isinstance(exc_class_or_code, int):\n try:\n exc_class = default_exceptions[exc_class_or_code]\n except KeyError:\n raise ValueError(\n f\"'{exc_class_or_code}' is not a recognized HTTP\"\n \" error code. Use a subclass of HTTPException with\"\n \" that code instead.\"\n ) from None\n else:\n exc_class = exc_class_or_code\n\n if isinstance(exc_class, Exception):\n raise TypeError(\n f\"{exc_class!r} is an instance, not a class. Handlers\"\n \" can only be registered for Exception classes or HTTP\"\n \" error codes.\"\n )\n\n if not issubclass(exc_cl"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":709,"symbol":"_endpoint_from_view_func","kind":"function","lang":"python","code":"def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str:\n \"\"\"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n \"\"\"\n assert view_func is not None, \"expected view func if endpoint is not provided.\"\n return view_func.__name__"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":717,"symbol":"_find_package_path","kind":"function","lang":"python","code":"def _find_package_path(import_name: str) -> str:\n \"\"\"Find the path that contains the package or module.\"\"\"\n root_mod_name, _, _ = import_name.partition(\".\")\n\n try:\n root_spec = importlib.util.find_spec(root_mod_name)\n\n if root_spec is None:\n raise ValueError(\"not found\")\n except (ImportError, ValueError):\n # ImportError: the machinery told us it does not exist\n # ValueError:\n # - the module name was invalid\n # - the module name is __main__\n # - we raised `ValueError` due to `root_spec` being `None`\n return os.getcwd()\n\n if root_spec.submodule_search_locations:\n if root_spec.origin is None or root_spec.origin == \"namespace\":\n # namespace package\n package_spec = importlib.util.find_spec(import_name)\n\n if package_spec is not None and package_spec.submodule_search_locations:\n # Pick the path in the namespace that contains the submodule.\n package_path = pathlib.Path(\n os.path.commonpath(package_spec.submodule_search_locations)\n )\n search_location = next(\n locati"} {"repo":"flask","file":"src/flask/sansio/scaffold.py","line":762,"symbol":"find_package","kind":"function","lang":"python","code":"def find_package(import_name: str) -> tuple[str | None, str]:\n \"\"\"Find the prefix that a package is installed under, and the path\n that it would be imported from.\n\n The prefix is the directory containing the standard directory\n hierarchy (lib, bin, etc.). If the package is not installed to the\n system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),\n ``None`` is returned.\n\n The path is the entry in :attr:`sys.path` that contains the package\n for import. If the package is not installed, it's assumed that the\n package was imported from the current working directory.\n \"\"\"\n package_path = _find_package_path(import_name)\n py_prefix = os.path.abspath(sys.prefix)\n\n # installed to the system\n if pathlib.PurePath(package_path).is_relative_to(py_prefix):\n return py_prefix, package_path\n\n site_parent, site_folder = os.path.split(package_path)\n\n # installed to a virtualenv\n if site_folder.lower() == \"site-packages\":\n parent, folder = os.path.split(site_parent)\n\n # Windows (prefix/lib/site-packages)\n if folder.lower() == \"lib\":\n return parent, package_path\n\n # Unix (prefix/lib/pythonX.Y/sit"} {"repo":"flask","file":"src/flask/sessions.py","line":24,"symbol":"SessionMixin","kind":"class","lang":"python","code":"class SessionMixin(MutableMapping[str, t.Any]):\n \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n @property\n def permanent(self) -> bool:\n \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n return self.get(\"_permanent\", False) # type: ignore[no-any-return]\n\n @permanent.setter\n def permanent(self, value: bool) -> None:\n self[\"_permanent\"] = bool(value)\n\n #: Some implementations can detect whether a session is newly\n #: created, but that is not guaranteed. Use with caution. The mixin\n # default is hard-coded ``False``.\n new = False\n\n #: Some implementations can detect changes to the session and set\n #: this when that happens. The mixin default is hard coded to\n #: ``True``.\n modified = True\n\n accessed = False\n \"\"\"Indicates if the session was accessed, even if it was not modified. This\n is set when the session object is accessed through the request context,\n including the global :data:`.session` proxy. A ``Vary: cookie`` header will\n be added if this is ``True``.\n\n .. versionchanged:: 3.1.3\n This is tracked by the request context.\n \"\"\""} {"repo":"flask","file":"src/flask/sessions.py","line":28,"symbol":"permanent","kind":"function","lang":"python","code":"def permanent(self) -> bool:\n \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n return self.get(\"_permanent\", False) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":33,"symbol":"permanent","kind":"function","lang":"python","code":"def permanent(self, value: bool) -> None:\n self[\"_permanent\"] = bool(value)"} {"repo":"flask","file":"src/flask/sessions.py","line":57,"symbol":"SecureCookieSession","kind":"class","lang":"python","code":"class SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):\n \"\"\"Base class for sessions based on signed cookies.\n\n This session backend will set the :attr:`modified` and\n :attr:`accessed` attributes. It cannot reliably track whether a\n session is new (vs. empty), so :attr:`new` remains hard coded to\n ``False``.\n \"\"\"\n\n #: When data is changed, this is set to ``True``. Only the session\n #: dictionary itself is tracked; if the session contains mutable\n #: data (for example a nested dict) then this must be set to\n #: ``True`` manually when modifying that data. The session cookie\n #: will only be written to the response if this is ``True``.\n modified = False\n\n def __init__(\n self,\n initial: c.Mapping[str, t.Any] | None = None,\n ) -> None:\n def on_update(self: te.Self) -> None:\n self.modified = True\n\n super().__init__(initial, on_update)"} {"repo":"flask","file":"src/flask/sessions.py","line":73,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n initial: c.Mapping[str, t.Any] | None = None,\n ) -> None:\n def on_update(self: te.Self) -> None:\n self.modified = True\n\n super().__init__(initial, on_update)"} {"repo":"flask","file":"src/flask/sessions.py","line":77,"symbol":"on_update","kind":"function","lang":"python","code":"def on_update(self: te.Self) -> None:\n self.modified = True"} {"repo":"flask","file":"src/flask/sessions.py","line":83,"symbol":"NullSession","kind":"class","lang":"python","code":"class NullSession(SecureCookieSession):\n \"\"\"Class used to generate nicer error messages if sessions are not\n available. Will still allow read-only access to the empty session\n but fail on setting.\n \"\"\"\n\n def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n raise RuntimeError(\n \"The session is unavailable because no secret \"\n \"key was set. Set the secret_key on the \"\n \"application to something unique and secret.\"\n )\n\n __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail\n del _fail"} {"repo":"flask","file":"src/flask/sessions.py","line":89,"symbol":"_fail","kind":"function","lang":"python","code":"def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:\n raise RuntimeError(\n \"The session is unavailable because no secret \"\n \"key was set. Set the secret_key on the \"\n \"application to something unique and secret.\"\n )"} {"repo":"flask","file":"src/flask/sessions.py","line":100,"symbol":"SessionInterface","kind":"class","lang":"python","code":"class SessionInterface:\n \"\"\"The basic interface you have to implement in order to replace the\n default session interface which uses werkzeug's securecookie\n implementation. The only methods you have to implement are\n :meth:`open_session` and :meth:`save_session`, the others have\n useful defaults which you don't need to change.\n\n The session object returned by the :meth:`open_session` method has to\n provide a dictionary like interface plus the properties and methods\n from the :class:`SessionMixin`. We recommend just subclassing a dict\n and adding that mixin::\n\n class Session(dict, SessionMixin):\n pass\n\n If :meth:`open_session` returns ``None`` Flask will call into\n :meth:`make_null_session` to create a session that acts as replacement\n if the session support cannot work because some requirement is not\n fulfilled. The default :class:`NullSession` class that is created\n will complain that the secret key was not set.\n\n To replace the session interface on an application all you have to do\n is to assign :attr:`flask.Flask.session_interface`::\n\n app = Flask(__name__)\n app.session_interface = MySessionInterf"} {"repo":"flask","file":"src/flask/sessions.py","line":150,"symbol":"make_null_session","kind":"function","lang":"python","code":"def make_null_session(self, app: Flask) -> NullSession:\n \"\"\"Creates a null session which acts as a replacement object if the\n real session support could not be loaded due to a configuration\n error. This mainly aids the user experience because the job of the\n null session is to still support lookup without complaining but\n modifications are answered with a helpful error message of what\n failed.\n\n This creates an instance of :attr:`null_session_class` by default.\n \"\"\"\n return self.null_session_class()"} {"repo":"flask","file":"src/flask/sessions.py","line":162,"symbol":"is_null_session","kind":"function","lang":"python","code":"def is_null_session(self, obj: object) -> bool:\n \"\"\"Checks if a given object is a null session. Null sessions are\n not asked to be saved.\n\n This checks if the object is an instance of :attr:`null_session_class`\n by default.\n \"\"\"\n return isinstance(obj, self.null_session_class)"} {"repo":"flask","file":"src/flask/sessions.py","line":171,"symbol":"get_cookie_name","kind":"function","lang":"python","code":"def get_cookie_name(self, app: Flask) -> str:\n \"\"\"The name of the session cookie. Uses``app.config[\"SESSION_COOKIE_NAME\"]``.\"\"\"\n return app.config[\"SESSION_COOKIE_NAME\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":175,"symbol":"get_cookie_domain","kind":"function","lang":"python","code":"def get_cookie_domain(self, app: Flask) -> str | None:\n \"\"\"The value of the ``Domain`` parameter on the session cookie. If not set,\n browsers will only send the cookie to the exact domain it was set from.\n Otherwise, they will send it to any subdomain of the given value as well.\n\n Uses the :data:`SESSION_COOKIE_DOMAIN` config.\n\n .. versionchanged:: 2.3\n Not set by default, does not fall back to ``SERVER_NAME``.\n \"\"\"\n return app.config[\"SESSION_COOKIE_DOMAIN\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":187,"symbol":"get_cookie_path","kind":"function","lang":"python","code":"def get_cookie_path(self, app: Flask) -> str:\n \"\"\"Returns the path for which the cookie should be valid. The\n default implementation uses the value from the ``SESSION_COOKIE_PATH``\n config var if it's set, and falls back to ``APPLICATION_ROOT`` or\n uses ``/`` if it's ``None``.\n \"\"\"\n return app.config[\"SESSION_COOKIE_PATH\"] or app.config[\"APPLICATION_ROOT\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":195,"symbol":"get_cookie_httponly","kind":"function","lang":"python","code":"def get_cookie_httponly(self, app: Flask) -> bool:\n \"\"\"Returns True if the session cookie should be httponly. This\n currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``\n config var.\n \"\"\"\n return app.config[\"SESSION_COOKIE_HTTPONLY\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":202,"symbol":"get_cookie_secure","kind":"function","lang":"python","code":"def get_cookie_secure(self, app: Flask) -> bool:\n \"\"\"Returns True if the cookie should be secure. This currently\n just returns the value of the ``SESSION_COOKIE_SECURE`` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SECURE\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":208,"symbol":"get_cookie_samesite","kind":"function","lang":"python","code":"def get_cookie_samesite(self, app: Flask) -> str | None:\n \"\"\"Return ``'Strict'`` or ``'Lax'`` if the cookie should use the\n ``SameSite`` attribute. This currently just returns the value of\n the :data:`SESSION_COOKIE_SAMESITE` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SAMESITE\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":215,"symbol":"get_cookie_partitioned","kind":"function","lang":"python","code":"def get_cookie_partitioned(self, app: Flask) -> bool:\n \"\"\"Returns True if the cookie should be partitioned. By default, uses\n the value of :data:`SESSION_COOKIE_PARTITIONED`.\n\n .. versionadded:: 3.1\n \"\"\"\n return app.config[\"SESSION_COOKIE_PARTITIONED\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/sessions.py","line":223,"symbol":"get_expiration_time","kind":"function","lang":"python","code":"def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None:\n \"\"\"A helper method that returns an expiration date for the session\n or ``None`` if the session is linked to the browser session. The\n default implementation returns now + the permanent session\n lifetime configured on the application.\n \"\"\"\n if session.permanent:\n return datetime.now(timezone.utc) + app.permanent_session_lifetime\n return None"} {"repo":"flask","file":"src/flask/sessions.py","line":233,"symbol":"should_set_cookie","kind":"function","lang":"python","code":"def should_set_cookie(self, app: Flask, session: SessionMixin) -> bool:\n \"\"\"Used by session backends to determine if a ``Set-Cookie`` header\n should be set for this session cookie for this response. If the session\n has been modified, the cookie is set. If the session is permanent and\n the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is\n always set.\n\n This check is usually skipped if the session was deleted.\n\n .. versionadded:: 0.11\n \"\"\"\n\n return session.modified or (\n session.permanent and app.config[\"SESSION_REFRESH_EACH_REQUEST\"]\n )"} {"repo":"flask","file":"src/flask/sessions.py","line":249,"symbol":"open_session","kind":"function","lang":"python","code":"def open_session(self, app: Flask, request: Request) -> SessionMixin | None:\n \"\"\"This is called at the beginning of each request, after\n pushing the request context, before matching the URL.\n\n This must return an object which implements a dictionary-like\n interface as well as the :class:`SessionMixin` interface.\n\n This will return ``None`` to indicate that loading failed in\n some way that is not immediately an error. The request\n context will fall back to using :meth:`make_null_session`\n in this case.\n \"\"\"\n raise NotImplementedError()"} {"repo":"flask","file":"src/flask/sessions.py","line":263,"symbol":"save_session","kind":"function","lang":"python","code":"def save_session(\n self, app: Flask, session: SessionMixin, response: Response\n ) -> None:\n \"\"\"This is called at the end of each request, after generating\n a response, before removing the request context. It is skipped\n if :meth:`is_null_session` returns ``True``.\n \"\"\"\n raise NotImplementedError()"} {"repo":"flask","file":"src/flask/sessions.py","line":276,"symbol":"_lazy_sha1","kind":"function","lang":"python","code":"def _lazy_sha1(string: bytes = b\"\") -> t.Any:\n \"\"\"Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include\n SHA-1, in which case the import and use as a default would fail before the\n developer can configure something else.\n \"\"\"\n return hashlib.sha1(string)"} {"repo":"flask","file":"src/flask/sessions.py","line":284,"symbol":"SecureCookieSessionInterface","kind":"class","lang":"python","code":"class SecureCookieSessionInterface(SessionInterface):\n \"\"\"The default session interface that stores sessions in signed cookies\n through the :mod:`itsdangerous` module.\n \"\"\"\n\n #: the salt that should be applied on top of the secret key for the\n #: signing of cookie based sessions.\n salt = \"cookie-session\"\n #: the hash function to use for the signature. The default is sha1\n digest_method = staticmethod(_lazy_sha1)\n #: the name of the itsdangerous supported key derivation. The default\n #: is hmac.\n key_derivation = \"hmac\"\n #: A python serializer for the payload. The default is a compact\n #: JSON derived serializer with support for some extra Python types\n #: such as datetime objects or tuples.\n serializer = session_json_serializer\n session_class = SecureCookieSession\n\n def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None:\n if not app.secret_key:\n return None\n\n keys: list[str | bytes] = []\n\n if fallbacks := app.config[\"SECRET_KEY_FALLBACKS\"]:\n keys.extend(fallbacks)\n\n keys.append(app.secret_key) # itsdangerous expects current key at top\n return URLSaf"} {"repo":"flask","file":"src/flask/sessions.py","line":303,"symbol":"get_signing_serializer","kind":"function","lang":"python","code":"def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None:\n if not app.secret_key:\n return None\n\n keys: list[str | bytes] = []\n\n if fallbacks := app.config[\"SECRET_KEY_FALLBACKS\"]:\n keys.extend(fallbacks)\n\n keys.append(app.secret_key) # itsdangerous expects current key at top\n return URLSafeTimedSerializer(\n keys, # type: ignore[arg-type]\n salt=self.salt,\n serializer=self.serializer,\n signer_kwargs={\n \"key_derivation\": self.key_derivation,\n \"digest_method\": self.digest_method,\n },\n )"} {"repo":"flask","file":"src/flask/sessions.py","line":323,"symbol":"open_session","kind":"function","lang":"python","code":"def open_session(self, app: Flask, request: Request) -> SecureCookieSession | None:\n s = self.get_signing_serializer(app)\n if s is None:\n return None\n val = request.cookies.get(self.get_cookie_name(app))\n if not val:\n return self.session_class()\n max_age = int(app.permanent_session_lifetime.total_seconds())\n try:\n data = s.loads(val, max_age=max_age)\n return self.session_class(data)\n except BadSignature:\n return self.session_class()"} {"repo":"flask","file":"src/flask/sessions.py","line":337,"symbol":"save_session","kind":"function","lang":"python","code":"def save_session(\n self, app: Flask, session: SessionMixin, response: Response\n ) -> None:\n name = self.get_cookie_name(app)\n domain = self.get_cookie_domain(app)\n path = self.get_cookie_path(app)\n secure = self.get_cookie_secure(app)\n partitioned = self.get_cookie_partitioned(app)\n samesite = self.get_cookie_samesite(app)\n httponly = self.get_cookie_httponly(app)\n\n # Add a \"Vary: Cookie\" header if the session was accessed at all.\n if session.accessed:\n response.vary.add(\"Cookie\")\n\n # If the session is modified to be empty, remove the cookie.\n # If the session is empty, return without setting the cookie.\n if not session:\n if session.modified:\n response.delete_cookie(\n name,\n domain=domain,\n path=path,\n secure=secure,\n partitioned=partitioned,\n samesite=samesite,\n httponly=httponly,\n )\n response.vary.add(\"Cookie\")\n\n return\n\n if not self.should_set_cookie(app, session):\n "} {"repo":"flask","file":"src/flask/templating.py","line":21,"symbol":"_default_template_ctx_processor","kind":"function","lang":"python","code":"def _default_template_ctx_processor() -> dict[str, t.Any]:\n \"\"\"Default template context processor. Replaces the ``request`` and ``g``\n proxies with their concrete objects for faster access.\n \"\"\"\n ctx = app_ctx._get_current_object()\n rv: dict[str, t.Any] = {\"g\": ctx.g}\n\n if ctx.has_request:\n rv[\"request\"] = ctx.request\n # The session proxy cannot be replaced, accessing it gets\n # RequestContext.session, which sets session.accessed.\n\n return rv"} {"repo":"flask","file":"src/flask/templating.py","line":36,"symbol":"Environment","kind":"class","lang":"python","code":"class Environment(BaseEnvironment):\n \"\"\"Works like a regular Jinja environment but has some additional\n knowledge of how Flask's blueprint works so that it can prepend the\n name of the blueprint to referenced templates if necessary.\n \"\"\"\n\n def __init__(self, app: App, **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app"} {"repo":"flask","file":"src/flask/templating.py","line":42,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, app: App, **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app"} {"repo":"flask","file":"src/flask/templating.py","line":49,"symbol":"DispatchingJinjaLoader","kind":"class","lang":"python","code":"class DispatchingJinjaLoader(BaseLoader):\n \"\"\"A loader that looks for templates in the application and all\n the blueprint folders.\n \"\"\"\n\n def __init__(self, app: App) -> None:\n self.app = app\n\n def get_source(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n return self._get_source_explained(environment, template)\n return self._get_source_fast(environment, template)\n\n def _get_source_explained(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n attempts = []\n rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n for srcobj, loader in self._iter_loaders(template):\n try:\n rv = loader.get_source(environment, template)\n if trv is None:\n trv = rv\n except TemplateNotFound:\n rv = None\n attempts.append((loader, srcobj, rv))\n\n from .debughel"} {"repo":"flask","file":"src/flask/templating.py","line":54,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, app: App) -> None:\n self.app = app"} {"repo":"flask","file":"src/flask/templating.py","line":57,"symbol":"get_source","kind":"function","lang":"python","code":"def get_source(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n return self._get_source_explained(environment, template)\n return self._get_source_fast(environment, template)"} {"repo":"flask","file":"src/flask/templating.py","line":64,"symbol":"_get_source_explained","kind":"function","lang":"python","code":"def _get_source_explained(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n attempts = []\n rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n for srcobj, loader in self._iter_loaders(template):\n try:\n rv = loader.get_source(environment, template)\n if trv is None:\n trv = rv\n except TemplateNotFound:\n rv = None\n attempts.append((loader, srcobj, rv))\n\n from .debughelpers import explain_template_loading_attempts\n\n explain_template_loading_attempts(self.app, template, attempts)\n\n if trv is not None:\n return trv\n raise TemplateNotFound(template)"} {"repo":"flask","file":"src/flask/templating.py","line":88,"symbol":"_get_source_fast","kind":"function","lang":"python","code":"def _get_source_fast(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n for _srcobj, loader in self._iter_loaders(template):\n try:\n return loader.get_source(environment, template)\n except TemplateNotFound:\n continue\n raise TemplateNotFound(template)"} {"repo":"flask","file":"src/flask/templating.py","line":98,"symbol":"_iter_loaders","kind":"function","lang":"python","code":"def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n loader = self.app.jinja_loader\n if loader is not None:\n yield self.app, loader\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n yield blueprint, loader"} {"repo":"flask","file":"src/flask/templating.py","line":108,"symbol":"list_templates","kind":"function","lang":"python","code":"def list_templates(self) -> list[str]:\n result = set()\n loader = self.app.jinja_loader\n if loader is not None:\n result.update(loader.list_templates())\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n for template in loader.list_templates():\n result.add(template)\n\n return list(result)"} {"repo":"flask","file":"src/flask/templating.py","line":123,"symbol":"_render","kind":"function","lang":"python","code":"def _render(ctx: AppContext, template: Template, context: dict[str, t.Any]) -> str:\n app = ctx.app\n app.update_template_context(ctx, context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n rv = template.render(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n return rv"} {"repo":"flask","file":"src/flask/templating.py","line":136,"symbol":"render_template","kind":"function","lang":"python","code":"def render_template(\n template_name_or_list: str | Template | list[str | Template],\n **context: t.Any,\n) -> str:\n \"\"\"Render a template by name with the given context.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)\n return _render(ctx, template, context)"} {"repo":"flask","file":"src/flask/templating.py","line":151,"symbol":"render_template_string","kind":"function","lang":"python","code":"def render_template_string(source: str, **context: t.Any) -> str:\n \"\"\"Render a template from the given source string with the given\n context.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.from_string(source)\n return _render(ctx, template, context)"} {"repo":"flask","file":"src/flask/templating.py","line":163,"symbol":"_stream","kind":"function","lang":"python","code":"def _stream(\n ctx: AppContext, template: Template, context: dict[str, t.Any]\n) -> t.Iterator[str]:\n app = ctx.app\n app.update_template_context(ctx, context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n def generate() -> t.Iterator[str]:\n yield from template.generate(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n return stream_with_context(generate())"} {"repo":"flask","file":"src/flask/templating.py","line":172,"symbol":"generate","kind":"function","lang":"python","code":"def generate() -> t.Iterator[str]:\n yield from template.generate(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )"} {"repo":"flask","file":"src/flask/templating.py","line":181,"symbol":"stream_template","kind":"function","lang":"python","code":"def stream_template(\n template_name_or_list: str | Template | list[str | Template],\n **context: t.Any,\n) -> t.Iterator[str]:\n \"\"\"Render a template by name with the given context as a stream.\n This returns an iterator of strings, which can be used as a\n streaming response from a view.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)\n return _stream(ctx, template, context)"} {"repo":"flask","file":"src/flask/templating.py","line":200,"symbol":"stream_template_string","kind":"function","lang":"python","code":"def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:\n \"\"\"Render a template from the given source string with the given\n context as a stream. This returns an iterator of strings, which can\n be used as a streaming response from a view.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.from_string(source)\n return _stream(ctx, template, context)"} {"repo":"flask","file":"src/flask/testing.py","line":27,"symbol":"EnvironBuilder","kind":"class","lang":"python","code":"class EnvironBuilder(werkzeug.test.EnvironBuilder):\n \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n application.\n\n :param app: The Flask application to configure the environment from.\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n\n def __init__(\n self,\n app: Flask,\n path: str = \"/\",\n base_url: str | None = None,\n subdomain: str | None = None,\n url_scheme: str | N"} {"repo":"flask","file":"src/flask/testing.py","line":49,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n app: Flask,\n path: str = \"/\",\n base_url: str | None = None,\n subdomain: str | None = None,\n url_scheme: str | None = None,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> None:\n assert not (base_url or subdomain or url_scheme) or (\n base_url is not None\n ) != bool(subdomain or url_scheme), (\n 'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n )\n\n if base_url is None:\n http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n app_root = app.config[\"APPLICATION_ROOT\"]\n\n if subdomain:\n http_host = f\"{subdomain}.{http_host}\"\n\n if url_scheme is None:\n url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n url = urlsplit(path)\n base_url = (\n f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n f\"/{app_root.lstrip('/')}\"\n )\n path = url.path\n\n if url.query:\n path = f\"{path}?{url.query}\"\n\n self.app = app\n super().__init__(path, base_url, *args, **kwargs)"} {"repo":"flask","file":"src/flask/testing.py","line":88,"symbol":"json_dumps","kind":"function","lang":"python","code":"def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n The serialization will be configured according to the config associated\n with this EnvironBuilder's ``app``.\n \"\"\"\n return self.app.json.dumps(obj, **kwargs)"} {"repo":"flask","file":"src/flask/testing.py","line":100,"symbol":"_get_werkzeug_version","kind":"function","lang":"python","code":"def _get_werkzeug_version() -> str:\n global _werkzeug_version\n\n if not _werkzeug_version:\n _werkzeug_version = importlib.metadata.version(\"werkzeug\")\n\n return _werkzeug_version"} {"repo":"flask","file":"src/flask/testing.py","line":109,"symbol":"FlaskClient","kind":"class","lang":"python","code":"class FlaskClient(Client):\n \"\"\"Works like a regular Werkzeug test client, with additional behavior for\n Flask. Can defer the cleanup of the request context until the end of a\n ``with`` block. For general information about how to use this class refer to\n :class:`werkzeug.test.Client`.\n\n .. versionchanged:: 0.12\n `app.test_client()` includes preset default environment, which can be\n set after instantiation of the `app.test_client()` object in\n `client.environ_base`.\n\n Basic usage is outlined in the :doc:`/testing` chapter.\n \"\"\"\n\n application: Flask\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.preserve_context = False\n self._new_contexts: list[t.ContextManager[t.Any]] = []\n self._context_stack = ExitStack()\n self.environ_base = {\n \"REMOTE_ADDR\": \"127.0.0.1\",\n \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n }\n\n @contextmanager\n def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Iterator[SessionMixin]:\n \"\"\"When used in combination with a ``with`` statement this opens a\n "} {"repo":"flask","file":"src/flask/testing.py","line":125,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.preserve_context = False\n self._new_contexts: list[t.ContextManager[t.Any]] = []\n self._context_stack = ExitStack()\n self.environ_base = {\n \"REMOTE_ADDR\": \"127.0.0.1\",\n \"HTTP_USER_AGENT\": f\"Werkzeug/{_get_werkzeug_version()}\",\n }"} {"repo":"flask","file":"src/flask/testing.py","line":136,"symbol":"session_transaction","kind":"function","lang":"python","code":"def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Iterator[SessionMixin]:\n \"\"\"When used in combination with a ``with`` statement this opens a\n session transaction. This can be used to modify the session that\n the test client uses. Once the ``with`` block is left the session is\n stored back.\n\n ::\n\n with client.session_transaction() as session:\n session['value'] = 42\n\n Internally this is implemented by going through a temporary test\n request context and since session handling could depend on\n request variables this function accepts the same arguments as\n :meth:`~flask.Flask.test_request_context` which are directly\n passed through.\n \"\"\"\n if self._cookies is None:\n raise TypeError(\n \"Cookies are disabled. Create a client with 'use_cookies=True'.\"\n )\n\n app = self.application\n ctx = app.test_request_context(*args, **kwargs)\n self._add_cookies_to_wsgi(ctx.request.environ)\n\n with ctx:\n sess = app.session_interface.open_session(app, ctx.request)\n\n if sess is None:\n "} {"repo":"flask","file":"src/flask/testing.py","line":185,"symbol":"_copy_environ","kind":"function","lang":"python","code":"def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:\n out = {**self.environ_base, **other}\n\n if self.preserve_context:\n out[\"werkzeug.debug.preserve_context\"] = self._new_contexts.append\n\n return out"} {"repo":"flask","file":"src/flask/testing.py","line":193,"symbol":"_request_from_builder_args","kind":"function","lang":"python","code":"def _request_from_builder_args(\n self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]\n ) -> BaseRequest:\n kwargs[\"environ_base\"] = self._copy_environ(kwargs.get(\"environ_base\", {}))\n builder = EnvironBuilder(self.application, *args, **kwargs)\n\n try:\n return builder.get_request()\n finally:\n builder.close()"} {"repo":"flask","file":"src/flask/testing.py","line":204,"symbol":"open","kind":"function","lang":"python","code":"def open(\n self,\n *args: t.Any,\n buffered: bool = False,\n follow_redirects: bool = False,\n **kwargs: t.Any,\n ) -> TestResponse:\n if args and isinstance(\n args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)\n ):\n if isinstance(args[0], werkzeug.test.EnvironBuilder):\n builder = copy(args[0])\n builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type]\n request = builder.get_request()\n elif isinstance(args[0], dict):\n request = EnvironBuilder.from_environ(\n args[0], app=self.application, environ_base=self._copy_environ({})\n ).get_request()\n else:\n # isinstance(args[0], BaseRequest)\n request = copy(args[0])\n request.environ = self._copy_environ(request.environ)\n else:\n # request is None\n request = self._request_from_builder_args(args, kwargs)\n\n # Pop any previously preserved contexts. This prevents contexts\n # from being preserved across redirects or multiple requests\n "} {"repo":"flask","file":"src/flask/testing.py","line":249,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self) -> FlaskClient:\n if self.preserve_context:\n raise RuntimeError(\"Cannot nest client invocations\")\n self.preserve_context = True\n return self"} {"repo":"flask","file":"src/flask/testing.py","line":255,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(\n self,\n exc_type: type | None,\n exc_value: BaseException | None,\n tb: TracebackType | None,\n ) -> None:\n self.preserve_context = False\n self._context_stack.close()"} {"repo":"flask","file":"src/flask/testing.py","line":265,"symbol":"FlaskCliRunner","kind":"class","lang":"python","code":"class FlaskCliRunner(CliRunner):\n \"\"\"A :class:`~click.testing.CliRunner` for testing a Flask app's\n CLI commands. Typically created using\n :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.\n \"\"\"\n\n def __init__(self, app: Flask, **kwargs: t.Any) -> None:\n self.app = app\n super().__init__(**kwargs)\n\n def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> Result:\n \"\"\"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n \"\"\"\n if cli is None:\n cli = self.app.cli\n\n if \"obj\" not in kwargs:\n kwargs[\"obj\"] = S"} {"repo":"flask","file":"src/flask/testing.py","line":271,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, app: Flask, **kwargs: t.Any) -> None:\n self.app = app\n super().__init__(**kwargs)"} {"repo":"flask","file":"src/flask/testing.py","line":275,"symbol":"invoke","kind":"function","lang":"python","code":"def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> Result:\n \"\"\"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n \"\"\"\n if cli is None:\n cli = self.app.cli\n\n if \"obj\" not in kwargs:\n kwargs[\"obj\"] = ScriptInfo(create_app=lambda: self.app)\n\n return super().invoke(cli, args, **kwargs)"} {"repo":"flask","file":"src/flask/views.py","line":16,"symbol":"View","kind":"class","lang":"python","code":"class View:\n \"\"\"Subclass this class and override :meth:`dispatch_request` to\n create a generic class-based view. Call :meth:`as_view` to create a\n view function that creates an instance of the class with the given\n arguments and calls its ``dispatch_request`` method with any URL\n variables.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class Hello(View):\n init_every_request = False\n\n def dispatch_request(self, name):\n return f\"Hello, {name}!\"\n\n app.add_url_rule(\n \"/hello/\", view_func=Hello.as_view(\"hello\")\n )\n\n Set :attr:`methods` on the class to change what methods the view\n accepts.\n\n Set :attr:`decorators` on the class to apply a list of decorators to\n the generated view function. Decorators applied to the class itself\n will not be applied to the generated view function!\n\n Set :attr:`init_every_request` to ``False`` for efficiency, unless\n you need to store request-global data on ``self``.\n \"\"\"\n\n #: The methods this view is registered for. Uses the same default\n #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n #: ``add_url_ru"} {"repo":"flask","file":"src/flask/views.py","line":78,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self) -> ft.ResponseReturnValue:\n \"\"\"The actual view function behavior. Subclasses must override\n this and return a valid response. Any variables from the URL\n rule are passed as keyword arguments.\n \"\"\"\n raise NotImplementedError()"} {"repo":"flask","file":"src/flask/views.py","line":86,"symbol":"as_view","kind":"function","lang":"python","code":"def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> ft.RouteCallable:\n \"\"\"Convert the class into a view function that can be registered\n for a route.\n\n By default, the generated view will create a new instance of the\n view class for every request and call its\n :meth:`dispatch_request` method. If the view class sets\n :attr:`init_every_request` to ``False``, the same instance will\n be used for every request.\n\n Except for ``name``, all other arguments passed to this method\n are forwarded to the view class ``__init__`` method.\n\n .. versionchanged:: 2.2\n Added the ``init_every_request`` class attribute.\n \"\"\"\n if cls.init_every_request:\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n self = view.view_class( # type: ignore[attr-defined]\n *class_args, **class_kwargs\n )\n return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]\n\n else:\n self = cls(*class_args, **class_kwargs) # pyright: ignore\n\n def view(**kwargs:"} {"repo":"flask","file":"src/flask/views.py","line":106,"symbol":"view","kind":"function","lang":"python","code":"def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n self = view.view_class( # type: ignore[attr-defined]\n *class_args, **class_kwargs\n )\n return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/views.py","line":115,"symbol":"view","kind":"function","lang":"python","code":"def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/views.py","line":138,"symbol":"MethodView","kind":"class","lang":"python","code":"class MethodView(View):\n \"\"\"Dispatches request methods to the corresponding instance methods.\n For example, if you implement a ``get`` method, it will be used to\n handle ``GET`` requests.\n\n This can be useful for defining a REST API.\n\n :attr:`methods` is automatically set based on the methods defined on\n the class.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class CounterAPI(MethodView):\n def get(self):\n return str(session.get(\"counter\", 0))\n\n def post(self):\n session[\"counter\"] = session.get(\"counter\", 0) + 1\n return redirect(url_for(\"counter\"))\n\n app.add_url_rule(\n \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n )\n \"\"\"\n\n def __init_subclass__(cls, **kwargs: t.Any) -> None:\n super().__init_subclass__(**kwargs)\n\n if \"methods\" not in cls.__dict__:\n methods = set()\n\n for base in cls.__bases__:\n if getattr(base, \"methods\", None):\n methods.update(base.methods) # type: ignore[attr-defined]\n\n for key in http_method_funcs:\n if hasattr(cls"} {"repo":"flask","file":"src/flask/views.py","line":165,"symbol":"__init_subclass__","kind":"function","lang":"python","code":"def __init_subclass__(cls, **kwargs: t.Any) -> None:\n super().__init_subclass__(**kwargs)\n\n if \"methods\" not in cls.__dict__:\n methods = set()\n\n for base in cls.__bases__:\n if getattr(base, \"methods\", None):\n methods.update(base.methods) # type: ignore[attr-defined]\n\n for key in http_method_funcs:\n if hasattr(cls, key):\n methods.add(key.upper())\n\n if methods:\n cls.methods = methods"} {"repo":"flask","file":"src/flask/views.py","line":182,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n meth = getattr(self, request.method.lower(), None)\n\n # If the request method is HEAD and we don't have a handler for it\n # retry with GET.\n if meth is None and request.method == \"HEAD\":\n meth = getattr(self, \"get\", None)\n\n assert meth is not None, f\"Unimplemented method {request.method!r}\"\n return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/wrappers.py","line":18,"symbol":"Request","kind":"class","lang":"python","code":"class Request(RequestBase):\n \"\"\"The request object used by default in Flask. Remembers the\n matched endpoint and view arguments.\n\n It is what ends up as :class:`~flask.request`. If you want to replace\n the request object used you can subclass this and set\n :attr:`~flask.Flask.request_class` to your subclass.\n\n The request object is a :class:`~werkzeug.wrappers.Request` subclass and\n provides all of the attributes Werkzeug defines plus a few Flask\n specific ones.\n \"\"\"\n\n json_module: t.Any = json\n\n #: The internal URL rule that matched the request. This can be\n #: useful to inspect which methods are allowed for the URL from\n #: a before/after handler (``request.url_rule.methods``) etc.\n #: Though if the request's method was invalid for the URL rule,\n #: the valid list is available in ``routing_exception.valid_methods``\n #: instead (an attribute of the Werkzeug exception\n #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)\n #: because the request was never internally bound.\n #:\n #: .. versionadded:: 0.6\n url_rule: Rule | None = None\n\n #: A dict of view arguments that matched the request. If an exception\n #: happened"} {"repo":"flask","file":"src/flask/wrappers.py","line":60,"symbol":"max_content_length","kind":"function","lang":"python","code":"def max_content_length(self) -> int | None:\n \"\"\"The maximum number of bytes that will be read during this request. If\n this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`\n error is raised. If it is set to ``None``, no limit is enforced at the\n Flask application level. However, if it is ``None`` and the request has\n no ``Content-Length`` header and the WSGI server does not indicate that\n it terminates the stream, then no data is read to avoid an infinite\n stream.\n\n Each request defaults to the :data:`MAX_CONTENT_LENGTH` config, which\n defaults to ``None``. It can be set on a specific ``request`` to apply\n the limit to that specific view. This should be set appropriately based\n on an application's or view's specific needs.\n\n .. versionchanged:: 3.1\n This can be set per-request.\n\n .. versionchanged:: 0.6\n This is configurable through Flask config.\n \"\"\"\n if self._max_content_length is not None:\n return self._max_content_length\n\n if not current_app:\n return super().max_content_length\n\n return curren"} {"repo":"flask","file":"src/flask/wrappers.py","line":89,"symbol":"max_content_length","kind":"function","lang":"python","code":"def max_content_length(self, value: int | None) -> None:\n self._max_content_length = value"} {"repo":"flask","file":"src/flask/wrappers.py","line":93,"symbol":"max_form_memory_size","kind":"function","lang":"python","code":"def max_form_memory_size(self) -> int | None:\n \"\"\"The maximum size in bytes any non-file form field may be in a\n ``multipart/form-data`` body. If this limit is exceeded, a 413\n :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it\n is set to ``None``, no limit is enforced at the Flask application level.\n\n Each request defaults to the :data:`MAX_FORM_MEMORY_SIZE` config, which\n defaults to ``500_000``. It can be set on a specific ``request`` to\n apply the limit to that specific view. This should be set appropriately\n based on an application's or view's specific needs.\n\n .. versionchanged:: 3.1\n This is configurable through Flask config.\n \"\"\"\n if self._max_form_memory_size is not None:\n return self._max_form_memory_size\n\n if not current_app:\n return super().max_form_memory_size\n\n return current_app.config[\"MAX_FORM_MEMORY_SIZE\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/wrappers.py","line":116,"symbol":"max_form_memory_size","kind":"function","lang":"python","code":"def max_form_memory_size(self, value: int | None) -> None:\n self._max_form_memory_size = value"} {"repo":"flask","file":"src/flask/wrappers.py","line":120,"symbol":"max_form_parts","kind":"function","lang":"python","code":"def max_form_parts(self) -> int | None:\n \"\"\"The maximum number of fields that may be present in a\n ``multipart/form-data`` body. If this limit is exceeded, a 413\n :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it\n is set to ``None``, no limit is enforced at the Flask application level.\n\n Each request defaults to the :data:`MAX_FORM_PARTS` config, which\n defaults to ``1_000``. It can be set on a specific ``request`` to apply\n the limit to that specific view. This should be set appropriately based\n on an application's or view's specific needs.\n\n .. versionchanged:: 3.1\n This is configurable through Flask config.\n \"\"\"\n if self._max_form_parts is not None:\n return self._max_form_parts\n\n if not current_app:\n return super().max_form_parts\n\n return current_app.config[\"MAX_FORM_PARTS\"] # type: ignore[no-any-return]"} {"repo":"flask","file":"src/flask/wrappers.py","line":143,"symbol":"max_form_parts","kind":"function","lang":"python","code":"def max_form_parts(self, value: int | None) -> None:\n self._max_form_parts = value"} {"repo":"flask","file":"src/flask/wrappers.py","line":147,"symbol":"endpoint","kind":"function","lang":"python","code":"def endpoint(self) -> str | None:\n \"\"\"The endpoint that matched the request URL.\n\n This will be ``None`` if matching failed or has not been\n performed yet.\n\n This in combination with :attr:`view_args` can be used to\n reconstruct the same URL or a modified URL.\n \"\"\"\n if self.url_rule is not None:\n return self.url_rule.endpoint # type: ignore[no-any-return]\n\n return None"} {"repo":"flask","file":"src/flask/wrappers.py","line":162,"symbol":"blueprint","kind":"function","lang":"python","code":"def blueprint(self) -> str | None:\n \"\"\"The registered name of the current blueprint.\n\n This will be ``None`` if the endpoint is not part of a\n blueprint, or if URL matching failed or has not been performed\n yet.\n\n This does not necessarily match the name the blueprint was\n created with. It may have been nested, or registered with a\n different name.\n \"\"\"\n endpoint = self.endpoint\n\n if endpoint is not None and \".\" in endpoint:\n return endpoint.rpartition(\".\")[0]\n\n return None"} {"repo":"flask","file":"src/flask/wrappers.py","line":181,"symbol":"blueprints","kind":"function","lang":"python","code":"def blueprints(self) -> list[str]:\n \"\"\"The registered names of the current blueprint upwards through\n parent blueprints.\n\n This will be an empty list if there is no current blueprint, or\n if URL matching failed.\n\n .. versionadded:: 2.0.1\n \"\"\"\n name = self.blueprint\n\n if name is None:\n return []\n\n return _split_blueprint_path(name)"} {"repo":"flask","file":"src/flask/wrappers.py","line":197,"symbol":"_load_form_data","kind":"function","lang":"python","code":"def _load_form_data(self) -> None:\n super()._load_form_data()\n\n # In debug mode we're replacing the files multidict with an ad-hoc\n # subclass that raises a different error for key errors.\n if (\n current_app\n and current_app.debug\n and self.mimetype != \"multipart/form-data\"\n and not self.files\n ):\n from .debughelpers import attach_enctype_error_multidict\n\n attach_enctype_error_multidict(self)"} {"repo":"flask","file":"src/flask/wrappers.py","line":212,"symbol":"on_json_loading_failed","kind":"function","lang":"python","code":"def on_json_loading_failed(self, e: ValueError | None) -> t.Any:\n try:\n return super().on_json_loading_failed(e)\n except BadRequest as ebr:\n if current_app and current_app.debug:\n raise\n\n raise BadRequest() from ebr"} {"repo":"flask","file":"src/flask/wrappers.py","line":222,"symbol":"Response","kind":"class","lang":"python","code":"class Response(ResponseBase):\n \"\"\"The response object that is used by default in Flask. Works like the\n response object from Werkzeug but is set to have an HTML mimetype by\n default. Quite often you don't have to create this object yourself because\n :meth:`~flask.Flask.make_response` will take care of that for you.\n\n If you want to replace the response object used you can subclass this and\n set :attr:`~flask.Flask.response_class` to your subclass.\n\n .. versionchanged:: 1.0\n JSON support is added to the response, like the request. This is useful\n when testing to get the test client response data as JSON.\n\n .. versionchanged:: 1.0\n\n Added :attr:`max_cookie_size`.\n \"\"\"\n\n default_mimetype: str | None = \"text/html\"\n\n json_module = json\n\n autocorrect_location_header = False\n\n @property\n def max_cookie_size(self) -> int: # type: ignore\n \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n \"\"\"\n if current_app:\n return current_app.config[\"MAX_COOKIE_SIZE\"] # type: ignore[no-any-return]\n\n "} {"repo":"flask","file":"src/flask/wrappers.py","line":247,"symbol":"max_cookie_size","kind":"function","lang":"python","code":"def max_cookie_size(self) -> int: # type: ignore\n \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n \"\"\"\n if current_app:\n return current_app.config[\"MAX_COOKIE_SIZE\"] # type: ignore[no-any-return]\n\n # return Werkzeug's default when not in an app context\n return super().max_cookie_size"} {"repo":"flask","file":"tests/conftest.py","line":11,"symbol":"_standard_os_environ","kind":"function","lang":"python","code":"def _standard_os_environ(monkeypatch):\n \"\"\"Set up ``os.environ`` at the start of every test to have\n standard values.\n \"\"\"\n for key in (\n \"FLASK_ENV_FILE\",\n \"FLASK_APP\",\n \"FLASK_DEBUG\",\n \"FLASK_RUN_FROM_CLI\",\n \"WERKZEUG_RUN_MAIN\",\n ):\n monkeypatch.delenv(key, False)\n\n yield"} {"repo":"flask","file":"tests/conftest.py","line":28,"symbol":"app","kind":"function","lang":"python","code":"def app():\n app = Flask(\"flask_test\", root_path=os.path.dirname(__file__))\n app.config.update(\n TESTING=True,\n SECRET_KEY=\"test key\",\n )\n return app"} {"repo":"flask","file":"tests/conftest.py","line":38,"symbol":"app_ctx","kind":"function","lang":"python","code":"def app_ctx(app):\n with app.app_context() as ctx:\n yield ctx"} {"repo":"flask","file":"tests/conftest.py","line":44,"symbol":"req_ctx","kind":"function","lang":"python","code":"def req_ctx(app):\n with app.test_request_context() as ctx:\n yield ctx"} {"repo":"flask","file":"tests/conftest.py","line":50,"symbol":"client","kind":"function","lang":"python","code":"def client(app):\n return app.test_client()"} {"repo":"flask","file":"tests/conftest.py","line":55,"symbol":"test_apps","kind":"function","lang":"python","code":"def test_apps(monkeypatch):\n monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), \"test_apps\"))\n original_modules = set(sys.modules.keys())\n\n yield\n\n # Remove any imports cached during the test. Otherwise \"import app\"\n # will work in the next test even though it's no longer on the path.\n for key in sys.modules.keys() - original_modules:\n sys.modules.pop(key)"} {"repo":"flask","file":"tests/conftest.py","line":68,"symbol":"leak_detector","kind":"function","lang":"python","code":"def leak_detector():\n \"\"\"Fails if any app contexts are still pushed when a test ends. Pops all\n contexts so subsequent tests are not affected.\n \"\"\"\n yield\n leaks = []\n\n while _app_ctx:\n leaks.append(_app_ctx._get_current_object())\n _app_ctx.pop()\n\n assert not leaks"} {"repo":"flask","file":"tests/conftest.py","line":83,"symbol":"modules_tmp_path","kind":"function","lang":"python","code":"def modules_tmp_path(tmp_path, monkeypatch):\n \"\"\"A temporary directory added to sys.path.\"\"\"\n rv = tmp_path / \"modules_tmp\"\n rv.mkdir()\n monkeypatch.syspath_prepend(os.fspath(rv))\n return rv"} {"repo":"flask","file":"tests/conftest.py","line":92,"symbol":"modules_tmp_path_prefix","kind":"function","lang":"python","code":"def modules_tmp_path_prefix(modules_tmp_path, monkeypatch):\n monkeypatch.setattr(sys, \"prefix\", os.fspath(modules_tmp_path))\n return modules_tmp_path"} {"repo":"flask","file":"tests/conftest.py","line":98,"symbol":"site_packages","kind":"function","lang":"python","code":"def site_packages(modules_tmp_path, monkeypatch):\n \"\"\"Create a fake site-packages.\"\"\"\n py_dir = f\"python{sys.version_info.major}.{sys.version_info.minor}\"\n rv = modules_tmp_path / \"lib\" / py_dir / \"site-packages\"\n rv.mkdir(parents=True)\n monkeypatch.syspath_prepend(os.fspath(rv))\n return rv"} {"repo":"flask","file":"tests/conftest.py","line":108,"symbol":"purge_module","kind":"function","lang":"python","code":"def purge_module(request):\n def inner(name):\n request.addfinalizer(lambda: sys.modules.pop(name, None))\n\n return inner"} {"repo":"flask","file":"tests/conftest.py","line":109,"symbol":"inner","kind":"function","lang":"python","code":"def inner(name):\n request.addfinalizer(lambda: sys.modules.pop(name, None))"} {"repo":"flask","file":"tests/test_appctx.py","line":10,"symbol":"test_basic_url_generation","kind":"function","lang":"python","code":"def test_basic_url_generation(app):\n app.config[\"SERVER_NAME\"] = \"localhost\"\n app.config[\"PREFERRED_URL_SCHEME\"] = \"https\"\n\n @app.route(\"/\")\n def index():\n pass\n\n with app.app_context():\n rv = flask.url_for(\"index\")\n assert rv == \"https://localhost/\""} {"repo":"flask","file":"tests/test_appctx.py","line":15,"symbol":"index","kind":"function","lang":"python","code":"def index():\n pass"} {"repo":"flask","file":"tests/test_appctx.py","line":23,"symbol":"test_url_generation_requires_server_name","kind":"function","lang":"python","code":"def test_url_generation_requires_server_name(app):\n with app.app_context():\n with pytest.raises(RuntimeError):\n flask.url_for(\"index\")"} {"repo":"flask","file":"tests/test_appctx.py","line":29,"symbol":"test_url_generation_without_context_fails","kind":"function","lang":"python","code":"def test_url_generation_without_context_fails():\n with pytest.raises(RuntimeError):\n flask.url_for(\"index\")"} {"repo":"flask","file":"tests/test_appctx.py","line":34,"symbol":"test_request_context_means_app_context","kind":"function","lang":"python","code":"def test_request_context_means_app_context(app):\n with app.test_request_context():\n assert flask.current_app._get_current_object() is app\n assert not flask.current_app"} {"repo":"flask","file":"tests/test_appctx.py","line":40,"symbol":"test_app_context_provides_current_app","kind":"function","lang":"python","code":"def test_app_context_provides_current_app(app):\n with app.app_context():\n assert flask.current_app._get_current_object() is app\n assert not flask.current_app"} {"repo":"flask","file":"tests/test_appctx.py","line":46,"symbol":"test_app_tearing_down","kind":"function","lang":"python","code":"def test_app_tearing_down(app):\n cleanup_stuff = []\n\n @app.teardown_appcontext\n def cleanup(exception):\n cleanup_stuff.append(exception)\n\n with app.app_context():\n pass\n\n assert cleanup_stuff == [None]"} {"repo":"flask","file":"tests/test_appctx.py","line":50,"symbol":"cleanup","kind":"function","lang":"python","code":"def cleanup(exception):\n cleanup_stuff.append(exception)"} {"repo":"flask","file":"tests/test_appctx.py","line":59,"symbol":"test_app_tearing_down_with_previous_exception","kind":"function","lang":"python","code":"def test_app_tearing_down_with_previous_exception(app):\n cleanup_stuff = []\n\n @app.teardown_appcontext\n def cleanup(exception):\n cleanup_stuff.append(exception)\n\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n\n with app.app_context():\n pass\n\n assert cleanup_stuff == [None]"} {"repo":"flask","file":"tests/test_appctx.py","line":63,"symbol":"cleanup","kind":"function","lang":"python","code":"def cleanup(exception):\n cleanup_stuff.append(exception)"} {"repo":"flask","file":"tests/test_appctx.py","line":77,"symbol":"test_app_tearing_down_with_handled_exception_by_except_block","kind":"function","lang":"python","code":"def test_app_tearing_down_with_handled_exception_by_except_block(app):\n cleanup_stuff = []\n\n @app.teardown_appcontext\n def cleanup(exception):\n cleanup_stuff.append(exception)\n\n with app.app_context():\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n\n assert cleanup_stuff == [None]"} {"repo":"flask","file":"tests/test_appctx.py","line":81,"symbol":"cleanup","kind":"function","lang":"python","code":"def cleanup(exception):\n cleanup_stuff.append(exception)"} {"repo":"flask","file":"tests/test_appctx.py","line":93,"symbol":"test_app_tearing_down_with_handled_exception_by_app_handler","kind":"function","lang":"python","code":"def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):\n app.config[\"PROPAGATE_EXCEPTIONS\"] = True\n cleanup_stuff = []\n\n @app.teardown_appcontext\n def cleanup(exception):\n cleanup_stuff.append(exception)\n\n @app.route(\"/\")\n def index():\n raise Exception(\"dummy\")\n\n @app.errorhandler(Exception)\n def handler(f):\n return flask.jsonify(str(f))\n\n with app.app_context():\n client.get(\"/\")\n\n # teardown request context, and with block context\n assert cleanup_stuff == [None, None]"} {"repo":"flask","file":"tests/test_appctx.py","line":98,"symbol":"cleanup","kind":"function","lang":"python","code":"def cleanup(exception):\n cleanup_stuff.append(exception)"} {"repo":"flask","file":"tests/test_appctx.py","line":102,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise Exception(\"dummy\")"} {"repo":"flask","file":"tests/test_appctx.py","line":106,"symbol":"handler","kind":"function","lang":"python","code":"def handler(f):\n return flask.jsonify(str(f))"} {"repo":"flask","file":"tests/test_appctx.py","line":116,"symbol":"test_app_tearing_down_with_unhandled_exception","kind":"function","lang":"python","code":"def test_app_tearing_down_with_unhandled_exception(app, client):\n app.config[\"PROPAGATE_EXCEPTIONS\"] = True\n cleanup_stuff = []\n\n @app.teardown_appcontext\n def cleanup(exception):\n cleanup_stuff.append(exception)\n\n @app.route(\"/\")\n def index():\n raise ValueError(\"dummy\")\n\n with pytest.raises(ValueError, match=\"dummy\"):\n with app.app_context():\n client.get(\"/\")\n\n assert len(cleanup_stuff) == 2\n assert isinstance(cleanup_stuff[0], ValueError)\n assert str(cleanup_stuff[0]) == \"dummy\"\n # exception propagated, seen by request context and with block context\n assert cleanup_stuff[0] is cleanup_stuff[1]"} {"repo":"flask","file":"tests/test_appctx.py","line":121,"symbol":"cleanup","kind":"function","lang":"python","code":"def cleanup(exception):\n cleanup_stuff.append(exception)"} {"repo":"flask","file":"tests/test_appctx.py","line":125,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise ValueError(\"dummy\")"} {"repo":"flask","file":"tests/test_appctx.py","line":139,"symbol":"test_app_ctx_globals_methods","kind":"function","lang":"python","code":"def test_app_ctx_globals_methods(app, app_ctx):\n # get\n assert flask.g.get(\"foo\") is None\n assert flask.g.get(\"foo\", \"bar\") == \"bar\"\n # __contains__\n assert \"foo\" not in flask.g\n flask.g.foo = \"bar\"\n assert \"foo\" in flask.g\n # setdefault\n flask.g.setdefault(\"bar\", \"the cake is a lie\")\n flask.g.setdefault(\"bar\", \"hello world\")\n assert flask.g.bar == \"the cake is a lie\"\n # pop\n assert flask.g.pop(\"bar\") == \"the cake is a lie\"\n with pytest.raises(KeyError):\n flask.g.pop(\"bar\")\n assert flask.g.pop(\"bar\", \"more cake\") == \"more cake\"\n # __iter__\n assert list(flask.g) == [\"foo\"]\n # __repr__\n assert repr(flask.g) == \"\""} {"repo":"flask","file":"tests/test_appctx.py","line":162,"symbol":"test_custom_app_ctx_globals_class","kind":"function","lang":"python","code":"def test_custom_app_ctx_globals_class(app):\n class CustomRequestGlobals:\n def __init__(self):\n self.spam = \"eggs\"\n\n app.app_ctx_globals_class = CustomRequestGlobals\n with app.app_context():\n assert flask.render_template_string(\"{{ g.spam }}\") == \"eggs\""} {"repo":"flask","file":"tests/test_appctx.py","line":163,"symbol":"CustomRequestGlobals","kind":"class","lang":"python","code":"class CustomRequestGlobals:\n def __init__(self):\n self.spam = \"eggs\""} {"repo":"flask","file":"tests/test_appctx.py","line":164,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self):\n self.spam = \"eggs\""} {"repo":"flask","file":"tests/test_appctx.py","line":172,"symbol":"test_context_refcounts","kind":"function","lang":"python","code":"def test_context_refcounts(app, client):\n called = []\n\n @app.teardown_request\n def teardown_req(error=None):\n called.append(\"request\")\n\n @app.teardown_appcontext\n def teardown_app(error=None):\n called.append(\"app\")\n\n @app.route(\"/\")\n def index():\n with app_ctx:\n pass\n\n assert flask.request.environ[\"werkzeug.request\"] is not None\n return \"\"\n\n res = client.get(\"/\")\n assert res.status_code == 200\n assert res.data == b\"\"\n assert called == [\"request\", \"app\"]"} {"repo":"flask","file":"tests/test_appctx.py","line":176,"symbol":"teardown_req","kind":"function","lang":"python","code":"def teardown_req(error=None):\n called.append(\"request\")"} {"repo":"flask","file":"tests/test_appctx.py","line":180,"symbol":"teardown_app","kind":"function","lang":"python","code":"def teardown_app(error=None):\n called.append(\"app\")"} {"repo":"flask","file":"tests/test_appctx.py","line":184,"symbol":"index","kind":"function","lang":"python","code":"def index():\n with app_ctx:\n pass\n\n assert flask.request.environ[\"werkzeug.request\"] is not None\n return \"\""} {"repo":"flask","file":"tests/test_appctx.py","line":197,"symbol":"test_clean_pop","kind":"function","lang":"python","code":"def test_clean_pop(app):\n app.testing = False\n called = []\n\n @app.teardown_request\n def teardown_req(error=None):\n raise ZeroDivisionError\n\n @app.teardown_appcontext\n def teardown_app(error=None):\n called.append(\"TEARDOWN\")\n\n with app.app_context():\n called.append(flask.current_app.name)\n\n assert called == [\"flask_test\", \"TEARDOWN\"]\n assert not flask.current_app"} {"repo":"flask","file":"tests/test_appctx.py","line":202,"symbol":"teardown_req","kind":"function","lang":"python","code":"def teardown_req(error=None):\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_appctx.py","line":206,"symbol":"teardown_app","kind":"function","lang":"python","code":"def teardown_app(error=None):\n called.append(\"TEARDOWN\")"} {"repo":"flask","file":"tests/test_appctx.py","line":216,"symbol":"test_robust_teardown","kind":"function","lang":"python","code":"def test_robust_teardown(app: flask.Flask, client: FlaskClient) -> None:\n count = 0\n\n @app.teardown_request\n def request_teardown(e: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"request_teardown\")\n\n @app.teardown_appcontext\n def app_teardown(e: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"app_teardown\")\n\n @app.get(\"/\")\n def index() -> str:\n return \"\"\n\n def request_signal(sender: flask.Flask, exc: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"request_signal\")\n\n def app_signal(sender: flask.Flask, exc: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"app_signal\")\n\n with (\n flask.request_tearing_down.connected_to(request_signal, app),\n flask.appcontext_tearing_down.connected_to(app_signal, app),\n ):\n if sys.version_info >= (3, 11):\n with pytest.raises(ExceptionGroup, match=\"context teardown\") as exc_info: # noqa: F821\n client.get()\n\n assert len(exc_info.value.exceptions) == 2\n eg1, eg2"} {"repo":"flask","file":"tests/test_appctx.py","line":220,"symbol":"request_teardown","kind":"function","lang":"python","code":"def request_teardown(e: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"request_teardown\")"} {"repo":"flask","file":"tests/test_appctx.py","line":226,"symbol":"app_teardown","kind":"function","lang":"python","code":"def app_teardown(e: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"app_teardown\")"} {"repo":"flask","file":"tests/test_appctx.py","line":232,"symbol":"index","kind":"function","lang":"python","code":"def index() -> str:\n return \"\""} {"repo":"flask","file":"tests/test_appctx.py","line":235,"symbol":"request_signal","kind":"function","lang":"python","code":"def request_signal(sender: flask.Flask, exc: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"request_signal\")"} {"repo":"flask","file":"tests/test_appctx.py","line":240,"symbol":"app_signal","kind":"function","lang":"python","code":"def app_signal(sender: flask.Flask, exc: Exception | None) -> None:\n nonlocal count\n count += 1\n raise ValueError(\"app_signal\")"} {"repo":"flask","file":"tests/test_apps/.flaskenv","line":1,"symbol":"FOO","kind":"variable","lang":"bash","code":"FOO=flaskenv"} {"repo":"flask","file":"tests/test_apps/.flaskenv","line":2,"symbol":"BAR","kind":"variable","lang":"bash","code":"BAR=bar"} {"repo":"flask","file":"tests/test_apps/.flaskenv","line":3,"symbol":"EGGS","kind":"variable","lang":"bash","code":"EGGS=0"} {"repo":"flask","file":"tests/test_apps/blueprintapp/apps/admin/__init__.py","line":14,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return render_template(\"admin/index.html\")"} {"repo":"flask","file":"tests/test_apps/blueprintapp/apps/admin/__init__.py","line":19,"symbol":"index2","kind":"function","lang":"python","code":"def index2():\n return render_template(\"./admin/index.html\")"} {"repo":"flask","file":"tests/test_apps/blueprintapp/apps/frontend/__init__.py","line":8,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return render_template(\"frontend/index.html\")"} {"repo":"flask","file":"tests/test_apps/blueprintapp/apps/frontend/__init__.py","line":13,"symbol":"missing_template","kind":"function","lang":"python","code":"def missing_template():\n return render_template(\"missing_template.html\")"} {"repo":"flask","file":"tests/test_apps/cliapp/factory.py","line":4,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"app\")"} {"repo":"flask","file":"tests/test_apps/cliapp/factory.py","line":8,"symbol":"create_app2","kind":"function","lang":"python","code":"def create_app2(foo, bar):\n return Flask(\"_\".join([\"app2\", foo, bar]))"} {"repo":"flask","file":"tests/test_apps/cliapp/factory.py","line":12,"symbol":"no_app","kind":"function","lang":"python","code":"def no_app():\n pass"} {"repo":"flask","file":"tests/test_apps/helloworld/hello.py","line":7,"symbol":"hello","kind":"function","lang":"python","code":"def hello():\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_async.py","line":14,"symbol":"AppError","kind":"class","lang":"python","code":"class AppError(Exception):\n pass"} {"repo":"flask","file":"tests/test_async.py","line":18,"symbol":"BlueprintError","kind":"class","lang":"python","code":"class BlueprintError(Exception):\n pass"} {"repo":"flask","file":"tests/test_async.py","line":22,"symbol":"AsyncView","kind":"class","lang":"python","code":"class AsyncView(View):\n methods = [\"GET\", \"POST\"]\n\n async def dispatch_request(self):\n await asyncio.sleep(0)\n return request.method"} {"repo":"flask","file":"tests/test_async.py","line":25,"symbol":"dispatch_request","kind":"function","lang":"python","code":"async def dispatch_request(self):\n await asyncio.sleep(0)\n return request.method"} {"repo":"flask","file":"tests/test_async.py","line":30,"symbol":"AsyncMethodView","kind":"class","lang":"python","code":"class AsyncMethodView(MethodView):\n async def get(self):\n await asyncio.sleep(0)\n return \"GET\"\n\n async def post(self):\n await asyncio.sleep(0)\n return \"POST\""} {"repo":"flask","file":"tests/test_async.py","line":31,"symbol":"get","kind":"function","lang":"python","code":"async def get(self):\n await asyncio.sleep(0)\n return \"GET\""} {"repo":"flask","file":"tests/test_async.py","line":35,"symbol":"post","kind":"function","lang":"python","code":"async def post(self):\n await asyncio.sleep(0)\n return \"POST\""} {"repo":"flask","file":"tests/test_async.py","line":41,"symbol":"_async_app","kind":"function","lang":"python","code":"def _async_app():\n app = Flask(__name__)\n\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n @app.route(\"/home\", methods=[\"GET\", \"POST\"])\n async def index():\n await asyncio.sleep(0)\n return request.method\n\n @app.errorhandler(AppError)\n async def handle(_):\n return \"\", 412\n\n @app.route(\"/error\")\n async def error():\n raise AppError()\n\n blueprint = Blueprint(\"bp\", __name__)\n\n @blueprint.route(\"/\", methods=[\"GET\", \"POST\"])\n async def bp_index():\n await asyncio.sleep(0)\n return request.method\n\n @blueprint.errorhandler(BlueprintError)\n async def bp_handle(_):\n return \"\", 412\n\n @blueprint.route(\"/error\")\n async def bp_error():\n raise BlueprintError()\n\n app.register_blueprint(blueprint, url_prefix=\"/bp\")\n\n app.add_url_rule(\"/view\", view_func=AsyncView.as_view(\"view\"))\n app.add_url_rule(\"/methodview\", view_func=AsyncMethodView.as_view(\"methodview\"))\n\n return app"} {"repo":"flask","file":"tests/test_async.py","line":46,"symbol":"index","kind":"function","lang":"python","code":"async def index():\n await asyncio.sleep(0)\n return request.method"} {"repo":"flask","file":"tests/test_async.py","line":51,"symbol":"handle","kind":"function","lang":"python","code":"async def handle(_):\n return \"\", 412"} {"repo":"flask","file":"tests/test_async.py","line":55,"symbol":"error","kind":"function","lang":"python","code":"async def error():\n raise AppError()"} {"repo":"flask","file":"tests/test_async.py","line":61,"symbol":"bp_index","kind":"function","lang":"python","code":"async def bp_index():\n await asyncio.sleep(0)\n return request.method"} {"repo":"flask","file":"tests/test_async.py","line":66,"symbol":"bp_handle","kind":"function","lang":"python","code":"async def bp_handle(_):\n return \"\", 412"} {"repo":"flask","file":"tests/test_async.py","line":70,"symbol":"bp_error","kind":"function","lang":"python","code":"async def bp_error():\n raise BlueprintError()"} {"repo":"flask","file":"tests/test_async.py","line":82,"symbol":"test_async_route","kind":"function","lang":"python","code":"def test_async_route(path, async_app):\n test_client = async_app.test_client()\n response = test_client.get(path)\n assert b\"GET\" in response.get_data()\n response = test_client.post(path)\n assert b\"POST\" in response.get_data()"} {"repo":"flask","file":"tests/test_async.py","line":91,"symbol":"test_async_error_handler","kind":"function","lang":"python","code":"def test_async_error_handler(path, async_app):\n test_client = async_app.test_client()\n response = test_client.get(path)\n assert response.status_code == 412"} {"repo":"flask","file":"tests/test_async.py","line":97,"symbol":"test_async_before_after_request","kind":"function","lang":"python","code":"def test_async_before_after_request():\n app_before_called = False\n app_after_called = False\n bp_before_called = False\n bp_after_called = False\n\n app = Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return \"\"\n\n @app.before_request\n async def before():\n nonlocal app_before_called\n app_before_called = True\n\n @app.after_request\n async def after(response):\n nonlocal app_after_called\n app_after_called = True\n return response\n\n blueprint = Blueprint(\"bp\", __name__)\n\n @blueprint.route(\"/\")\n def bp_index():\n return \"\"\n\n @blueprint.before_request\n async def bp_before():\n nonlocal bp_before_called\n bp_before_called = True\n\n @blueprint.after_request\n async def bp_after(response):\n nonlocal bp_after_called\n bp_after_called = True\n return response\n\n app.register_blueprint(blueprint, url_prefix=\"/bp\")\n\n test_client = app.test_client()\n test_client.get(\"/\")\n assert app_before_called\n assert app_after_called\n test_client.get(\"/bp/\")\n assert bp_before_called\n assert bp_after_called"} {"repo":"flask","file":"tests/test_async.py","line":106,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"\""} {"repo":"flask","file":"tests/test_async.py","line":110,"symbol":"before","kind":"function","lang":"python","code":"async def before():\n nonlocal app_before_called\n app_before_called = True"} {"repo":"flask","file":"tests/test_async.py","line":115,"symbol":"after","kind":"function","lang":"python","code":"async def after(response):\n nonlocal app_after_called\n app_after_called = True\n return response"} {"repo":"flask","file":"tests/test_async.py","line":123,"symbol":"bp_index","kind":"function","lang":"python","code":"def bp_index():\n return \"\""} {"repo":"flask","file":"tests/test_async.py","line":127,"symbol":"bp_before","kind":"function","lang":"python","code":"async def bp_before():\n nonlocal bp_before_called\n bp_before_called = True"} {"repo":"flask","file":"tests/test_async.py","line":132,"symbol":"bp_after","kind":"function","lang":"python","code":"async def bp_after(response):\n nonlocal bp_after_called\n bp_after_called = True\n return response"} {"repo":"flask","file":"tests/test_basic.py","line":33,"symbol":"test_options_work","kind":"function","lang":"python","code":"def test_options_work(app, client):\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n def index():\n return \"Hello World\"\n\n rv = client.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n assert rv.data == b\"\""} {"repo":"flask","file":"tests/test_basic.py","line":35,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":43,"symbol":"test_options_on_multiple_rules","kind":"function","lang":"python","code":"def test_options_on_multiple_rules(app, client):\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n def index():\n return \"Hello World\"\n\n @app.route(\"/\", methods=[\"PUT\"])\n def index_put():\n return \"Aha!\"\n\n rv = client.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\", \"PUT\"]"} {"repo":"flask","file":"tests/test_basic.py","line":45,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":49,"symbol":"index_put","kind":"function","lang":"python","code":"def index_put():\n return \"Aha!\""} {"repo":"flask","file":"tests/test_basic.py","line":57,"symbol":"test_method_route","kind":"function","lang":"python","code":"def test_method_route(app, client, method):\n method_route = getattr(app, method)\n client_method = getattr(\n client, method, partial(client.open, method=method.capitalize())\n )\n\n @method_route(\"/\")\n def hello():\n return \"Hello\"\n\n assert client_method(\"/\").data == b\"Hello\""} {"repo":"flask","file":"tests/test_basic.py","line":64,"symbol":"hello","kind":"function","lang":"python","code":"def hello():\n return \"Hello\""} {"repo":"flask","file":"tests/test_basic.py","line":70,"symbol":"test_method_route_no_methods","kind":"function","lang":"python","code":"def test_method_route_no_methods(app):\n with pytest.raises(TypeError):\n app.get(\"/\", methods=[\"GET\", \"POST\"])"} {"repo":"flask","file":"tests/test_basic.py","line":75,"symbol":"test_provide_automatic_options_attr_disable","kind":"function","lang":"python","code":"def test_provide_automatic_options_attr_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options can be disabled by the view func attribute.\"\"\"\n\n def index():\n return \"Hello World!\"\n\n index.provide_automatic_options = False\n app.add_url_rule(\"/\", view_func=index)\n rv = client.options()\n assert rv.status_code == 405"} {"repo":"flask","file":"tests/test_basic.py","line":80,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_basic.py","line":89,"symbol":"test_provide_automatic_options_attr_enable","kind":"function","lang":"python","code":"def test_provide_automatic_options_attr_enable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"When default automatic options is disabled in config, it can still be\n enabled by the view function attribute.\n \"\"\"\n app.config[\"PROVIDE_AUTOMATIC_OPTIONS\"] = False\n\n def index():\n return \"Hello World!\"\n\n index.provide_automatic_options = True\n app.add_url_rule(\"/\", view_func=index)\n rv = client.options()\n assert rv.allow == {\"GET\", \"HEAD\", \"OPTIONS\"}"} {"repo":"flask","file":"tests/test_basic.py","line":97,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_basic.py","line":106,"symbol":"test_provide_automatic_options_arg_disable","kind":"function","lang":"python","code":"def test_provide_automatic_options_arg_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options can be disabled by the route argument.\"\"\"\n\n @app.get(\"/\", provide_automatic_options=False)\n def index():\n return \"Hello World!\"\n\n rv = client.options()\n assert rv.status_code == 405"} {"repo":"flask","file":"tests/test_basic.py","line":112,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_basic.py","line":119,"symbol":"test_provide_automatic_options_method_disable","kind":"function","lang":"python","code":"def test_provide_automatic_options_method_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options is ignored if the route handles options.\"\"\"\n\n @app.route(\"/\", methods=[\"OPTIONS\"])\n def index():\n return \"\", {\"X-Test\": \"test\"}\n\n rv = client.options()\n assert rv.headers[\"X-Test\"] == \"test\""} {"repo":"flask","file":"tests/test_basic.py","line":125,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"\", {\"X-Test\": \"test\"}"} {"repo":"flask","file":"tests/test_basic.py","line":132,"symbol":"test_request_dispatching","kind":"function","lang":"python","code":"def test_request_dispatching(app, client):\n @app.route(\"/\")\n def index():\n return flask.request.method\n\n @app.route(\"/more\", methods=[\"GET\", \"POST\"])\n def more():\n return flask.request.method\n\n assert client.get(\"/\").data == b\"GET\"\n rv = client.post(\"/\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\"]\n rv = client.head(\"/\")\n assert rv.status_code == 200\n assert not rv.data # head truncates\n assert client.post(\"/more\").data == b\"POST\"\n assert client.get(\"/more\").data == b\"GET\"\n rv = client.delete(\"/more\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]"} {"repo":"flask","file":"tests/test_basic.py","line":134,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.method"} {"repo":"flask","file":"tests/test_basic.py","line":138,"symbol":"more","kind":"function","lang":"python","code":"def more():\n return flask.request.method"} {"repo":"flask","file":"tests/test_basic.py","line":155,"symbol":"test_disallow_string_for_allowed_methods","kind":"function","lang":"python","code":"def test_disallow_string_for_allowed_methods(app):\n with pytest.raises(TypeError):\n app.add_url_rule(\"/\", methods=\"GET POST\", endpoint=\"test\")"} {"repo":"flask","file":"tests/test_basic.py","line":160,"symbol":"test_url_mapping","kind":"function","lang":"python","code":"def test_url_mapping(app, client):\n random_uuid4 = \"7eb41166-9ebf-4d26-b771-ea3f54f8b383\"\n\n def index():\n return flask.request.method\n\n def more():\n return flask.request.method\n\n def options():\n return random_uuid4\n\n app.add_url_rule(\"/\", \"index\", index)\n app.add_url_rule(\"/more\", \"more\", more, methods=[\"GET\", \"POST\"])\n\n # Issue 1288: Test that automatic options are not added\n # when non-uppercase 'options' in methods\n app.add_url_rule(\"/options\", \"options\", options, methods=[\"options\"])\n\n assert client.get(\"/\").data == b\"GET\"\n rv = client.post(\"/\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\"]\n rv = client.head(\"/\")\n assert rv.status_code == 200\n assert not rv.data # head truncates\n assert client.post(\"/more\").data == b\"POST\"\n assert client.get(\"/more\").data == b\"GET\"\n rv = client.delete(\"/more\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n rv = client.open(\"/options\", method=\"OPTIONS\")\n assert rv.status_code == 200\n assert random_uuid4 in rv.data.decode(\"utf-8\")"} {"repo":"flask","file":"tests/test_basic.py","line":163,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.method"} {"repo":"flask","file":"tests/test_basic.py","line":166,"symbol":"more","kind":"function","lang":"python","code":"def more():\n return flask.request.method"} {"repo":"flask","file":"tests/test_basic.py","line":169,"symbol":"options","kind":"function","lang":"python","code":"def options():\n return random_uuid4"} {"repo":"flask","file":"tests/test_basic.py","line":196,"symbol":"test_werkzeug_routing","kind":"function","lang":"python","code":"def test_werkzeug_routing(app, client):\n from werkzeug.routing import Rule\n from werkzeug.routing import Submount\n\n app.url_map.add(\n Submount(\"/foo\", [Rule(\"/bar\", endpoint=\"bar\"), Rule(\"/\", endpoint=\"index\")])\n )\n\n def bar():\n return \"bar\"\n\n def index():\n return \"index\"\n\n app.view_functions[\"bar\"] = bar\n app.view_functions[\"index\"] = index\n\n assert client.get(\"/foo/\").data == b\"index\"\n assert client.get(\"/foo/bar\").data == b\"bar\""} {"repo":"flask","file":"tests/test_basic.py","line":204,"symbol":"bar","kind":"function","lang":"python","code":"def bar():\n return \"bar\""} {"repo":"flask","file":"tests/test_basic.py","line":207,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"index\""} {"repo":"flask","file":"tests/test_basic.py","line":217,"symbol":"test_endpoint_decorator","kind":"function","lang":"python","code":"def test_endpoint_decorator(app, client):\n from werkzeug.routing import Rule\n from werkzeug.routing import Submount\n\n app.url_map.add(\n Submount(\"/foo\", [Rule(\"/bar\", endpoint=\"bar\"), Rule(\"/\", endpoint=\"index\")])\n )\n\n @app.endpoint(\"bar\")\n def bar():\n return \"bar\"\n\n @app.endpoint(\"index\")\n def index():\n return \"index\"\n\n assert client.get(\"/foo/\").data == b\"index\"\n assert client.get(\"/foo/bar\").data == b\"bar\""} {"repo":"flask","file":"tests/test_basic.py","line":226,"symbol":"bar","kind":"function","lang":"python","code":"def bar():\n return \"bar\""} {"repo":"flask","file":"tests/test_basic.py","line":230,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"index\""} {"repo":"flask","file":"tests/test_basic.py","line":237,"symbol":"test_session_accessed","kind":"function","lang":"python","code":"def test_session_accessed(app: flask.Flask, client: FlaskClient) -> None:\n @app.post(\"/\")\n def do_set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.get(\"/\")\n def do_get():\n return flask.session.get(\"value\", \"None\")\n\n @app.get(\"/nothing\")\n def do_nothing() -> str:\n return \"\"\n\n with client:\n rv = client.get(\"/nothing\")\n assert \"cookie\" not in rv.vary\n assert not app_ctx._session.accessed\n assert not app_ctx._session.modified\n\n with client:\n rv = client.post(data={\"value\": \"42\"})\n assert rv.text == \"value set\"\n assert \"cookie\" in rv.vary\n assert app_ctx._session.accessed\n assert app_ctx._session.modified\n\n with client:\n rv = client.get()\n assert rv.text == \"42\"\n assert \"cookie\" in rv.vary\n assert app_ctx._session.accessed\n assert not app_ctx._session.modified\n\n with client:\n rv = client.get(\"/nothing\")\n assert rv.text == \"\"\n assert \"cookie\" not in rv.vary\n assert not app_ctx._session.accessed\n assert not app_ctx._session.modified"} {"repo":"flask","file":"tests/test_basic.py","line":239,"symbol":"do_set","kind":"function","lang":"python","code":"def do_set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\""} {"repo":"flask","file":"tests/test_basic.py","line":244,"symbol":"do_get","kind":"function","lang":"python","code":"def do_get():\n return flask.session.get(\"value\", \"None\")"} {"repo":"flask","file":"tests/test_basic.py","line":248,"symbol":"do_nothing","kind":"function","lang":"python","code":"def do_nothing() -> str:\n return \"\""} {"repo":"flask","file":"tests/test_basic.py","line":279,"symbol":"test_session_path","kind":"function","lang":"python","code":"def test_session_path(app, client):\n app.config.update(APPLICATION_ROOT=\"/foo\")\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n rv = client.get(\"/\", \"http://example.com:8080/foo\")\n assert \"path=/foo\" in rv.headers[\"set-cookie\"].lower()"} {"repo":"flask","file":"tests/test_basic.py","line":283,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":291,"symbol":"test_session_using_application_root","kind":"function","lang":"python","code":"def test_session_using_application_root(app, client):\n class PrefixPathMiddleware:\n def __init__(self, app, prefix):\n self.app = app\n self.prefix = prefix\n\n def __call__(self, environ, start_response):\n environ[\"SCRIPT_NAME\"] = self.prefix\n return self.app(environ, start_response)\n\n app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, \"/bar\")\n app.config.update(APPLICATION_ROOT=\"/bar\")\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n rv = client.get(\"/\", \"http://example.com:8080/\")\n assert \"path=/bar\" in rv.headers[\"set-cookie\"].lower()"} {"repo":"flask","file":"tests/test_basic.py","line":292,"symbol":"PrefixPathMiddleware","kind":"class","lang":"python","code":"class PrefixPathMiddleware:\n def __init__(self, app, prefix):\n self.app = app\n self.prefix = prefix\n\n def __call__(self, environ, start_response):\n environ[\"SCRIPT_NAME\"] = self.prefix\n return self.app(environ, start_response)"} {"repo":"flask","file":"tests/test_basic.py","line":293,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, app, prefix):\n self.app = app\n self.prefix = prefix"} {"repo":"flask","file":"tests/test_basic.py","line":297,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, environ, start_response):\n environ[\"SCRIPT_NAME\"] = self.prefix\n return self.app(environ, start_response)"} {"repo":"flask","file":"tests/test_basic.py","line":305,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":313,"symbol":"test_session_using_session_settings","kind":"function","lang":"python","code":"def test_session_using_session_settings(app, client):\n app.config.update(\n SERVER_NAME=\"www.example.com:8080\",\n APPLICATION_ROOT=\"/test\",\n SESSION_COOKIE_DOMAIN=\".example.com\",\n SESSION_COOKIE_HTTPONLY=False,\n SESSION_COOKIE_SECURE=True,\n SESSION_COOKIE_PARTITIONED=True,\n SESSION_COOKIE_SAMESITE=\"Lax\",\n SESSION_COOKIE_PATH=\"/\",\n )\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n @app.route(\"/clear\")\n def clear():\n flask.session.pop(\"testing\", None)\n return \"Goodbye World\"\n\n rv = client.get(\"/\", \"http://www.example.com:8080/test/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n # or condition for Werkzeug < 2.3\n assert \"domain=example.com\" in cookie or \"domain=.example.com\" in cookie\n assert \"path=/\" in cookie\n assert \"secure\" in cookie\n assert \"httponly\" not in cookie\n assert \"samesite\" in cookie\n assert \"partitioned\" in cookie\n\n rv = client.get(\"/clear\", \"http://www.example.com:8080/test/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"session=;\" in cookie\n # or condition for Werkzeug < 2.3\n assert "} {"repo":"flask","file":"tests/test_basic.py","line":326,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":331,"symbol":"clear","kind":"function","lang":"python","code":"def clear():\n flask.session.pop(\"testing\", None)\n return \"Goodbye World\""} {"repo":"flask","file":"tests/test_basic.py","line":356,"symbol":"test_session_using_samesite_attribute","kind":"function","lang":"python","code":"def test_session_using_samesite_attribute(app, client):\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"invalid\")\n\n with pytest.raises(ValueError):\n client.get(\"/\")\n\n app.config.update(SESSION_COOKIE_SAMESITE=None)\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite\" not in cookie\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"Strict\")\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite=strict\" in cookie\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"Lax\")\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite=lax\" in cookie"} {"repo":"flask","file":"tests/test_basic.py","line":358,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\""} {"repo":"flask","file":"tests/test_basic.py","line":383,"symbol":"test_missing_session","kind":"function","lang":"python","code":"def test_missing_session(app):\n app.secret_key = None\n\n def expect_exception(f, *args, **kwargs):\n e = pytest.raises(RuntimeError, f, *args, **kwargs)\n assert e.value.args and \"session is unavailable\" in e.value.args[0]\n\n with app.test_request_context():\n assert flask.session.get(\"missing_key\") is None\n expect_exception(flask.session.__setitem__, \"foo\", 42)\n expect_exception(flask.session.pop, \"foo\")"} {"repo":"flask","file":"tests/test_basic.py","line":386,"symbol":"expect_exception","kind":"function","lang":"python","code":"def expect_exception(f, *args, **kwargs):\n e = pytest.raises(RuntimeError, f, *args, **kwargs)\n assert e.value.args and \"session is unavailable\" in e.value.args[0]"} {"repo":"flask","file":"tests/test_basic.py","line":396,"symbol":"test_session_secret_key_fallbacks","kind":"function","lang":"python","code":"def test_session_secret_key_fallbacks(app, client) -> None:\n @app.post(\"/\")\n def set_session() -> str:\n flask.session[\"a\"] = 1\n return \"\"\n\n @app.get(\"/\")\n def get_session() -> dict[str, t.Any]:\n return dict(flask.session)\n\n # Set session with initial secret key, and two valid expiring keys\n app.secret_key, app.config[\"SECRET_KEY_FALLBACKS\"] = (\n \"0 key\",\n [\"-1 key\", \"-2 key\"],\n )\n client.post()\n assert client.get().json == {\"a\": 1}\n # Change secret key, session can't be loaded and appears empty\n app.secret_key = \"? key\"\n assert client.get().json == {}\n # Rotate the valid keys, session can be loaded\n app.secret_key, app.config[\"SECRET_KEY_FALLBACKS\"] = (\n \"+1 key\",\n [\"0 key\", \"-1 key\"],\n )\n assert client.get().json == {\"a\": 1}"} {"repo":"flask","file":"tests/test_basic.py","line":398,"symbol":"set_session","kind":"function","lang":"python","code":"def set_session() -> str:\n flask.session[\"a\"] = 1\n return \"\""} {"repo":"flask","file":"tests/test_basic.py","line":403,"symbol":"get_session","kind":"function","lang":"python","code":"def get_session() -> dict[str, t.Any]:\n return dict(flask.session)"} {"repo":"flask","file":"tests/test_basic.py","line":424,"symbol":"test_session_expiration","kind":"function","lang":"python","code":"def test_session_expiration(app, client):\n permanent = True\n\n @app.route(\"/\")\n def index():\n flask.session[\"test\"] = 42\n flask.session.permanent = permanent\n return \"\"\n\n @app.route(\"/test\")\n def test():\n return str(flask.session.permanent)\n\n rv = client.get(\"/\")\n assert \"set-cookie\" in rv.headers\n match = re.search(r\"(?i)\\bexpires=([^;]+)\", rv.headers[\"set-cookie\"])\n expires = parse_date(match.group())\n expected = datetime.now(timezone.utc) + app.permanent_session_lifetime\n assert expires.year == expected.year\n assert expires.month == expected.month\n assert expires.day == expected.day\n\n rv = client.get(\"/test\")\n assert rv.data == b\"True\"\n\n permanent = False\n rv = client.get(\"/\")\n assert \"set-cookie\" in rv.headers\n match = re.search(r\"\\bexpires=([^;]+)\", rv.headers[\"set-cookie\"])\n assert match is None"} {"repo":"flask","file":"tests/test_basic.py","line":428,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"test\"] = 42\n flask.session.permanent = permanent\n return \"\""} {"repo":"flask","file":"tests/test_basic.py","line":434,"symbol":"test","kind":"function","lang":"python","code":"def test():\n return str(flask.session.permanent)"} {"repo":"flask","file":"tests/test_basic.py","line":456,"symbol":"test_session_stored_last","kind":"function","lang":"python","code":"def test_session_stored_last(app, client):\n @app.after_request\n def modify_session(response):\n flask.session[\"foo\"] = 42\n return response\n\n @app.route(\"/\")\n def dump_session_contents():\n return repr(flask.session.get(\"foo\"))\n\n assert client.get(\"/\").data == b\"None\"\n assert client.get(\"/\").data == b\"42\""} {"repo":"flask","file":"tests/test_basic.py","line":458,"symbol":"modify_session","kind":"function","lang":"python","code":"def modify_session(response):\n flask.session[\"foo\"] = 42\n return response"} {"repo":"flask","file":"tests/test_basic.py","line":463,"symbol":"dump_session_contents","kind":"function","lang":"python","code":"def dump_session_contents():\n return repr(flask.session.get(\"foo\"))"} {"repo":"flask","file":"tests/test_basic.py","line":470,"symbol":"test_session_special_types","kind":"function","lang":"python","code":"def test_session_special_types(app, client):\n now = datetime.now(timezone.utc).replace(microsecond=0)\n the_uuid = uuid.uuid4()\n\n @app.route(\"/\")\n def dump_session_contents():\n flask.session[\"t\"] = (1, 2, 3)\n flask.session[\"b\"] = b\"\\xff\"\n flask.session[\"m\"] = Markup(\"\")\n flask.session[\"u\"] = the_uuid\n flask.session[\"d\"] = now\n flask.session[\"t_tag\"] = {\" t\": \"not-a-tuple\"}\n flask.session[\"di_t_tag\"] = {\" t__\": \"not-a-tuple\"}\n flask.session[\"di_tag\"] = {\" di\": \"not-a-dict\"}\n return \"\", 204\n\n with client:\n client.get(\"/\")\n s = flask.session\n assert s[\"t\"] == (1, 2, 3)\n assert type(s[\"b\"]) is bytes # noqa: E721\n assert s[\"b\"] == b\"\\xff\"\n assert type(s[\"m\"]) is Markup # noqa: E721\n assert s[\"m\"] == Markup(\"\")\n assert s[\"u\"] == the_uuid\n assert s[\"d\"] == now\n assert s[\"t_tag\"] == {\" t\": \"not-a-tuple\"}\n assert s[\"di_t_tag\"] == {\" t__\": \"not-a-tuple\"}\n assert s[\"di_tag\"] == {\" di\": \"not-a-dict\"}"} {"repo":"flask","file":"tests/test_basic.py","line":475,"symbol":"dump_session_contents","kind":"function","lang":"python","code":"def dump_session_contents():\n flask.session[\"t\"] = (1, 2, 3)\n flask.session[\"b\"] = b\"\\xff\"\n flask.session[\"m\"] = Markup(\"\")\n flask.session[\"u\"] = the_uuid\n flask.session[\"d\"] = now\n flask.session[\"t_tag\"] = {\" t\": \"not-a-tuple\"}\n flask.session[\"di_t_tag\"] = {\" t__\": \"not-a-tuple\"}\n flask.session[\"di_tag\"] = {\" di\": \"not-a-dict\"}\n return \"\", 204"} {"repo":"flask","file":"tests/test_basic.py","line":501,"symbol":"test_session_cookie_setting","kind":"function","lang":"python","code":"def test_session_cookie_setting(app):\n is_permanent = True\n\n @app.route(\"/bump\")\n def bump():\n rv = flask.session[\"foo\"] = flask.session.get(\"foo\", 0) + 1\n flask.session.permanent = is_permanent\n return str(rv)\n\n @app.route(\"/read\")\n def read():\n return str(flask.session.get(\"foo\", 0))\n\n def run_test(expect_header):\n with app.test_client() as c:\n assert c.get(\"/bump\").data == b\"1\"\n assert c.get(\"/bump\").data == b\"2\"\n assert c.get(\"/bump\").data == b\"3\"\n\n rv = c.get(\"/read\")\n set_cookie = rv.headers.get(\"set-cookie\")\n assert (set_cookie is not None) == expect_header\n assert rv.data == b\"3\"\n\n is_permanent = True\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = True\n run_test(expect_header=True)\n\n is_permanent = True\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = False\n run_test(expect_header=False)\n\n is_permanent = False\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = True\n run_test(expect_header=False)\n\n is_permanent = False\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = False\n run_test(expect_header=False)"} {"repo":"flask","file":"tests/test_blueprints.py","line":7,"symbol":"test_blueprint_specific_error_handling","kind":"function","lang":"python","code":"def test_blueprint_specific_error_handling(app, client):\n frontend = flask.Blueprint(\"frontend\", __name__)\n backend = flask.Blueprint(\"backend\", __name__)\n sideend = flask.Blueprint(\"sideend\", __name__)\n\n @frontend.errorhandler(403)\n def frontend_forbidden(e):\n return \"frontend says no\", 403\n\n @frontend.route(\"/frontend-no\")\n def frontend_no():\n flask.abort(403)\n\n @backend.errorhandler(403)\n def backend_forbidden(e):\n return \"backend says no\", 403\n\n @backend.route(\"/backend-no\")\n def backend_no():\n flask.abort(403)\n\n @sideend.route(\"/what-is-a-sideend\")\n def sideend_no():\n flask.abort(403)\n\n app.register_blueprint(frontend)\n app.register_blueprint(backend)\n app.register_blueprint(sideend)\n\n @app.errorhandler(403)\n def app_forbidden(e):\n return \"application itself says no\", 403\n\n assert client.get(\"/frontend-no\").data == b\"frontend says no\"\n assert client.get(\"/backend-no\").data == b\"backend says no\"\n assert client.get(\"/what-is-a-sideend\").data == b\"application itself says no\""} {"repo":"flask","file":"tests/test_blueprints.py","line":13,"symbol":"frontend_forbidden","kind":"function","lang":"python","code":"def frontend_forbidden(e):\n return \"frontend says no\", 403"} {"repo":"flask","file":"tests/test_blueprints.py","line":17,"symbol":"frontend_no","kind":"function","lang":"python","code":"def frontend_no():\n flask.abort(403)"} {"repo":"flask","file":"tests/test_blueprints.py","line":21,"symbol":"backend_forbidden","kind":"function","lang":"python","code":"def backend_forbidden(e):\n return \"backend says no\", 403"} {"repo":"flask","file":"tests/test_blueprints.py","line":25,"symbol":"backend_no","kind":"function","lang":"python","code":"def backend_no():\n flask.abort(403)"} {"repo":"flask","file":"tests/test_blueprints.py","line":29,"symbol":"sideend_no","kind":"function","lang":"python","code":"def sideend_no():\n flask.abort(403)"} {"repo":"flask","file":"tests/test_blueprints.py","line":37,"symbol":"app_forbidden","kind":"function","lang":"python","code":"def app_forbidden(e):\n return \"application itself says no\", 403"} {"repo":"flask","file":"tests/test_blueprints.py","line":45,"symbol":"test_blueprint_specific_user_error_handling","kind":"function","lang":"python","code":"def test_blueprint_specific_user_error_handling(app, client):\n class MyDecoratorException(Exception):\n pass\n\n class MyFunctionException(Exception):\n pass\n\n blue = flask.Blueprint(\"blue\", __name__)\n\n @blue.errorhandler(MyDecoratorException)\n def my_decorator_exception_handler(e):\n assert isinstance(e, MyDecoratorException)\n return \"boom\"\n\n def my_function_exception_handler(e):\n assert isinstance(e, MyFunctionException)\n return \"bam\"\n\n blue.register_error_handler(MyFunctionException, my_function_exception_handler)\n\n @blue.route(\"/decorator\")\n def blue_deco_test():\n raise MyDecoratorException()\n\n @blue.route(\"/function\")\n def blue_func_test():\n raise MyFunctionException()\n\n app.register_blueprint(blue)\n\n assert client.get(\"/decorator\").data == b\"boom\"\n assert client.get(\"/function\").data == b\"bam\""} {"repo":"flask","file":"tests/test_blueprints.py","line":46,"symbol":"MyDecoratorException","kind":"class","lang":"python","code":"class MyDecoratorException(Exception):\n pass"} {"repo":"flask","file":"tests/test_blueprints.py","line":49,"symbol":"MyFunctionException","kind":"class","lang":"python","code":"class MyFunctionException(Exception):\n pass"} {"repo":"flask","file":"tests/test_blueprints.py","line":55,"symbol":"my_decorator_exception_handler","kind":"function","lang":"python","code":"def my_decorator_exception_handler(e):\n assert isinstance(e, MyDecoratorException)\n return \"boom\""} {"repo":"flask","file":"tests/test_blueprints.py","line":59,"symbol":"my_function_exception_handler","kind":"function","lang":"python","code":"def my_function_exception_handler(e):\n assert isinstance(e, MyFunctionException)\n return \"bam\""} {"repo":"flask","file":"tests/test_blueprints.py","line":66,"symbol":"blue_deco_test","kind":"function","lang":"python","code":"def blue_deco_test():\n raise MyDecoratorException()"} {"repo":"flask","file":"tests/test_blueprints.py","line":70,"symbol":"blue_func_test","kind":"function","lang":"python","code":"def blue_func_test():\n raise MyFunctionException()"} {"repo":"flask","file":"tests/test_blueprints.py","line":79,"symbol":"test_blueprint_app_error_handling","kind":"function","lang":"python","code":"def test_blueprint_app_error_handling(app, client):\n errors = flask.Blueprint(\"errors\", __name__)\n\n @errors.app_errorhandler(403)\n def forbidden_handler(e):\n return \"you shall not pass\", 403\n\n @app.route(\"/forbidden\")\n def app_forbidden():\n flask.abort(403)\n\n forbidden_bp = flask.Blueprint(\"forbidden_bp\", __name__)\n\n @forbidden_bp.route(\"/nope\")\n def bp_forbidden():\n flask.abort(403)\n\n app.register_blueprint(errors)\n app.register_blueprint(forbidden_bp)\n\n assert client.get(\"/forbidden\").data == b\"you shall not pass\"\n assert client.get(\"/nope\").data == b\"you shall not pass\""} {"repo":"flask","file":"tests/test_blueprints.py","line":83,"symbol":"forbidden_handler","kind":"function","lang":"python","code":"def forbidden_handler(e):\n return \"you shall not pass\", 403"} {"repo":"flask","file":"tests/test_blueprints.py","line":87,"symbol":"app_forbidden","kind":"function","lang":"python","code":"def app_forbidden():\n flask.abort(403)"} {"repo":"flask","file":"tests/test_blueprints.py","line":93,"symbol":"bp_forbidden","kind":"function","lang":"python","code":"def bp_forbidden():\n flask.abort(403)"} {"repo":"flask","file":"tests/test_blueprints.py","line":119,"symbol":"test_blueprint_prefix_slash","kind":"function","lang":"python","code":"def test_blueprint_prefix_slash(app, client, prefix, rule, url):\n bp = flask.Blueprint(\"test\", __name__, url_prefix=prefix)\n\n @bp.route(rule)\n def index():\n return \"\", 204\n\n app.register_blueprint(bp)\n assert client.get(url).status_code == 204"} {"repo":"flask","file":"tests/test_blueprints.py","line":123,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"\", 204"} {"repo":"flask","file":"tests/test_blueprints.py","line":130,"symbol":"test_blueprint_url_defaults","kind":"function","lang":"python","code":"def test_blueprint_url_defaults(app, client):\n bp = flask.Blueprint(\"test\", __name__)\n\n @bp.route(\"/foo\", defaults={\"baz\": 42})\n def foo(bar, baz):\n return f\"{bar}/{baz:d}\"\n\n @bp.route(\"/bar\")\n def bar(bar):\n return str(bar)\n\n app.register_blueprint(bp, url_prefix=\"/1\", url_defaults={\"bar\": 23})\n app.register_blueprint(bp, name=\"test2\", url_prefix=\"/2\", url_defaults={\"bar\": 19})\n\n assert client.get(\"/1/foo\").data == b\"23/42\"\n assert client.get(\"/2/foo\").data == b\"19/42\"\n assert client.get(\"/1/bar\").data == b\"23\"\n assert client.get(\"/2/bar\").data == b\"19\""} {"repo":"flask","file":"tests/test_blueprints.py","line":134,"symbol":"foo","kind":"function","lang":"python","code":"def foo(bar, baz):\n return f\"{bar}/{baz:d}\""} {"repo":"flask","file":"tests/test_blueprints.py","line":138,"symbol":"bar","kind":"function","lang":"python","code":"def bar(bar):\n return str(bar)"} {"repo":"flask","file":"tests/test_blueprints.py","line":150,"symbol":"test_blueprint_url_processors","kind":"function","lang":"python","code":"def test_blueprint_url_processors(app, client):\n bp = flask.Blueprint(\"frontend\", __name__, url_prefix=\"/\")\n\n @bp.url_defaults\n def add_language_code(endpoint, values):\n values.setdefault(\"lang_code\", flask.g.lang_code)\n\n @bp.url_value_preprocessor\n def pull_lang_code(endpoint, values):\n flask.g.lang_code = values.pop(\"lang_code\")\n\n @bp.route(\"/\")\n def index():\n return flask.url_for(\".about\")\n\n @bp.route(\"/about\")\n def about():\n return flask.url_for(\".index\")\n\n app.register_blueprint(bp)\n\n assert client.get(\"/de/\").data == b\"/de/about\"\n assert client.get(\"/de/about\").data == b\"/de/\""} {"repo":"flask","file":"tests/test_blueprints.py","line":154,"symbol":"add_language_code","kind":"function","lang":"python","code":"def add_language_code(endpoint, values):\n values.setdefault(\"lang_code\", flask.g.lang_code)"} {"repo":"flask","file":"tests/test_blueprints.py","line":158,"symbol":"pull_lang_code","kind":"function","lang":"python","code":"def pull_lang_code(endpoint, values):\n flask.g.lang_code = values.pop(\"lang_code\")"} {"repo":"flask","file":"tests/test_blueprints.py","line":162,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.url_for(\".about\")"} {"repo":"flask","file":"tests/test_blueprints.py","line":166,"symbol":"about","kind":"function","lang":"python","code":"def about():\n return flask.url_for(\".index\")"} {"repo":"flask","file":"tests/test_blueprints.py","line":175,"symbol":"test_templates_and_static","kind":"function","lang":"python","code":"def test_templates_and_static(test_apps):\n from blueprintapp import app\n\n client = app.test_client()\n\n rv = client.get(\"/\")\n assert rv.data == b\"Hello from the Frontend\"\n rv = client.get(\"/admin/\")\n assert rv.data == b\"Hello from the Admin\"\n rv = client.get(\"/admin/index2\")\n assert rv.data == b\"Hello from the Admin\"\n\n with client.get(\"/admin/static/test.txt\") as rv:\n assert rv.data.strip() == b\"Admin File\"\n\n with client.get(\"/admin/static/css/test.css\") as rv:\n assert rv.data.strip() == b\"/* nested file */\"\n\n # try/finally, in case other tests use this app for Blueprint tests.\n max_age_default = app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n try:\n expected_max_age = 3600\n if app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] == expected_max_age:\n expected_max_age = 7200\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = expected_max_age\n\n with client.get(\"/admin/static/css/test.css\") as rv:\n assert rv.cache_control.max_age == expected_max_age\n finally:\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = max_age_default\n\n with app.test_request_context():\n assert (\n flask.url_for(\"admi"} {"repo":"flask","file":"tests/test_blueprints.py","line":221,"symbol":"test_default_static_max_age","kind":"function","lang":"python","code":"def test_default_static_max_age(app: flask.Flask) -> None:\n class MyBlueprint(flask.Blueprint):\n def get_send_file_max_age(self, filename):\n return 100\n\n blueprint = MyBlueprint(\n \"blueprint\", __name__, url_prefix=\"/bp\", static_folder=\"static\"\n )\n app.register_blueprint(blueprint)\n\n with app.test_request_context(), blueprint.send_static_file(\"index.html\") as rv:\n assert rv.cache_control.max_age == 100"} {"repo":"flask","file":"tests/test_blueprints.py","line":222,"symbol":"MyBlueprint","kind":"class","lang":"python","code":"class MyBlueprint(flask.Blueprint):\n def get_send_file_max_age(self, filename):\n return 100"} {"repo":"flask","file":"tests/test_blueprints.py","line":223,"symbol":"get_send_file_max_age","kind":"function","lang":"python","code":"def get_send_file_max_age(self, filename):\n return 100"} {"repo":"flask","file":"tests/test_blueprints.py","line":235,"symbol":"test_templates_list","kind":"function","lang":"python","code":"def test_templates_list(test_apps):\n from blueprintapp import app\n\n templates = sorted(app.jinja_env.list_templates())\n assert templates == [\"admin/index.html\", \"frontend/index.html\"]"} {"repo":"flask","file":"tests/test_blueprints.py","line":242,"symbol":"test_dotted_name_not_allowed","kind":"function","lang":"python","code":"def test_dotted_name_not_allowed(app, client):\n with pytest.raises(ValueError):\n flask.Blueprint(\"app.ui\", __name__)"} {"repo":"flask","file":"tests/test_blueprints.py","line":247,"symbol":"test_empty_name_not_allowed","kind":"function","lang":"python","code":"def test_empty_name_not_allowed(app, client):\n with pytest.raises(ValueError):\n flask.Blueprint(\"\", __name__)"} {"repo":"flask","file":"tests/test_blueprints.py","line":252,"symbol":"test_dotted_names_from_app","kind":"function","lang":"python","code":"def test_dotted_names_from_app(app, client):\n test = flask.Blueprint(\"test\", __name__)\n\n @app.route(\"/\")\n def app_index():\n return flask.url_for(\"test.index\")\n\n @test.route(\"/test/\")\n def index():\n return flask.url_for(\"app_index\")\n\n app.register_blueprint(test)\n\n rv = client.get(\"/\")\n assert rv.data == b\"/test/\""} {"repo":"flask","file":"tests/test_blueprints.py","line":256,"symbol":"app_index","kind":"function","lang":"python","code":"def app_index():\n return flask.url_for(\"test.index\")"} {"repo":"flask","file":"tests/test_blueprints.py","line":260,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.url_for(\"app_index\")"} {"repo":"flask","file":"tests/test_blueprints.py","line":269,"symbol":"test_empty_url_defaults","kind":"function","lang":"python","code":"def test_empty_url_defaults(app, client):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.route(\"/\", defaults={\"page\": 1})\n @bp.route(\"/page/\")\n def something(page):\n return str(page)\n\n app.register_blueprint(bp)\n\n assert client.get(\"/\").data == b\"1\"\n assert client.get(\"/page/2\").data == b\"2\""} {"repo":"flask","file":"tests/test_blueprints.py","line":274,"symbol":"something","kind":"function","lang":"python","code":"def something(page):\n return str(page)"} {"repo":"flask","file":"tests/test_blueprints.py","line":283,"symbol":"test_route_decorator_custom_endpoint","kind":"function","lang":"python","code":"def test_route_decorator_custom_endpoint(app, client):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.route(\"/foo\")\n def foo():\n return flask.request.endpoint\n\n @bp.route(\"/bar\", endpoint=\"bar\")\n def foo_bar():\n return flask.request.endpoint\n\n @bp.route(\"/bar/123\", endpoint=\"123\")\n def foo_bar_foo():\n return flask.request.endpoint\n\n @bp.route(\"/bar/foo\")\n def bar_foo():\n return flask.request.endpoint\n\n app.register_blueprint(bp, url_prefix=\"/py\")\n\n @app.route(\"/\")\n def index():\n return flask.request.endpoint\n\n assert client.get(\"/\").data == b\"index\"\n assert client.get(\"/py/foo\").data == b\"bp.foo\"\n assert client.get(\"/py/bar\").data == b\"bp.bar\"\n assert client.get(\"/py/bar/123\").data == b\"bp.123\"\n assert client.get(\"/py/bar/foo\").data == b\"bp.bar_foo\""} {"repo":"flask","file":"tests/test_blueprints.py","line":287,"symbol":"foo","kind":"function","lang":"python","code":"def foo():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":291,"symbol":"foo_bar","kind":"function","lang":"python","code":"def foo_bar():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":295,"symbol":"foo_bar_foo","kind":"function","lang":"python","code":"def foo_bar_foo():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":299,"symbol":"bar_foo","kind":"function","lang":"python","code":"def bar_foo():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":305,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":315,"symbol":"test_route_decorator_custom_endpoint_with_dots","kind":"function","lang":"python","code":"def test_route_decorator_custom_endpoint_with_dots(app, client):\n bp = flask.Blueprint(\"bp\", __name__)\n\n with pytest.raises(ValueError):\n bp.route(\"/\", endpoint=\"a.b\")(lambda: \"\")\n\n with pytest.raises(ValueError):\n bp.add_url_rule(\"/\", endpoint=\"a.b\")\n\n def view():\n return \"\"\n\n view.__name__ = \"a.b\"\n\n with pytest.raises(ValueError):\n bp.add_url_rule(\"/\", view_func=view)"} {"repo":"flask","file":"tests/test_blueprints.py","line":324,"symbol":"view","kind":"function","lang":"python","code":"def view():\n return \"\""} {"repo":"flask","file":"tests/test_blueprints.py","line":333,"symbol":"test_endpoint_decorator","kind":"function","lang":"python","code":"def test_endpoint_decorator(app, client):\n from werkzeug.routing import Rule\n\n app.url_map.add(Rule(\"/foo\", endpoint=\"bar\"))\n\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.endpoint(\"bar\")\n def foobar():\n return flask.request.endpoint\n\n app.register_blueprint(bp, url_prefix=\"/bp_prefix\")\n\n assert client.get(\"/foo\").data == b\"bar\"\n assert client.get(\"/bp_prefix/bar\").status_code == 404"} {"repo":"flask","file":"tests/test_blueprints.py","line":341,"symbol":"foobar","kind":"function","lang":"python","code":"def foobar():\n return flask.request.endpoint"} {"repo":"flask","file":"tests/test_blueprints.py","line":350,"symbol":"test_template_filter","kind":"function","lang":"python","code":"def test_template_filter(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.app_template_filter()\n def my_reverse(s):\n return s[::-1]\n\n @bp.app_template_filter\n def my_reverse_2(s):\n return s[::-1]\n\n @bp.app_template_filter(\"my_reverse_custom_name_3\")\n def my_reverse_3(s):\n return s[::-1]\n\n @bp.app_template_filter(name=\"my_reverse_custom_name_4\")\n def my_reverse_4(s):\n return s[::-1]\n\n app.register_blueprint(bp, url_prefix=\"/py\")\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\"\n\n assert \"my_reverse_2\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse_2\"] == my_reverse_2\n assert app.jinja_env.filters[\"my_reverse_2\"](\"abcd\") == \"dcba\"\n\n assert \"my_reverse_custom_name_3\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse_custom_name_3\"] == my_reverse_3\n assert app.jinja_env.filters[\"my_reverse_custom_name_3\"](\"abcd\") == \"dcba\"\n\n assert \"my_reverse_custom_name_4\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_r"} {"repo":"flask","file":"tests/test_blueprints.py","line":354,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":358,"symbol":"my_reverse_2","kind":"function","lang":"python","code":"def my_reverse_2(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":362,"symbol":"my_reverse_3","kind":"function","lang":"python","code":"def my_reverse_3(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":366,"symbol":"my_reverse_4","kind":"function","lang":"python","code":"def my_reverse_4(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":387,"symbol":"test_add_template_filter","kind":"function","lang":"python","code":"def test_add_template_filter(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n def my_reverse(s):\n return s[::-1]\n\n bp.add_app_template_filter(my_reverse)\n app.register_blueprint(bp, url_prefix=\"/py\")\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_blueprints.py","line":390,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":400,"symbol":"test_template_filter_with_name","kind":"function","lang":"python","code":"def test_template_filter_with_name(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.app_template_filter(\"strrev\")\n def my_reverse(s):\n return s[::-1]\n\n app.register_blueprint(bp, url_prefix=\"/py\")\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_blueprints.py","line":404,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_blueprints.py","line":413,"symbol":"test_add_template_filter_with_name","kind":"function","lang":"python","code":"def test_add_template_filter_with_name(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n def my_reverse(s):\n return s[::-1]\n\n bp.add_app_template_filter(my_reverse, \"strrev\")\n app.register_blueprint(bp, url_prefix=\"/py\")\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_cli.py","line":36,"symbol":"runner","kind":"function","lang":"python","code":"def runner():\n return CliRunner()"} {"repo":"flask","file":"tests/test_cli.py","line":40,"symbol":"test_cli_name","kind":"function","lang":"python","code":"def test_cli_name(test_apps):\n \"\"\"Make sure the CLI object's name is the app's name and not the app itself\"\"\"\n from cliapp.app import testapp\n\n assert testapp.cli.name == testapp.name"} {"repo":"flask","file":"tests/test_cli.py","line":47,"symbol":"test_find_best_app","kind":"function","lang":"python","code":"def test_find_best_app(test_apps):\n class Module:\n app = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.app\n\n class Module:\n application = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.application\n\n class Module:\n myapp = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.myapp\n\n class Module:\n @staticmethod\n def create_app():\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n @staticmethod\n def create_app(**kwargs):\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n @staticmethod\n def make_app():\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n myapp = Flask(\"appname1\")\n\n @staticmethod\n def create_app():\n return Flask(\"appname2\")\n\n assert find_best_app(Module) == Module.myapp\n\n class Module:\n myapp = Flask(\"appnam"} {"repo":"flask","file":"tests/test_cli.py","line":48,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n app = Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":53,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n application = Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":58,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n myapp = Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":63,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n @staticmethod\n def create_app():\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":65,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":72,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n @staticmethod\n def create_app(**kwargs):\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":74,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app(**kwargs):\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":81,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n @staticmethod\n def make_app():\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":83,"symbol":"make_app","kind":"function","lang":"python","code":"def make_app():\n return Flask(\"appname\")"} {"repo":"flask","file":"tests/test_cli.py","line":90,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n myapp = Flask(\"appname1\")\n\n @staticmethod\n def create_app():\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":94,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":99,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n myapp = Flask(\"appname1\")\n\n @staticmethod\n def create_app():\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":103,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":108,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n pass"} {"repo":"flask","file":"tests/test_cli.py","line":113,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n myapp1 = Flask(\"appname1\")\n myapp2 = Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":119,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n @staticmethod\n def create_app(foo, bar):\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":121,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app(foo, bar):\n return Flask(\"appname2\")"} {"repo":"flask","file":"tests/test_cli.py","line":126,"symbol":"Module","kind":"class","lang":"python","code":"class Module:\n @staticmethod\n def create_app():\n raise TypeError(\"bad bad factory!\")"} {"repo":"flask","file":"tests/test_cli.py","line":128,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n raise TypeError(\"bad bad factory!\")"} {"repo":"flask","file":"tests/test_cli.py","line":160,"symbol":"test_prepare_import","kind":"function","lang":"python","code":"def test_prepare_import(request, value, path, result):\n \"\"\"Expect the correct path to be set and the correct import and app names\n to be returned.\n\n :func:`prepare_exec_for_file` has a side effect where the parent directory\n of the given import is added to :data:`sys.path`. This is reset after the\n test runs.\n \"\"\"\n original_path = sys.path[:]\n\n def reset_path():\n sys.path[:] = original_path\n\n request.addfinalizer(reset_path)\n\n assert prepare_import(value) == result\n assert sys.path[0] == str(path)"} {"repo":"flask","file":"tests/test_cli.py","line":170,"symbol":"reset_path","kind":"function","lang":"python","code":"def reset_path():\n sys.path[:] = original_path"} {"repo":"flask","file":"tests/test_cli.py","line":194,"symbol":"test_locate_app","kind":"function","lang":"python","code":"def test_locate_app(test_apps, iname, aname, result):\n assert locate_app(iname, aname).name == result"} {"repo":"flask","file":"tests/test_cli.py","line":216,"symbol":"test_locate_app_raises","kind":"function","lang":"python","code":"def test_locate_app_raises(test_apps, iname, aname):\n with pytest.raises(NoAppException):\n locate_app(iname, aname)"} {"repo":"flask","file":"tests/test_cli.py","line":221,"symbol":"test_locate_app_suppress_raise","kind":"function","lang":"python","code":"def test_locate_app_suppress_raise(test_apps):\n app = locate_app(\"notanapp.py\", None, raise_if_not_found=False)\n assert app is None\n\n # only direct import error is suppressed\n with pytest.raises(NoAppException):\n locate_app(\"cliapp.importerrorapp\", None, raise_if_not_found=False)"} {"repo":"flask","file":"tests/test_cli.py","line":230,"symbol":"test_get_version","kind":"function","lang":"python","code":"def test_get_version(test_apps, capsys):\n class MockCtx:\n resilient_parsing = False\n color = None\n\n def exit(self):\n return\n\n ctx = MockCtx()\n get_version(ctx, None, \"test\")\n out, err = capsys.readouterr()\n assert f\"Python {platform.python_version()}\" in out\n assert f\"Flask {importlib.metadata.version('flask')}\" in out\n assert f\"Werkzeug {importlib.metadata.version('werkzeug')}\" in out"} {"repo":"flask","file":"tests/test_cli.py","line":231,"symbol":"MockCtx","kind":"class","lang":"python","code":"class MockCtx:\n resilient_parsing = False\n color = None\n\n def exit(self):\n return"} {"repo":"flask","file":"tests/test_cli.py","line":235,"symbol":"exit","kind":"function","lang":"python","code":"def exit(self):\n return"} {"repo":"flask","file":"tests/test_cli.py","line":246,"symbol":"test_scriptinfo","kind":"function","lang":"python","code":"def test_scriptinfo(test_apps, monkeypatch):\n obj = ScriptInfo(app_import_path=\"cliapp.app:testapp\")\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n\n # import app with module's absolute path\n cli_app_path = str(test_path / \"cliapp\" / \"app.py\")\n\n obj = ScriptInfo(app_import_path=cli_app_path)\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n obj = ScriptInfo(app_import_path=f\"{cli_app_path}:testapp\")\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n\n def create_app():\n return Flask(\"createapp\")\n\n obj = ScriptInfo(create_app=create_app)\n app = obj.load_app()\n assert app.name == \"createapp\"\n assert obj.load_app() is app\n\n obj = ScriptInfo()\n pytest.raises(NoAppException, obj.load_app)\n\n # import app from wsgi.py in current directory\n monkeypatch.chdir(test_path / \"helloworld\")\n obj = ScriptInfo()\n app = obj.load_app()\n assert app.name == \"hello\"\n\n # import app from app.py in current directory\n monkeypatch.chdir(test_path / \"cliapp\")\n obj = ScriptInfo()\n app = obj.load_app()\n assert app.n"} {"repo":"flask","file":"tests/test_cli.py","line":264,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"createapp\")"} {"repo":"flask","file":"tests/test_cli.py","line":288,"symbol":"test_app_cli_has_app_context","kind":"function","lang":"python","code":"def test_app_cli_has_app_context(app, runner):\n def _param_cb(ctx, param, value):\n # current_app should be available in parameter callbacks\n return bool(current_app)\n\n @app.cli.command()\n @click.argument(\"value\", callback=_param_cb)\n def check(value):\n app = click.get_current_context().obj.load_app()\n # the loaded app should be the same as current_app\n same_app = current_app._get_current_object() is app\n return same_app, value\n\n cli = FlaskGroup(create_app=lambda: app)\n result = runner.invoke(cli, [\"check\", \"x\"], standalone_mode=False)\n assert result.return_value == (True, True)"} {"repo":"flask","file":"tests/test_cli.py","line":289,"symbol":"_param_cb","kind":"function","lang":"python","code":"def _param_cb(ctx, param, value):\n # current_app should be available in parameter callbacks\n return bool(current_app)"} {"repo":"flask","file":"tests/test_cli.py","line":295,"symbol":"check","kind":"function","lang":"python","code":"def check(value):\n app = click.get_current_context().obj.load_app()\n # the loaded app should be the same as current_app\n same_app = current_app._get_current_object() is app\n return same_app, value"} {"repo":"flask","file":"tests/test_cli.py","line":306,"symbol":"test_with_appcontext","kind":"function","lang":"python","code":"def test_with_appcontext(runner):\n @click.command()\n @with_appcontext\n def testcmd():\n click.echo(current_app.name)\n\n obj = ScriptInfo(create_app=lambda: Flask(\"testapp\"))\n\n result = runner.invoke(testcmd, obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testapp\\n\""} {"repo":"flask","file":"tests/test_cli.py","line":309,"symbol":"testcmd","kind":"function","lang":"python","code":"def testcmd():\n click.echo(current_app.name)"} {"repo":"flask","file":"tests/test_cli.py","line":319,"symbol":"test_appgroup_app_context","kind":"function","lang":"python","code":"def test_appgroup_app_context(runner):\n @click.group(cls=AppGroup)\n def cli():\n pass\n\n @cli.command()\n def test():\n click.echo(current_app.name)\n\n @cli.group()\n def subgroup():\n pass\n\n @subgroup.command()\n def test2():\n click.echo(current_app.name)\n\n obj = ScriptInfo(create_app=lambda: Flask(\"testappgroup\"))\n\n result = runner.invoke(cli, [\"test\"], obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testappgroup\\n\"\n\n result = runner.invoke(cli, [\"subgroup\", \"test2\"], obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testappgroup\\n\""} {"repo":"flask","file":"tests/test_cli.py","line":321,"symbol":"cli","kind":"function","lang":"python","code":"def cli():\n pass"} {"repo":"flask","file":"tests/test_cli.py","line":325,"symbol":"test","kind":"function","lang":"python","code":"def test():\n click.echo(current_app.name)"} {"repo":"flask","file":"tests/test_cli.py","line":329,"symbol":"subgroup","kind":"function","lang":"python","code":"def subgroup():\n pass"} {"repo":"flask","file":"tests/test_cli.py","line":333,"symbol":"test2","kind":"function","lang":"python","code":"def test2():\n click.echo(current_app.name)"} {"repo":"flask","file":"tests/test_cli.py","line":347,"symbol":"test_flaskgroup_app_context","kind":"function","lang":"python","code":"def test_flaskgroup_app_context(runner):\n def create_app():\n return Flask(\"flaskgroup\")\n\n @click.group(cls=FlaskGroup, create_app=create_app)\n def cli(**params):\n pass\n\n @cli.command()\n def test():\n click.echo(current_app.name)\n\n result = runner.invoke(cli, [\"test\"])\n assert result.exit_code == 0\n assert result.output == \"flaskgroup\\n\""} {"repo":"flask","file":"tests/test_cli.py","line":348,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n return Flask(\"flaskgroup\")"} {"repo":"flask","file":"tests/test_cli.py","line":352,"symbol":"cli","kind":"function","lang":"python","code":"def cli(**params):\n pass"} {"repo":"flask","file":"tests/test_cli.py","line":356,"symbol":"test","kind":"function","lang":"python","code":"def test():\n click.echo(current_app.name)"} {"repo":"flask","file":"tests/test_cli.py","line":365,"symbol":"test_flaskgroup_debug","kind":"function","lang":"python","code":"def test_flaskgroup_debug(runner, set_debug_flag):\n def create_app():\n app = Flask(\"flaskgroup\")\n app.debug = True\n return app\n\n @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)\n def cli(**params):\n pass\n\n @cli.command()\n def test():\n click.echo(str(current_app.debug))\n\n result = runner.invoke(cli, [\"test\"])\n assert result.exit_code == 0\n assert result.output == f\"{not set_debug_flag}\\n\""} {"repo":"flask","file":"tests/test_cli.py","line":366,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n app = Flask(\"flaskgroup\")\n app.debug = True\n return app"} {"repo":"flask","file":"tests/test_cli.py","line":372,"symbol":"cli","kind":"function","lang":"python","code":"def cli(**params):\n pass"} {"repo":"flask","file":"tests/test_cli.py","line":376,"symbol":"test","kind":"function","lang":"python","code":"def test():\n click.echo(str(current_app.debug))"} {"repo":"flask","file":"tests/test_cli.py","line":384,"symbol":"test_flaskgroup_nested","kind":"function","lang":"python","code":"def test_flaskgroup_nested(app, runner):\n cli = click.Group(\"cli\")\n flask_group = FlaskGroup(name=\"flask\", create_app=lambda: app)\n cli.add_command(flask_group)\n\n @flask_group.command()\n def show():\n click.echo(current_app.name)\n\n result = runner.invoke(cli, [\"flask\", \"show\"])\n assert result.output == \"flask_test\\n\""} {"repo":"flask","file":"tests/test_cli.py","line":390,"symbol":"show","kind":"function","lang":"python","code":"def show():\n click.echo(current_app.name)"} {"repo":"flask","file":"tests/test_cli.py","line":397,"symbol":"test_no_command_echo_loading_error","kind":"function","lang":"python","code":"def test_no_command_echo_loading_error():\n from flask.cli import cli\n\n try:\n runner = CliRunner(mix_stderr=False)\n except (DeprecationWarning, TypeError):\n # Click >= 8.2\n runner = CliRunner()\n\n result = runner.invoke(cli, [\"missing\"])\n assert result.exit_code == 2\n assert \"FLASK_APP\" in result.stderr\n assert \"Usage:\" in result.stderr"} {"repo":"flask","file":"tests/test_cli.py","line":412,"symbol":"test_help_echo_loading_error","kind":"function","lang":"python","code":"def test_help_echo_loading_error():\n from flask.cli import cli\n\n try:\n runner = CliRunner(mix_stderr=False)\n except (DeprecationWarning, TypeError):\n # Click >= 8.2\n runner = CliRunner()\n\n result = runner.invoke(cli, [\"--help\"])\n assert result.exit_code == 0\n assert \"FLASK_APP\" in result.stderr\n assert \"Usage:\" in result.stdout"} {"repo":"flask","file":"tests/test_cli.py","line":427,"symbol":"test_help_echo_exception","kind":"function","lang":"python","code":"def test_help_echo_exception():\n def create_app():\n raise Exception(\"oh no\")\n\n cli = FlaskGroup(create_app=create_app)\n\n try:\n runner = CliRunner(mix_stderr=False)\n except (DeprecationWarning, TypeError):\n # Click >= 8.2\n runner = CliRunner()\n\n result = runner.invoke(cli, [\"--help\"])\n assert result.exit_code == 0\n assert \"Exception: oh no\" in result.stderr\n assert \"Usage:\" in result.stdout"} {"repo":"flask","file":"tests/test_cli.py","line":428,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n raise Exception(\"oh no\")"} {"repo":"flask","file":"tests/test_cli.py","line":445,"symbol":"TestRoutes","kind":"class","lang":"python","code":"class TestRoutes:\n @pytest.fixture\n def app(self):\n app = Flask(__name__)\n app.add_url_rule(\n \"/get_post//\",\n methods=[\"GET\", \"POST\"],\n endpoint=\"yyy_get_post\",\n )\n app.add_url_rule(\"/zzz_post\", methods=[\"POST\"], endpoint=\"aaa_post\")\n return app\n\n @pytest.fixture\n def invoke(self, app, runner):\n cli = FlaskGroup(create_app=lambda: app)\n return partial(runner.invoke, cli)\n\n def expect_order(self, order, output):\n # skip the header and match the start of each row\n for expect, line in zip(order, output.splitlines()[2:], strict=False):\n # do this instead of startswith for nicer pytest output\n assert line[: len(expect)] == expect\n\n def test_simple(self, invoke):\n result = invoke([\"routes\"])\n assert result.exit_code == 0\n self.expect_order([\"aaa_post\", \"static\", \"yyy_get_post\"], result.output)\n\n def test_sort(self, app, invoke):\n default_output = invoke([\"routes\"]).output\n endpoint_output = invoke([\"routes\", \"-s\", \"endpoint\"]).output\n assert default_output == endpoint_output\n self.expect_o"} {"repo":"flask","file":"tests/test_cli.py","line":447,"symbol":"app","kind":"function","lang":"python","code":"def app(self):\n app = Flask(__name__)\n app.add_url_rule(\n \"/get_post//\",\n methods=[\"GET\", \"POST\"],\n endpoint=\"yyy_get_post\",\n )\n app.add_url_rule(\"/zzz_post\", methods=[\"POST\"], endpoint=\"aaa_post\")\n return app"} {"repo":"flask","file":"tests/test_cli.py","line":458,"symbol":"invoke","kind":"function","lang":"python","code":"def invoke(self, app, runner):\n cli = FlaskGroup(create_app=lambda: app)\n return partial(runner.invoke, cli)"} {"repo":"flask","file":"tests/test_cli.py","line":462,"symbol":"expect_order","kind":"function","lang":"python","code":"def expect_order(self, order, output):\n # skip the header and match the start of each row\n for expect, line in zip(order, output.splitlines()[2:], strict=False):\n # do this instead of startswith for nicer pytest output\n assert line[: len(expect)] == expect"} {"repo":"flask","file":"tests/test_config.py","line":13,"symbol":"common_object_test","kind":"function","lang":"python","code":"def common_object_test(app):\n assert app.secret_key == \"config\"\n assert app.config[\"TEST_KEY\"] == \"foo\"\n assert \"TestConfig\" not in app.config"} {"repo":"flask","file":"tests/test_config.py","line":19,"symbol":"test_config_from_pyfile","kind":"function","lang":"python","code":"def test_config_from_pyfile():\n app = flask.Flask(__name__)\n app.config.from_pyfile(f\"{__file__.rsplit('.', 1)[0]}.py\")\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":25,"symbol":"test_config_from_object","kind":"function","lang":"python","code":"def test_config_from_object():\n app = flask.Flask(__name__)\n app.config.from_object(__name__)\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":31,"symbol":"test_config_from_file_json","kind":"function","lang":"python","code":"def test_config_from_file_json():\n app = flask.Flask(__name__)\n current_dir = os.path.dirname(os.path.abspath(__file__))\n app.config.from_file(os.path.join(current_dir, \"static\", \"config.json\"), json.load)\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":38,"symbol":"test_config_from_file_toml","kind":"function","lang":"python","code":"def test_config_from_file_toml():\n tomllib = pytest.importorskip(\"tomllib\", reason=\"tomllib added in 3.11\")\n app = flask.Flask(__name__)\n current_dir = os.path.dirname(os.path.abspath(__file__))\n app.config.from_file(\n os.path.join(current_dir, \"static\", \"config.toml\"), tomllib.load, text=False\n )\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":48,"symbol":"test_from_prefixed_env","kind":"function","lang":"python","code":"def test_from_prefixed_env(monkeypatch):\n monkeypatch.setenv(\"FLASK_STRING\", \"value\")\n monkeypatch.setenv(\"FLASK_BOOL\", \"true\")\n monkeypatch.setenv(\"FLASK_INT\", \"1\")\n monkeypatch.setenv(\"FLASK_FLOAT\", \"1.2\")\n monkeypatch.setenv(\"FLASK_LIST\", \"[1, 2]\")\n monkeypatch.setenv(\"FLASK_DICT\", '{\"k\": \"v\"}')\n monkeypatch.setenv(\"NOT_FLASK_OTHER\", \"other\")\n\n app = flask.Flask(__name__)\n app.config.from_prefixed_env()\n\n assert app.config[\"STRING\"] == \"value\"\n assert app.config[\"BOOL\"] is True\n assert app.config[\"INT\"] == 1\n assert app.config[\"FLOAT\"] == 1.2\n assert app.config[\"LIST\"] == [1, 2]\n assert app.config[\"DICT\"] == {\"k\": \"v\"}\n assert \"OTHER\" not in app.config"} {"repo":"flask","file":"tests/test_config.py","line":69,"symbol":"test_from_prefixed_env_custom_prefix","kind":"function","lang":"python","code":"def test_from_prefixed_env_custom_prefix(monkeypatch):\n monkeypatch.setenv(\"FLASK_A\", \"a\")\n monkeypatch.setenv(\"NOT_FLASK_A\", \"b\")\n\n app = flask.Flask(__name__)\n app.config.from_prefixed_env(\"NOT_FLASK\")\n\n assert app.config[\"A\"] == \"b\""} {"repo":"flask","file":"tests/test_config.py","line":79,"symbol":"test_from_prefixed_env_nested","kind":"function","lang":"python","code":"def test_from_prefixed_env_nested(monkeypatch):\n monkeypatch.setenv(\"FLASK_EXIST__ok\", \"other\")\n monkeypatch.setenv(\"FLASK_EXIST__inner__ik\", \"2\")\n monkeypatch.setenv(\"FLASK_EXIST__new__more\", '{\"k\": false}')\n monkeypatch.setenv(\"FLASK_NEW__K\", \"v\")\n\n app = flask.Flask(__name__)\n app.config[\"EXIST\"] = {\"ok\": \"value\", \"flag\": True, \"inner\": {\"ik\": 1}}\n app.config.from_prefixed_env()\n\n if os.name != \"nt\":\n assert app.config[\"EXIST\"] == {\n \"ok\": \"other\",\n \"flag\": True,\n \"inner\": {\"ik\": 2},\n \"new\": {\"more\": {\"k\": False}},\n }\n else:\n # Windows env var keys are always uppercase.\n assert app.config[\"EXIST\"] == {\n \"ok\": \"value\",\n \"OK\": \"other\",\n \"flag\": True,\n \"inner\": {\"ik\": 1},\n \"INNER\": {\"IK\": 2},\n \"NEW\": {\"MORE\": {\"k\": False}},\n }\n\n assert app.config[\"NEW\"] == {\"K\": \"v\"}"} {"repo":"flask","file":"tests/test_config.py","line":110,"symbol":"test_config_from_mapping","kind":"function","lang":"python","code":"def test_config_from_mapping():\n app = flask.Flask(__name__)\n app.config.from_mapping({\"SECRET_KEY\": \"config\", \"TEST_KEY\": \"foo\"})\n common_object_test(app)\n\n app = flask.Flask(__name__)\n app.config.from_mapping([(\"SECRET_KEY\", \"config\"), (\"TEST_KEY\", \"foo\")])\n common_object_test(app)\n\n app = flask.Flask(__name__)\n app.config.from_mapping(SECRET_KEY=\"config\", TEST_KEY=\"foo\")\n common_object_test(app)\n\n app = flask.Flask(__name__)\n app.config.from_mapping(SECRET_KEY=\"config\", TEST_KEY=\"foo\", skip_key=\"skip\")\n common_object_test(app)\n\n app = flask.Flask(__name__)\n with pytest.raises(TypeError):\n app.config.from_mapping({}, {})"} {"repo":"flask","file":"tests/test_config.py","line":132,"symbol":"test_config_from_class","kind":"function","lang":"python","code":"def test_config_from_class():\n class Base:\n TEST_KEY = \"foo\"\n\n class Test(Base):\n SECRET_KEY = \"config\"\n\n app = flask.Flask(__name__)\n app.config.from_object(Test)\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":133,"symbol":"Base","kind":"class","lang":"python","code":"class Base:\n TEST_KEY = \"foo\""} {"repo":"flask","file":"tests/test_config.py","line":136,"symbol":"Test","kind":"class","lang":"python","code":"class Test(Base):\n SECRET_KEY = \"config\""} {"repo":"flask","file":"tests/test_config.py","line":144,"symbol":"test_config_from_envvar","kind":"function","lang":"python","code":"def test_config_from_envvar(monkeypatch):\n monkeypatch.setattr(\"os.environ\", {})\n app = flask.Flask(__name__)\n\n with pytest.raises(RuntimeError) as e:\n app.config.from_envvar(\"FOO_SETTINGS\")\n\n assert \"'FOO_SETTINGS' is not set\" in str(e.value)\n assert not app.config.from_envvar(\"FOO_SETTINGS\", silent=True)\n\n monkeypatch.setattr(\n \"os.environ\", {\"FOO_SETTINGS\": f\"{__file__.rsplit('.', 1)[0]}.py\"}\n )\n assert app.config.from_envvar(\"FOO_SETTINGS\")\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":161,"symbol":"test_config_from_envvar_missing","kind":"function","lang":"python","code":"def test_config_from_envvar_missing(monkeypatch):\n monkeypatch.setattr(\"os.environ\", {\"FOO_SETTINGS\": \"missing.cfg\"})\n app = flask.Flask(__name__)\n with pytest.raises(IOError) as e:\n app.config.from_envvar(\"FOO_SETTINGS\")\n msg = str(e.value)\n assert msg.startswith(\n \"[Errno 2] Unable to load configuration file (No such file or directory):\"\n )\n assert msg.endswith(\"missing.cfg'\")\n assert not app.config.from_envvar(\"FOO_SETTINGS\", silent=True)"} {"repo":"flask","file":"tests/test_config.py","line":174,"symbol":"test_config_missing","kind":"function","lang":"python","code":"def test_config_missing():\n app = flask.Flask(__name__)\n with pytest.raises(IOError) as e:\n app.config.from_pyfile(\"missing.cfg\")\n msg = str(e.value)\n assert msg.startswith(\n \"[Errno 2] Unable to load configuration file (No such file or directory):\"\n )\n assert msg.endswith(\"missing.cfg'\")\n assert not app.config.from_pyfile(\"missing.cfg\", silent=True)"} {"repo":"flask","file":"tests/test_config.py","line":186,"symbol":"test_config_missing_file","kind":"function","lang":"python","code":"def test_config_missing_file():\n app = flask.Flask(__name__)\n with pytest.raises(IOError) as e:\n app.config.from_file(\"missing.json\", load=json.load)\n msg = str(e.value)\n assert msg.startswith(\n \"[Errno 2] Unable to load configuration file (No such file or directory):\"\n )\n assert msg.endswith(\"missing.json'\")\n assert not app.config.from_file(\"missing.json\", load=json.load, silent=True)"} {"repo":"flask","file":"tests/test_config.py","line":198,"symbol":"test_custom_config_class","kind":"function","lang":"python","code":"def test_custom_config_class():\n class Config(flask.Config):\n pass\n\n class Flask(flask.Flask):\n config_class = Config\n\n app = Flask(__name__)\n assert isinstance(app.config, Config)\n app.config.from_object(__name__)\n common_object_test(app)"} {"repo":"flask","file":"tests/test_config.py","line":199,"symbol":"Config","kind":"class","lang":"python","code":"class Config(flask.Config):\n pass"} {"repo":"flask","file":"tests/test_config.py","line":202,"symbol":"Flask","kind":"class","lang":"python","code":"class Flask(flask.Flask):\n config_class = Config"} {"repo":"flask","file":"tests/test_config.py","line":211,"symbol":"test_session_lifetime","kind":"function","lang":"python","code":"def test_session_lifetime():\n app = flask.Flask(__name__)\n app.config[\"PERMANENT_SESSION_LIFETIME\"] = 42\n assert app.permanent_session_lifetime.seconds == 42"} {"repo":"flask","file":"tests/test_config.py","line":217,"symbol":"test_get_namespace","kind":"function","lang":"python","code":"def test_get_namespace():\n app = flask.Flask(__name__)\n app.config[\"FOO_OPTION_1\"] = \"foo option 1\"\n app.config[\"FOO_OPTION_2\"] = \"foo option 2\"\n app.config[\"BAR_STUFF_1\"] = \"bar stuff 1\"\n app.config[\"BAR_STUFF_2\"] = \"bar stuff 2\"\n foo_options = app.config.get_namespace(\"FOO_\")\n assert 2 == len(foo_options)\n assert \"foo option 1\" == foo_options[\"option_1\"]\n assert \"foo option 2\" == foo_options[\"option_2\"]\n bar_options = app.config.get_namespace(\"BAR_\", lowercase=False)\n assert 2 == len(bar_options)\n assert \"bar stuff 1\" == bar_options[\"STUFF_1\"]\n assert \"bar stuff 2\" == bar_options[\"STUFF_2\"]\n foo_options = app.config.get_namespace(\"FOO_\", trim_namespace=False)\n assert 2 == len(foo_options)\n assert \"foo option 1\" == foo_options[\"foo_option_1\"]\n assert \"foo option 2\" == foo_options[\"foo_option_2\"]\n bar_options = app.config.get_namespace(\n \"BAR_\", lowercase=False, trim_namespace=False\n )\n assert 2 == len(bar_options)\n assert \"bar stuff 1\" == bar_options[\"BAR_STUFF_1\"]\n assert \"bar stuff 2\" == bar_options[\"BAR_STUFF_2\"]"} {"repo":"flask","file":"tests/test_config.py","line":244,"symbol":"test_from_pyfile_weird_encoding","kind":"function","lang":"python","code":"def test_from_pyfile_weird_encoding(tmp_path, encoding):\n f = tmp_path / \"my_config.py\"\n f.write_text(f'# -*- coding: {encoding} -*-\\nTEST_VALUE = \"föö\"\\n', encoding)\n app = flask.Flask(__name__)\n app.config.from_pyfile(os.fspath(f))\n value = app.config[\"TEST_VALUE\"]\n assert value == \"föö\""} {"repo":"flask","file":"tests/test_converters.py","line":8,"symbol":"test_custom_converters","kind":"function","lang":"python","code":"def test_custom_converters(app, client):\n class ListConverter(BaseConverter):\n def to_python(self, value):\n return value.split(\",\")\n\n def to_url(self, value):\n base_to_url = super().to_url\n return \",\".join(base_to_url(x) for x in value)\n\n app.url_map.converters[\"list\"] = ListConverter\n\n @app.route(\"/\")\n def index(args):\n return \"|\".join(args)\n\n assert client.get(\"/1,2,3\").data == b\"1|2|3\"\n\n with app.test_request_context():\n assert url_for(\"index\", args=[4, 5, 6]) == \"/4,5,6\""} {"repo":"flask","file":"tests/test_converters.py","line":9,"symbol":"ListConverter","kind":"class","lang":"python","code":"class ListConverter(BaseConverter):\n def to_python(self, value):\n return value.split(\",\")\n\n def to_url(self, value):\n base_to_url = super().to_url\n return \",\".join(base_to_url(x) for x in value)"} {"repo":"flask","file":"tests/test_converters.py","line":10,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value):\n return value.split(\",\")"} {"repo":"flask","file":"tests/test_converters.py","line":13,"symbol":"to_url","kind":"function","lang":"python","code":"def to_url(self, value):\n base_to_url = super().to_url\n return \",\".join(base_to_url(x) for x in value)"} {"repo":"flask","file":"tests/test_converters.py","line":20,"symbol":"index","kind":"function","lang":"python","code":"def index(args):\n return \"|\".join(args)"} {"repo":"flask","file":"tests/test_converters.py","line":29,"symbol":"test_context_available","kind":"function","lang":"python","code":"def test_context_available(app, client):\n class ContextConverter(BaseConverter):\n def to_python(self, value):\n assert request is not None\n assert session is not None\n return value\n\n app.url_map.converters[\"ctx\"] = ContextConverter\n\n @app.get(\"/\")\n def index(name):\n return name\n\n assert client.get(\"/admin\").data == b\"admin\""} {"repo":"flask","file":"tests/test_converters.py","line":30,"symbol":"ContextConverter","kind":"class","lang":"python","code":"class ContextConverter(BaseConverter):\n def to_python(self, value):\n assert request is not None\n assert session is not None\n return value"} {"repo":"flask","file":"tests/test_converters.py","line":31,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value):\n assert request is not None\n assert session is not None\n return value"} {"repo":"flask","file":"tests/test_converters.py","line":39,"symbol":"index","kind":"function","lang":"python","code":"def index(name):\n return name"} {"repo":"flask","file":"tests/test_helpers.py","line":11,"symbol":"FakePath","kind":"class","lang":"python","code":"class FakePath:\n \"\"\"Fake object to represent a ``PathLike object``.\n\n This represents a ``pathlib.Path`` object in python 3.\n See: https://www.python.org/dev/peps/pep-0519/\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n\n def __fspath__(self):\n return self.path"} {"repo":"flask","file":"tests/test_helpers.py","line":18,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, path):\n self.path = path"} {"repo":"flask","file":"tests/test_helpers.py","line":21,"symbol":"__fspath__","kind":"function","lang":"python","code":"def __fspath__(self):\n return self.path"} {"repo":"flask","file":"tests/test_helpers.py","line":25,"symbol":"PyBytesIO","kind":"class","lang":"python","code":"class PyBytesIO:\n def __init__(self, *args, **kwargs):\n self._io = io.BytesIO(*args, **kwargs)\n\n def __getattr__(self, name):\n return getattr(self._io, name)"} {"repo":"flask","file":"tests/test_helpers.py","line":26,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, *args, **kwargs):\n self._io = io.BytesIO(*args, **kwargs)"} {"repo":"flask","file":"tests/test_helpers.py","line":29,"symbol":"__getattr__","kind":"function","lang":"python","code":"def __getattr__(self, name):\n return getattr(self._io, name)"} {"repo":"flask","file":"tests/test_helpers.py","line":33,"symbol":"TestSendfile","kind":"class","lang":"python","code":"class TestSendfile:\n def test_send_file(self, app, req_ctx):\n with app.open_resource(\"static/index.html\") as f:\n expect = f.read()\n\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.direct_passthrough\n assert rv.mimetype == \"text/html\"\n rv.direct_passthrough = False\n assert rv.data == expect\n\n def test_static_file(self, app, req_ctx):\n # Default max_age is None.\n\n # Test with static file handler.\n with app.send_static_file(\"index.html\") as rv:\n assert rv.cache_control.max_age is None\n\n # Test with direct use of send_file.\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.cache_control.max_age is None\n\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 3600\n\n # Test with static file handler.\n with app.send_static_file(\"index.html\") as rv:\n assert rv.cache_control.max_age == 3600\n\n # Test with direct use of send_file.\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.cache_control.max_age == 3600\n\n # Test with pathlib.Path.\n with app.send_static_file(FakePath("} {"repo":"flask","file":"tests/test_helpers.py","line":34,"symbol":"test_send_file","kind":"function","lang":"python","code":"def test_send_file(self, app, req_ctx):\n with app.open_resource(\"static/index.html\") as f:\n expect = f.read()\n\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.direct_passthrough\n assert rv.mimetype == \"text/html\"\n rv.direct_passthrough = False\n assert rv.data == expect"} {"repo":"flask","file":"tests/test_helpers.py","line":44,"symbol":"test_static_file","kind":"function","lang":"python","code":"def test_static_file(self, app, req_ctx):\n # Default max_age is None.\n\n # Test with static file handler.\n with app.send_static_file(\"index.html\") as rv:\n assert rv.cache_control.max_age is None\n\n # Test with direct use of send_file.\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.cache_control.max_age is None\n\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 3600\n\n # Test with static file handler.\n with app.send_static_file(\"index.html\") as rv:\n assert rv.cache_control.max_age == 3600\n\n # Test with direct use of send_file.\n with flask.send_file(\"static/index.html\") as rv:\n assert rv.cache_control.max_age == 3600\n\n # Test with pathlib.Path.\n with app.send_static_file(FakePath(\"index.html\")) as rv:\n assert rv.cache_control.max_age == 3600\n\n class StaticFileApp(flask.Flask):\n def get_send_file_max_age(self, filename):\n return 10\n\n app = StaticFileApp(__name__)\n\n with app.test_request_context():\n # Test with static file handler.\n with app.send_static_file(\"index.html\") as rv"} {"repo":"flask","file":"tests/test_helpers.py","line":69,"symbol":"StaticFileApp","kind":"class","lang":"python","code":"class StaticFileApp(flask.Flask):\n def get_send_file_max_age(self, filename):\n return 10"} {"repo":"flask","file":"tests/test_helpers.py","line":70,"symbol":"get_send_file_max_age","kind":"function","lang":"python","code":"def get_send_file_max_age(self, filename):\n return 10"} {"repo":"flask","file":"tests/test_helpers.py","line":84,"symbol":"test_send_from_directory","kind":"function","lang":"python","code":"def test_send_from_directory(self, app, req_ctx):\n app.root_path = os.path.join(\n os.path.dirname(__file__), \"test_apps\", \"subdomaintestmodule\"\n )\n\n with flask.send_from_directory(\"static\", \"hello.txt\") as rv:\n rv.direct_passthrough = False\n assert rv.data.strip() == b\"Hello Subdomain\""} {"repo":"flask","file":"tests/test_helpers.py","line":94,"symbol":"TestUrlFor","kind":"class","lang":"python","code":"class TestUrlFor:\n def test_url_for_with_anchor(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _anchor=\"x y\") == \"/#x%20y\"\n\n def test_url_for_with_scheme(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n\n def test_url_for_with_scheme_not_external(self, app, req_ctx):\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n # Implicit external with scheme.\n url = flask.url_for(\"index\", _scheme=\"https\")\n assert url == \"https://localhost/\"\n\n # Error when external=False with scheme\n with pytest.raises(ValueError):\n flask.url_for(\"index\", _scheme=\"https\", _external=False)\n\n def test_url_for_with_alternating_schemes(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https:/"} {"repo":"flask","file":"tests/test_helpers.py","line":95,"symbol":"test_url_for_with_anchor","kind":"function","lang":"python","code":"def test_url_for_with_anchor(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _anchor=\"x y\") == \"/#x%20y\""} {"repo":"flask","file":"tests/test_helpers.py","line":97,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"42\""} {"repo":"flask","file":"tests/test_helpers.py","line":102,"symbol":"test_url_for_with_scheme","kind":"function","lang":"python","code":"def test_url_for_with_scheme(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )"} {"repo":"flask","file":"tests/test_helpers.py","line":104,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"42\""} {"repo":"flask","file":"tests/test_helpers.py","line":112,"symbol":"test_url_for_with_scheme_not_external","kind":"function","lang":"python","code":"def test_url_for_with_scheme_not_external(self, app, req_ctx):\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n # Implicit external with scheme.\n url = flask.url_for(\"index\", _scheme=\"https\")\n assert url == \"https://localhost/\"\n\n # Error when external=False with scheme\n with pytest.raises(ValueError):\n flask.url_for(\"index\", _scheme=\"https\", _external=False)"} {"repo":"flask","file":"tests/test_helpers.py","line":123,"symbol":"test_url_for_with_alternating_schemes","kind":"function","lang":"python","code":"def test_url_for_with_alternating_schemes(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\""} {"repo":"flask","file":"tests/test_helpers.py","line":125,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"42\""} {"repo":"flask","file":"tests/test_helpers.py","line":135,"symbol":"test_url_with_method","kind":"function","lang":"python","code":"def test_url_with_method(self, app, req_ctx):\n from flask.views import MethodView\n\n class MyView(MethodView):\n def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\"\n\n def post(self):\n return \"Create\"\n\n myview = MyView.as_view(\"myview\")\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/create\", methods=[\"POST\"], view_func=myview)\n\n assert flask.url_for(\"myview\", _method=\"GET\") == \"/myview/\"\n assert flask.url_for(\"myview\", id=42, _method=\"GET\") == \"/myview/42\"\n assert flask.url_for(\"myview\", _method=\"POST\") == \"/myview/create\""} {"repo":"flask","file":"tests/test_helpers.py","line":138,"symbol":"MyView","kind":"class","lang":"python","code":"class MyView(MethodView):\n def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\"\n\n def post(self):\n return \"Create\""} {"repo":"flask","file":"tests/test_helpers.py","line":139,"symbol":"get","kind":"function","lang":"python","code":"def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\""} {"repo":"flask","file":"tests/test_helpers.py","line":144,"symbol":"post","kind":"function","lang":"python","code":"def post(self):\n return \"Create\""} {"repo":"flask","file":"tests/test_helpers.py","line":156,"symbol":"test_url_for_with_self","kind":"function","lang":"python","code":"def test_url_for_with_self(self, app, req_ctx):\n @app.route(\"/\")\n def index(self):\n return \"42\"\n\n assert flask.url_for(\"index\", self=\"2\") == \"/2\""} {"repo":"flask","file":"tests/test_helpers.py","line":158,"symbol":"index","kind":"function","lang":"python","code":"def index(self):\n return \"42\""} {"repo":"flask","file":"tests/test_helpers.py","line":164,"symbol":"test_redirect_no_app","kind":"function","lang":"python","code":"def test_redirect_no_app():\n response = flask.redirect(\"https://localhost\", 307)\n assert response.location == \"https://localhost\"\n assert response.status_code == 307"} {"repo":"flask","file":"tests/test_helpers.py","line":170,"symbol":"test_redirect_with_app","kind":"function","lang":"python","code":"def test_redirect_with_app(app):\n def redirect(location, code=302):\n raise ValueError\n\n app.redirect = redirect\n\n with app.app_context(), pytest.raises(ValueError):\n flask.redirect(\"other\")"} {"repo":"flask","file":"tests/test_helpers.py","line":171,"symbol":"redirect","kind":"function","lang":"python","code":"def redirect(location, code=302):\n raise ValueError"} {"repo":"flask","file":"tests/test_helpers.py","line":180,"symbol":"test_abort_no_app","kind":"function","lang":"python","code":"def test_abort_no_app():\n with pytest.raises(werkzeug.exceptions.Unauthorized):\n flask.abort(401)\n\n with pytest.raises(LookupError):\n flask.abort(900)"} {"repo":"flask","file":"tests/test_helpers.py","line":188,"symbol":"test_app_aborter_class","kind":"function","lang":"python","code":"def test_app_aborter_class():\n class MyAborter(werkzeug.exceptions.Aborter):\n pass\n\n class MyFlask(flask.Flask):\n aborter_class = MyAborter\n\n app = MyFlask(__name__)\n assert isinstance(app.aborter, MyAborter)"} {"repo":"flask","file":"tests/test_helpers.py","line":189,"symbol":"MyAborter","kind":"class","lang":"python","code":"class MyAborter(werkzeug.exceptions.Aborter):\n pass"} {"repo":"flask","file":"tests/test_helpers.py","line":192,"symbol":"MyFlask","kind":"class","lang":"python","code":"class MyFlask(flask.Flask):\n aborter_class = MyAborter"} {"repo":"flask","file":"tests/test_helpers.py","line":199,"symbol":"test_abort_with_app","kind":"function","lang":"python","code":"def test_abort_with_app(app):\n class My900Error(werkzeug.exceptions.HTTPException):\n code = 900\n\n app.aborter.mapping[900] = My900Error\n\n with app.app_context(), pytest.raises(My900Error):\n flask.abort(900)"} {"repo":"flask","file":"tests/test_helpers.py","line":200,"symbol":"My900Error","kind":"class","lang":"python","code":"class My900Error(werkzeug.exceptions.HTTPException):\n code = 900"} {"repo":"flask","file":"tests/test_helpers.py","line":209,"symbol":"TestNoImports","kind":"class","lang":"python","code":"class TestNoImports:\n \"\"\"Test Flasks are created without import.\n\n Avoiding ``__import__`` helps create Flask instances where there are errors\n at import time. Those runtime errors will be apparent to the user soon\n enough, but tools which build Flask instances meta-programmatically benefit\n from a Flask which does not ``__import__``. Instead of importing to\n retrieve file paths or metadata on a module or package, use the pkgutil and\n imp modules in the Python standard library.\n \"\"\"\n\n def test_name_with_import_error(self, modules_tmp_path):\n (modules_tmp_path / \"importerror.py\").write_text(\"raise NotImplementedError()\")\n try:\n flask.Flask(\"importerror\")\n except NotImplementedError:\n AssertionError(\"Flask(import_name) is importing import_name.\")"} {"repo":"flask","file":"tests/test_helpers.py","line":220,"symbol":"test_name_with_import_error","kind":"function","lang":"python","code":"def test_name_with_import_error(self, modules_tmp_path):\n (modules_tmp_path / \"importerror.py\").write_text(\"raise NotImplementedError()\")\n try:\n flask.Flask(\"importerror\")\n except NotImplementedError:\n AssertionError(\"Flask(import_name) is importing import_name.\")"} {"repo":"flask","file":"tests/test_helpers.py","line":228,"symbol":"TestStreaming","kind":"class","lang":"python","code":"class TestStreaming:\n def test_streaming_with_context(self, app, client):\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_as_decorator(self, app, client):\n @app.route(\"/\")\n def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_and_custom_close(self, app, client):\n called = []\n\n class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n "} {"repo":"flask","file":"tests/test_helpers.py","line":229,"symbol":"test_streaming_with_context","kind":"function","lang":"python","code":"def test_streaming_with_context(self, app, client):\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\""} {"repo":"flask","file":"tests/test_helpers.py","line":231,"symbol":"index","kind":"function","lang":"python","code":"def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))"} {"repo":"flask","file":"tests/test_helpers.py","line":232,"symbol":"generate","kind":"function","lang":"python","code":"def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\""} {"repo":"flask","file":"tests/test_helpers.py","line":242,"symbol":"test_streaming_with_context_as_decorator","kind":"function","lang":"python","code":"def test_streaming_with_context_as_decorator(self, app, client):\n @app.route(\"/\")\n def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\""} {"repo":"flask","file":"tests/test_helpers.py","line":244,"symbol":"index","kind":"function","lang":"python","code":"def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))"} {"repo":"flask","file":"tests/test_helpers.py","line":246,"symbol":"generate","kind":"function","lang":"python","code":"def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\""} {"repo":"flask","file":"tests/test_helpers.py","line":256,"symbol":"test_streaming_with_context_and_custom_close","kind":"function","lang":"python","code":"def test_streaming_with_context_and_custom_close(self, app, client):\n called = []\n\n class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n return next(self._gen)\n\n next = __next__\n\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(Wrapper(generate())))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n assert called == [42]"} {"repo":"flask","file":"tests/test_helpers.py","line":259,"symbol":"Wrapper","kind":"class","lang":"python","code":"class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n return next(self._gen)\n\n next = __next__"} {"repo":"flask","file":"tests/test_helpers.py","line":260,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, gen):\n self._gen = gen"} {"repo":"flask","file":"tests/test_helpers.py","line":263,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self):\n return self"} {"repo":"flask","file":"tests/test_helpers.py","line":266,"symbol":"close","kind":"function","lang":"python","code":"def close(self):\n called.append(42)"} {"repo":"flask","file":"tests/test_helpers.py","line":269,"symbol":"__next__","kind":"function","lang":"python","code":"def __next__(self):\n return next(self._gen)"} {"repo":"flask","file":"tests/test_helpers.py","line":275,"symbol":"index","kind":"function","lang":"python","code":"def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(Wrapper(generate())))"} {"repo":"flask","file":"tests/test_helpers.py","line":276,"symbol":"generate","kind":"function","lang":"python","code":"def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\""} {"repo":"flask","file":"tests/test_helpers.py","line":287,"symbol":"test_stream_keeps_session","kind":"function","lang":"python","code":"def test_stream_keeps_session(self, app, client):\n @app.route(\"/\")\n def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())\n\n rv = client.get(\"/\")\n assert rv.data == b\"flask\""} {"repo":"flask","file":"tests/test_helpers.py","line":289,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())"} {"repo":"flask","file":"tests/test_helpers.py","line":293,"symbol":"gen","kind":"function","lang":"python","code":"def gen():\n yield flask.session[\"test\"]"} {"repo":"flask","file":"tests/test_helpers.py","line":301,"symbol":"test_async_view","kind":"function","lang":"python","code":"def test_async_view(self, app, client):\n @app.route(\"/\")\n async def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())\n\n # response is closed without reading stream\n client.get().close()\n\n # response stream is read\n with client.get() as rv:\n assert rv.text == \"flask\"\n\n # same as above, but with client context preservation\n with client:\n client.get().close()\n\n with client, client.get() as rv:\n assert rv.text == \"flask\""} {"repo":"flask","file":"tests/test_helpers.py","line":303,"symbol":"index","kind":"function","lang":"python","code":"async def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())"} {"repo":"flask","file":"tests/test_helpers.py","line":307,"symbol":"gen","kind":"function","lang":"python","code":"def gen():\n yield flask.session[\"test\"]"} {"repo":"flask","file":"tests/test_helpers.py","line":327,"symbol":"TestHelpers","kind":"class","lang":"python","code":"class TestHelpers:\n @pytest.mark.parametrize(\n (\"debug\", \"expect\"),\n [\n (\"\", False),\n (\"0\", False),\n (\"False\", False),\n (\"No\", False),\n (\"True\", True),\n ],\n )\n def test_get_debug_flag(self, monkeypatch, debug, expect):\n monkeypatch.setenv(\"FLASK_DEBUG\", debug)\n assert get_debug_flag() == expect\n\n def test_make_response(self):\n app = flask.Flask(__name__)\n with app.test_request_context():\n rv = flask.helpers.make_response()\n assert rv.status_code == 200\n assert rv.mimetype == \"text/html\"\n\n rv = flask.helpers.make_response(\"Hello\")\n assert rv.status_code == 200\n assert rv.data == b\"Hello\"\n assert rv.mimetype == \"text/html\""} {"repo":"flask","file":"tests/test_helpers.py","line":338,"symbol":"test_get_debug_flag","kind":"function","lang":"python","code":"def test_get_debug_flag(self, monkeypatch, debug, expect):\n monkeypatch.setenv(\"FLASK_DEBUG\", debug)\n assert get_debug_flag() == expect"} {"repo":"flask","file":"tests/test_instance_config.py","line":8,"symbol":"test_explicit_instance_paths","kind":"function","lang":"python","code":"def test_explicit_instance_paths(modules_tmp_path):\n with pytest.raises(ValueError, match=\".*must be absolute\"):\n flask.Flask(__name__, instance_path=\"instance\")\n\n app = flask.Flask(__name__, instance_path=os.fspath(modules_tmp_path))\n assert app.instance_path == os.fspath(modules_tmp_path)"} {"repo":"flask","file":"tests/test_instance_config.py","line":16,"symbol":"test_uninstalled_module_paths","kind":"function","lang":"python","code":"def test_uninstalled_module_paths(modules_tmp_path, purge_module):\n (modules_tmp_path / \"config_module_app.py\").write_text(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_module_app\")\n\n from config_module_app import app\n\n assert app.instance_path == os.fspath(modules_tmp_path / \"instance\")"} {"repo":"flask","file":"tests/test_instance_config.py","line":30,"symbol":"test_uninstalled_package_paths","kind":"function","lang":"python","code":"def test_uninstalled_package_paths(modules_tmp_path, purge_module):\n app = modules_tmp_path / \"config_package_app\"\n app.mkdir()\n (app / \"__init__.py\").write_text(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_package_app\")\n\n from config_package_app import app\n\n assert app.instance_path == os.fspath(modules_tmp_path / \"instance\")"} {"repo":"flask","file":"tests/test_instance_config.py","line":46,"symbol":"test_uninstalled_namespace_paths","kind":"function","lang":"python","code":"def test_uninstalled_namespace_paths(tmp_path, monkeypatch, purge_module):\n def create_namespace(package):\n project = tmp_path / f\"project-{package}\"\n monkeypatch.syspath_prepend(os.fspath(project))\n ns = project / \"namespace\" / package\n ns.mkdir(parents=True)\n (ns / \"__init__.py\").write_text(\"import flask\\napp = flask.Flask(__name__)\\n\")\n return project\n\n _ = create_namespace(\"package1\")\n project2 = create_namespace(\"package2\")\n purge_module(\"namespace.package2\")\n purge_module(\"namespace\")\n\n from namespace.package2 import app\n\n assert app.instance_path == os.fspath(project2 / \"instance\")"} {"repo":"flask","file":"tests/test_instance_config.py","line":47,"symbol":"create_namespace","kind":"function","lang":"python","code":"def create_namespace(package):\n project = tmp_path / f\"project-{package}\"\n monkeypatch.syspath_prepend(os.fspath(project))\n ns = project / \"namespace\" / package\n ns.mkdir(parents=True)\n (ns / \"__init__.py\").write_text(\"import flask\\napp = flask.Flask(__name__)\\n\")\n return project"} {"repo":"flask","file":"tests/test_instance_config.py","line":65,"symbol":"test_installed_module_paths","kind":"function","lang":"python","code":"def test_installed_module_paths(\n modules_tmp_path, modules_tmp_path_prefix, purge_module, site_packages\n):\n (site_packages / \"site_app.py\").write_text(\n \"import flask\\napp = flask.Flask(__name__)\\n\"\n )\n purge_module(\"site_app\")\n\n from site_app import app\n\n assert app.instance_path == os.fspath(\n modules_tmp_path / \"var\" / \"site_app-instance\"\n )"} {"repo":"flask","file":"tests/test_instance_config.py","line":80,"symbol":"test_installed_package_paths","kind":"function","lang":"python","code":"def test_installed_package_paths(\n modules_tmp_path, modules_tmp_path_prefix, purge_module, monkeypatch\n):\n installed_path = modules_tmp_path / \"path\"\n installed_path.mkdir()\n monkeypatch.syspath_prepend(installed_path)\n\n app = installed_path / \"installed_package\"\n app.mkdir()\n (app / \"__init__.py\").write_text(\"import flask\\napp = flask.Flask(__name__)\\n\")\n purge_module(\"installed_package\")\n\n from installed_package import app\n\n assert app.instance_path == os.fspath(\n modules_tmp_path / \"var\" / \"installed_package-instance\"\n )"} {"repo":"flask","file":"tests/test_instance_config.py","line":99,"symbol":"test_prefix_package_paths","kind":"function","lang":"python","code":"def test_prefix_package_paths(\n modules_tmp_path, modules_tmp_path_prefix, purge_module, site_packages\n):\n app = site_packages / \"site_package\"\n app.mkdir()\n (app / \"__init__.py\").write_text(\"import flask\\napp = flask.Flask(__name__)\\n\")\n purge_module(\"site_package\")\n\n import site_package\n\n assert site_package.app.instance_path == os.fspath(\n modules_tmp_path / \"var\" / \"site_package-instance\"\n )"} {"repo":"flask","file":"tests/test_json.py","line":15,"symbol":"test_bad_request_debug_message","kind":"function","lang":"python","code":"def test_bad_request_debug_message(app, client, debug):\n app.config[\"DEBUG\"] = debug\n app.config[\"TRAP_BAD_REQUEST_ERRORS\"] = False\n\n @app.route(\"/json\", methods=[\"POST\"])\n def post_json():\n flask.request.get_json()\n return None\n\n rv = client.post(\"/json\", data=None, content_type=\"application/json\")\n assert rv.status_code == 400\n contains = b\"Failed to decode JSON object\" in rv.data\n assert contains == debug"} {"repo":"flask","file":"tests/test_json.py","line":20,"symbol":"post_json","kind":"function","lang":"python","code":"def post_json():\n flask.request.get_json()\n return None"} {"repo":"flask","file":"tests/test_json.py","line":30,"symbol":"test_json_bad_requests","kind":"function","lang":"python","code":"def test_json_bad_requests(app, client):\n @app.route(\"/json\", methods=[\"POST\"])\n def return_json():\n return flask.jsonify(foo=str(flask.request.get_json()))\n\n rv = client.post(\"/json\", data=\"malformed\", content_type=\"application/json\")\n assert rv.status_code == 400"} {"repo":"flask","file":"tests/test_json.py","line":32,"symbol":"return_json","kind":"function","lang":"python","code":"def return_json():\n return flask.jsonify(foo=str(flask.request.get_json()))"} {"repo":"flask","file":"tests/test_json.py","line":39,"symbol":"test_json_custom_mimetypes","kind":"function","lang":"python","code":"def test_json_custom_mimetypes(app, client):\n @app.route(\"/json\", methods=[\"POST\"])\n def return_json():\n return flask.request.get_json()\n\n rv = client.post(\"/json\", data='\"foo\"', content_type=\"application/x+json\")\n assert rv.data == b\"foo\""} {"repo":"flask","file":"tests/test_json.py","line":41,"symbol":"return_json","kind":"function","lang":"python","code":"def return_json():\n return flask.request.get_json()"} {"repo":"flask","file":"tests/test_json.py","line":51,"symbol":"test_json_as_unicode","kind":"function","lang":"python","code":"def test_json_as_unicode(test_value, expected, app, app_ctx):\n app.json.ensure_ascii = test_value\n rv = app.json.dumps(\"\\N{SNOWMAN}\")\n assert rv == expected"} {"repo":"flask","file":"tests/test_json.py","line":57,"symbol":"test_json_dump_to_file","kind":"function","lang":"python","code":"def test_json_dump_to_file(app, app_ctx):\n test_data = {\"name\": \"Flask\"}\n out = io.StringIO()\n\n flask.json.dump(test_data, out)\n out.seek(0)\n rv = flask.json.load(out)\n assert rv == test_data"} {"repo":"flask","file":"tests/test_json.py","line":70,"symbol":"test_jsonify_basic_types","kind":"function","lang":"python","code":"def test_jsonify_basic_types(test_value, app, client):\n url = \"/jsonify_basic_types\"\n app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))\n rv = client.get(url)\n assert rv.mimetype == \"application/json\"\n assert flask.json.loads(rv.data) == test_value"} {"repo":"flask","file":"tests/test_json.py","line":78,"symbol":"test_jsonify_dicts","kind":"function","lang":"python","code":"def test_jsonify_dicts(app, client):\n d = {\n \"a\": 0,\n \"b\": 23,\n \"c\": 3.14,\n \"d\": \"t\",\n \"e\": \"Hi\",\n \"f\": True,\n \"g\": False,\n \"h\": [\"test list\", 10, False],\n \"i\": {\"test\": \"dict\"},\n }\n\n @app.route(\"/kw\")\n def return_kwargs():\n return flask.jsonify(**d)\n\n @app.route(\"/dict\")\n def return_dict():\n return flask.jsonify(d)\n\n for url in \"/kw\", \"/dict\":\n rv = client.get(url)\n assert rv.mimetype == \"application/json\"\n assert flask.json.loads(rv.data) == d"} {"repo":"flask","file":"tests/test_json.py","line":92,"symbol":"return_kwargs","kind":"function","lang":"python","code":"def return_kwargs():\n return flask.jsonify(**d)"} {"repo":"flask","file":"tests/test_json.py","line":96,"symbol":"return_dict","kind":"function","lang":"python","code":"def return_dict():\n return flask.jsonify(d)"} {"repo":"flask","file":"tests/test_json.py","line":105,"symbol":"test_jsonify_arrays","kind":"function","lang":"python","code":"def test_jsonify_arrays(app, client):\n \"\"\"Test jsonify of lists and args unpacking.\"\"\"\n a_list = [\n 0,\n 42,\n 3.14,\n \"t\",\n \"hello\",\n True,\n False,\n [\"test list\", 2, False],\n {\"test\": \"dict\"},\n ]\n\n @app.route(\"/args_unpack\")\n def return_args_unpack():\n return flask.jsonify(*a_list)\n\n @app.route(\"/array\")\n def return_array():\n return flask.jsonify(a_list)\n\n for url in \"/args_unpack\", \"/array\":\n rv = client.get(url)\n assert rv.mimetype == \"application/json\"\n assert flask.json.loads(rv.data) == a_list"} {"repo":"flask","file":"tests/test_json.py","line":120,"symbol":"return_args_unpack","kind":"function","lang":"python","code":"def return_args_unpack():\n return flask.jsonify(*a_list)"} {"repo":"flask","file":"tests/test_json.py","line":124,"symbol":"return_array","kind":"function","lang":"python","code":"def return_array():\n return flask.jsonify(a_list)"} {"repo":"flask","file":"tests/test_json.py","line":136,"symbol":"test_jsonify_datetime","kind":"function","lang":"python","code":"def test_jsonify_datetime(app, client, value):\n @app.route(\"/\")\n def index():\n return flask.jsonify(value=value)\n\n r = client.get()\n assert r.json[\"value\"] == http_date(value)"} {"repo":"flask","file":"tests/test_json.py","line":138,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.jsonify(value=value)"} {"repo":"flask","file":"tests/test_json.py","line":145,"symbol":"FixedOffset","kind":"class","lang":"python","code":"class FixedOffset(datetime.tzinfo):\n \"\"\"Fixed offset in hours east from UTC.\n\n This is a slight adaptation of the ``FixedOffset`` example found in\n https://docs.python.org/2.7/library/datetime.html.\n \"\"\"\n\n def __init__(self, hours, name):\n self.__offset = datetime.timedelta(hours=hours)\n self.__name = name\n\n def utcoffset(self, dt):\n return self.__offset\n\n def tzname(self, dt):\n return self.__name\n\n def dst(self, dt):\n return datetime.timedelta()"} {"repo":"flask","file":"tests/test_json.py","line":152,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, hours, name):\n self.__offset = datetime.timedelta(hours=hours)\n self.__name = name"} {"repo":"flask","file":"tests/test_json.py","line":156,"symbol":"utcoffset","kind":"function","lang":"python","code":"def utcoffset(self, dt):\n return self.__offset"} {"repo":"flask","file":"tests/test_json.py","line":159,"symbol":"tzname","kind":"function","lang":"python","code":"def tzname(self, dt):\n return self.__name"} {"repo":"flask","file":"tests/test_json.py","line":162,"symbol":"dst","kind":"function","lang":"python","code":"def dst(self, dt):\n return datetime.timedelta()"} {"repo":"flask","file":"tests/test_json.py","line":167,"symbol":"test_jsonify_aware_datetimes","kind":"function","lang":"python","code":"def test_jsonify_aware_datetimes(tz):\n \"\"\"Test if aware datetime.datetime objects are converted into GMT.\"\"\"\n tzinfo = FixedOffset(hours=tz[1], name=tz[0])\n dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)\n gmt = FixedOffset(hours=0, name=\"GMT\")\n expected = dt.astimezone(gmt).strftime('\"%a, %d %b %Y %H:%M:%S %Z\"')\n assert flask.json.dumps(dt) == expected"} {"repo":"flask","file":"tests/test_json.py","line":176,"symbol":"test_jsonify_uuid_types","kind":"function","lang":"python","code":"def test_jsonify_uuid_types(app, client):\n \"\"\"Test jsonify with uuid.UUID types\"\"\"\n\n test_uuid = uuid.UUID(bytes=b\"\\xde\\xad\\xbe\\xef\" * 4)\n url = \"/uuid_test\"\n app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))\n\n rv = client.get(url)\n\n rv_x = flask.json.loads(rv.data)[\"x\"]\n assert rv_x == str(test_uuid)\n rv_uuid = uuid.UUID(rv_x)\n assert rv_uuid == test_uuid"} {"repo":"flask","file":"tests/test_json.py","line":191,"symbol":"test_json_decimal","kind":"function","lang":"python","code":"def test_json_decimal():\n rv = flask.json.dumps(decimal.Decimal(\"0.003\"))\n assert rv == '\"0.003\"'"} {"repo":"flask","file":"tests/test_json.py","line":196,"symbol":"test_json_attr","kind":"function","lang":"python","code":"def test_json_attr(app, client):\n @app.route(\"/add\", methods=[\"POST\"])\n def add():\n json = flask.request.get_json()\n return str(json[\"a\"] + json[\"b\"])\n\n rv = client.post(\n \"/add\",\n data=flask.json.dumps({\"a\": 1, \"b\": 2}),\n content_type=\"application/json\",\n )\n assert rv.data == b\"3\""} {"repo":"flask","file":"tests/test_json.py","line":198,"symbol":"add","kind":"function","lang":"python","code":"def add():\n json = flask.request.get_json()\n return str(json[\"a\"] + json[\"b\"])"} {"repo":"flask","file":"tests/test_json.py","line":210,"symbol":"test_tojson_filter","kind":"function","lang":"python","code":"def test_tojson_filter(app, req_ctx):\n # The tojson filter is tested in Jinja, this confirms that it's\n # using Flask's dumps.\n rv = flask.render_template_string(\n \"const data = {{ data|tojson }};\",\n data={\"name\": \"\", \"time\": datetime.datetime(2021, 2, 1, 7, 15)},\n )\n assert rv == (\n 'const data = {\"name\": \"\\\\u003c/script\\\\u003e\",'\n ' \"time\": \"Mon, 01 Feb 2021 07:15:00 GMT\"};'\n )"} {"repo":"flask","file":"tests/test_json.py","line":223,"symbol":"test_json_customization","kind":"function","lang":"python","code":"def test_json_customization(app, client):\n class X: # noqa: B903, for Python2 compatibility\n def __init__(self, val):\n self.val = val\n\n def default(o):\n if isinstance(o, X):\n return f\"<{o.val}>\"\n\n return DefaultJSONProvider.default(o)\n\n class CustomProvider(DefaultJSONProvider):\n def object_hook(self, obj):\n if len(obj) == 1 and \"_foo\" in obj:\n return X(obj[\"_foo\"])\n\n return obj\n\n def loads(self, s, **kwargs):\n kwargs.setdefault(\"object_hook\", self.object_hook)\n return super().loads(s, **kwargs)\n\n app.json = CustomProvider(app)\n app.json.default = default\n\n @app.route(\"/\", methods=[\"POST\"])\n def index():\n return flask.json.dumps(flask.request.get_json()[\"x\"])\n\n rv = client.post(\n \"/\",\n data=flask.json.dumps({\"x\": {\"_foo\": 42}}),\n content_type=\"application/json\",\n )\n assert rv.data == b'\"<42>\"'"} {"repo":"flask","file":"tests/test_json.py","line":224,"symbol":"X","kind":"class","lang":"python","code":"class X: # noqa: B903, for Python2 compatibility\n def __init__(self, val):\n self.val = val"} {"repo":"flask","file":"tests/test_json.py","line":225,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, val):\n self.val = val"} {"repo":"flask","file":"tests/test_json.py","line":228,"symbol":"default","kind":"function","lang":"python","code":"def default(o):\n if isinstance(o, X):\n return f\"<{o.val}>\"\n\n return DefaultJSONProvider.default(o)"} {"repo":"flask","file":"tests/test_json.py","line":234,"symbol":"CustomProvider","kind":"class","lang":"python","code":"class CustomProvider(DefaultJSONProvider):\n def object_hook(self, obj):\n if len(obj) == 1 and \"_foo\" in obj:\n return X(obj[\"_foo\"])\n\n return obj\n\n def loads(self, s, **kwargs):\n kwargs.setdefault(\"object_hook\", self.object_hook)\n return super().loads(s, **kwargs)"} {"repo":"flask","file":"tests/test_json.py","line":235,"symbol":"object_hook","kind":"function","lang":"python","code":"def object_hook(self, obj):\n if len(obj) == 1 and \"_foo\" in obj:\n return X(obj[\"_foo\"])\n\n return obj"} {"repo":"flask","file":"tests/test_json.py","line":241,"symbol":"loads","kind":"function","lang":"python","code":"def loads(self, s, **kwargs):\n kwargs.setdefault(\"object_hook\", self.object_hook)\n return super().loads(s, **kwargs)"} {"repo":"flask","file":"tests/test_json.py","line":249,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.json.dumps(flask.request.get_json()[\"x\"])"} {"repo":"flask","file":"tests/test_json.py","line":260,"symbol":"_has_encoding","kind":"function","lang":"python","code":"def _has_encoding(name):\n try:\n import codecs\n\n codecs.lookup(name)\n return True\n except LookupError:\n return False"} {"repo":"flask","file":"tests/test_json.py","line":270,"symbol":"test_json_key_sorting","kind":"function","lang":"python","code":"def test_json_key_sorting(app, client):\n app.debug = True\n assert app.json.sort_keys\n d = dict.fromkeys(range(20), \"foo\")\n\n @app.route(\"/\")\n def index():\n return flask.jsonify(values=d)\n\n rv = client.get(\"/\")\n lines = [x.strip() for x in rv.data.strip().decode(\"utf-8\").splitlines()]\n sorted_by_str = [\n \"{\",\n '\"values\": {',\n '\"0\": \"foo\",',\n '\"1\": \"foo\",',\n '\"10\": \"foo\",',\n '\"11\": \"foo\",',\n '\"12\": \"foo\",',\n '\"13\": \"foo\",',\n '\"14\": \"foo\",',\n '\"15\": \"foo\",',\n '\"16\": \"foo\",',\n '\"17\": \"foo\",',\n '\"18\": \"foo\",',\n '\"19\": \"foo\",',\n '\"2\": \"foo\",',\n '\"3\": \"foo\",',\n '\"4\": \"foo\",',\n '\"5\": \"foo\",',\n '\"6\": \"foo\",',\n '\"7\": \"foo\",',\n '\"8\": \"foo\",',\n '\"9\": \"foo\"',\n \"}\",\n \"}\",\n ]\n sorted_by_int = [\n \"{\",\n '\"values\": {',\n '\"0\": \"foo\",',\n '\"1\": \"foo\",',\n '\"2\": \"foo\",',\n '\"3\": \"foo\",',\n '\"4\": \"foo\",',\n '\"5\": \"foo\",',\n '\"6\": \"foo\",',\n '\"7\": \"foo\",',\n '\"8\": \"foo\",',\n '\"9\": \"foo\",',\n '\"10\": \"foo\",',\n '\"11\": \"f"} {"repo":"flask","file":"tests/test_json.py","line":276,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.jsonify(values=d)"} {"repo":"flask","file":"tests/test_json.py","line":340,"symbol":"test_html_method","kind":"function","lang":"python","code":"def test_html_method():\n class ObjectWithHTML:\n def __html__(self):\n return \"

test

\"\n\n result = json.dumps(ObjectWithHTML())\n assert result == '\"

test

\"'"} {"repo":"flask","file":"tests/test_json.py","line":341,"symbol":"ObjectWithHTML","kind":"class","lang":"python","code":"class ObjectWithHTML:\n def __html__(self):\n return \"

test

\""} {"repo":"flask","file":"tests/test_json.py","line":342,"symbol":"__html__","kind":"function","lang":"python","code":"def __html__(self):\n return \"

test

\""} {"repo":"flask","file":"tests/test_json_tag.py","line":27,"symbol":"test_dump_load_unchanged","kind":"function","lang":"python","code":"def test_dump_load_unchanged(data):\n s = TaggedJSONSerializer()\n assert s.loads(s.dumps(data)) == data"} {"repo":"flask","file":"tests/test_json_tag.py","line":32,"symbol":"test_duplicate_tag","kind":"function","lang":"python","code":"def test_duplicate_tag():\n class TagDict(JSONTag):\n key = \" d\"\n\n s = TaggedJSONSerializer()\n pytest.raises(KeyError, s.register, TagDict)\n s.register(TagDict, force=True, index=0)\n assert isinstance(s.tags[\" d\"], TagDict)\n assert isinstance(s.order[0], TagDict)"} {"repo":"flask","file":"tests/test_json_tag.py","line":33,"symbol":"TagDict","kind":"class","lang":"python","code":"class TagDict(JSONTag):\n key = \" d\""} {"repo":"flask","file":"tests/test_json_tag.py","line":43,"symbol":"test_custom_tag","kind":"function","lang":"python","code":"def test_custom_tag():\n class Foo: # noqa: B903, for Python2 compatibility\n def __init__(self, data):\n self.data = data\n\n class TagFoo(JSONTag):\n __slots__ = ()\n key = \" f\"\n\n def check(self, value):\n return isinstance(value, Foo)\n\n def to_json(self, value):\n return self.serializer.tag(value.data)\n\n def to_python(self, value):\n return Foo(value)\n\n s = TaggedJSONSerializer()\n s.register(TagFoo)\n assert s.loads(s.dumps(Foo(\"bar\"))).data == \"bar\""} {"repo":"flask","file":"tests/test_json_tag.py","line":44,"symbol":"Foo","kind":"class","lang":"python","code":"class Foo: # noqa: B903, for Python2 compatibility\n def __init__(self, data):\n self.data = data"} {"repo":"flask","file":"tests/test_json_tag.py","line":45,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, data):\n self.data = data"} {"repo":"flask","file":"tests/test_json_tag.py","line":48,"symbol":"TagFoo","kind":"class","lang":"python","code":"class TagFoo(JSONTag):\n __slots__ = ()\n key = \" f\"\n\n def check(self, value):\n return isinstance(value, Foo)\n\n def to_json(self, value):\n return self.serializer.tag(value.data)\n\n def to_python(self, value):\n return Foo(value)"} {"repo":"flask","file":"tests/test_json_tag.py","line":52,"symbol":"check","kind":"function","lang":"python","code":"def check(self, value):\n return isinstance(value, Foo)"} {"repo":"flask","file":"tests/test_json_tag.py","line":55,"symbol":"to_json","kind":"function","lang":"python","code":"def to_json(self, value):\n return self.serializer.tag(value.data)"} {"repo":"flask","file":"tests/test_json_tag.py","line":58,"symbol":"to_python","kind":"function","lang":"python","code":"def to_python(self, value):\n return Foo(value)"} {"repo":"flask","file":"tests/test_json_tag.py","line":66,"symbol":"test_tag_interface","kind":"function","lang":"python","code":"def test_tag_interface():\n t = JSONTag(None)\n pytest.raises(NotImplementedError, t.check, None)\n pytest.raises(NotImplementedError, t.to_json, None)\n pytest.raises(NotImplementedError, t.to_python, None)"} {"repo":"flask","file":"tests/test_json_tag.py","line":73,"symbol":"test_tag_order","kind":"function","lang":"python","code":"def test_tag_order():\n class Tag1(JSONTag):\n key = \" 1\"\n\n class Tag2(JSONTag):\n key = \" 2\"\n\n s = TaggedJSONSerializer()\n\n s.register(Tag1, index=-1)\n assert isinstance(s.order[-2], Tag1)\n\n s.register(Tag2, index=None)\n assert isinstance(s.order[-1], Tag2)"} {"repo":"flask","file":"tests/test_json_tag.py","line":74,"symbol":"Tag1","kind":"class","lang":"python","code":"class Tag1(JSONTag):\n key = \" 1\""} {"repo":"flask","file":"tests/test_json_tag.py","line":77,"symbol":"Tag2","kind":"class","lang":"python","code":"class Tag2(JSONTag):\n key = \" 2\""} {"repo":"flask","file":"tests/test_logging.py","line":13,"symbol":"reset_logging","kind":"function","lang":"python","code":"def reset_logging(pytestconfig):\n root_handlers = logging.root.handlers[:]\n logging.root.handlers = []\n root_level = logging.root.level\n\n logger = logging.getLogger(\"flask_test\")\n logger.handlers = []\n logger.setLevel(logging.NOTSET)\n\n logging_plugin = pytestconfig.pluginmanager.unregister(name=\"logging-plugin\")\n\n yield\n\n logging.root.handlers[:] = root_handlers\n logging.root.setLevel(root_level)\n\n logger.handlers = []\n logger.setLevel(logging.NOTSET)\n\n if logging_plugin:\n pytestconfig.pluginmanager.register(logging_plugin, \"logging-plugin\")"} {"repo":"flask","file":"tests/test_logging.py","line":36,"symbol":"test_logger","kind":"function","lang":"python","code":"def test_logger(app):\n assert app.logger.name == \"flask_test\"\n assert app.logger.level == logging.NOTSET\n assert app.logger.handlers == [default_handler]"} {"repo":"flask","file":"tests/test_logging.py","line":42,"symbol":"test_logger_debug","kind":"function","lang":"python","code":"def test_logger_debug(app):\n app.debug = True\n assert app.logger.level == logging.DEBUG\n assert app.logger.handlers == [default_handler]"} {"repo":"flask","file":"tests/test_logging.py","line":48,"symbol":"test_existing_handler","kind":"function","lang":"python","code":"def test_existing_handler(app):\n logging.root.addHandler(logging.StreamHandler())\n assert app.logger.level == logging.NOTSET\n assert not app.logger.handlers"} {"repo":"flask","file":"tests/test_logging.py","line":54,"symbol":"test_wsgi_errors_stream","kind":"function","lang":"python","code":"def test_wsgi_errors_stream(app, client):\n @app.route(\"/\")\n def index():\n app.logger.error(\"test\")\n return \"\"\n\n stream = StringIO()\n client.get(\"/\", errors_stream=stream)\n assert \"ERROR in test_logging: test\" in stream.getvalue()\n\n assert wsgi_errors_stream._get_current_object() is sys.stderr\n\n with app.test_request_context(errors_stream=stream):\n assert wsgi_errors_stream._get_current_object() is stream"} {"repo":"flask","file":"tests/test_logging.py","line":56,"symbol":"index","kind":"function","lang":"python","code":"def index():\n app.logger.error(\"test\")\n return \"\""} {"repo":"flask","file":"tests/test_logging.py","line":70,"symbol":"test_has_level_handler","kind":"function","lang":"python","code":"def test_has_level_handler():\n logger = logging.getLogger(\"flask.app\")\n assert not has_level_handler(logger)\n\n handler = logging.StreamHandler()\n logging.root.addHandler(handler)\n assert has_level_handler(logger)\n\n logger.propagate = False\n assert not has_level_handler(logger)\n logger.propagate = True\n\n handler.setLevel(logging.ERROR)\n assert not has_level_handler(logger)"} {"repo":"flask","file":"tests/test_logging.py","line":86,"symbol":"test_log_view_exception","kind":"function","lang":"python","code":"def test_log_view_exception(app, client):\n @app.route(\"/\")\n def index():\n raise Exception(\"test\")\n\n app.testing = False\n stream = StringIO()\n rv = client.get(\"/\", errors_stream=stream)\n assert rv.status_code == 500\n assert rv.data\n err = stream.getvalue()\n assert \"Exception on / [GET]\" in err\n assert \"Exception: test\" in err"} {"repo":"flask","file":"tests/test_logging.py","line":88,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise Exception(\"test\")"} {"repo":"flask","file":"tests/test_regression.py","line":4,"symbol":"test_aborting","kind":"function","lang":"python","code":"def test_aborting(app):\n class Foo(Exception):\n whatever = 42\n\n @app.errorhandler(Foo)\n def handle_foo(e):\n return str(e.whatever)\n\n @app.route(\"/\")\n def index():\n raise flask.abort(flask.redirect(flask.url_for(\"test\")))\n\n @app.route(\"/test\")\n def test():\n raise Foo()\n\n with app.test_client() as c:\n rv = c.get(\"/\")\n location_parts = rv.headers[\"Location\"].rpartition(\"/\")\n\n if location_parts[0]:\n # For older Werkzeug that used absolute redirects.\n assert location_parts[0] == \"http://localhost\"\n\n assert location_parts[2] == \"test\"\n rv = c.get(\"/test\")\n assert rv.data == b\"42\""} {"repo":"flask","file":"tests/test_regression.py","line":5,"symbol":"Foo","kind":"class","lang":"python","code":"class Foo(Exception):\n whatever = 42"} {"repo":"flask","file":"tests/test_regression.py","line":9,"symbol":"handle_foo","kind":"function","lang":"python","code":"def handle_foo(e):\n return str(e.whatever)"} {"repo":"flask","file":"tests/test_regression.py","line":13,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise flask.abort(flask.redirect(flask.url_for(\"test\")))"} {"repo":"flask","file":"tests/test_regression.py","line":17,"symbol":"test","kind":"function","lang":"python","code":"def test():\n raise Foo()"} {"repo":"flask","file":"tests/test_reqctx.py","line":15,"symbol":"test_teardown_on_pop","kind":"function","lang":"python","code":"def test_teardown_on_pop(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n ctx = app.test_request_context()\n ctx.push()\n assert buffer == []\n ctx.pop()\n assert buffer == [None]"} {"repo":"flask","file":"tests/test_reqctx.py","line":19,"symbol":"end_of_request","kind":"function","lang":"python","code":"def end_of_request(exception):\n buffer.append(exception)"} {"repo":"flask","file":"tests/test_reqctx.py","line":29,"symbol":"test_teardown_with_previous_exception","kind":"function","lang":"python","code":"def test_teardown_with_previous_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n\n with app.test_request_context():\n assert buffer == []\n assert buffer == [None]"} {"repo":"flask","file":"tests/test_reqctx.py","line":33,"symbol":"end_of_request","kind":"function","lang":"python","code":"def end_of_request(exception):\n buffer.append(exception)"} {"repo":"flask","file":"tests/test_reqctx.py","line":46,"symbol":"test_teardown_with_handled_exception","kind":"function","lang":"python","code":"def test_teardown_with_handled_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n with app.test_request_context():\n assert buffer == []\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n assert buffer == [None]"} {"repo":"flask","file":"tests/test_reqctx.py","line":50,"symbol":"end_of_request","kind":"function","lang":"python","code":"def end_of_request(exception):\n buffer.append(exception)"} {"repo":"flask","file":"tests/test_reqctx.py","line":62,"symbol":"test_proper_test_request_context","kind":"function","lang":"python","code":"def test_proper_test_request_context(app):\n app.config.update(SERVER_NAME=\"localhost.localdomain:5000\")\n\n @app.route(\"/\")\n def index():\n return None\n\n @app.route(\"/\", subdomain=\"foo\")\n def sub():\n return None\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"index\", _external=True)\n == \"http://localhost.localdomain:5000/\"\n )\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"sub\", _external=True)\n == \"http://foo.localhost.localdomain:5000/\"\n )\n\n # suppress Werkzeug 0.15 warning about name mismatch\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\", \"Current server name\", UserWarning, \"flask.app\"\n )\n with app.test_request_context(\n \"/\", environ_overrides={\"HTTP_HOST\": \"localhost\"}\n ):\n pass\n\n app.config.update(SERVER_NAME=\"localhost\")\n with app.test_request_context(\"/\", environ_overrides={\"SERVER_NAME\": \"localhost\"}):\n pass\n\n app.config.update(SERVER_NAME=\"localhost:80\")\n with app.test_request_context(\n \"/\", environ_overrides={\"SERVER_NAME\": "} {"repo":"flask","file":"tests/test_reqctx.py","line":66,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return None"} {"repo":"flask","file":"tests/test_reqctx.py","line":70,"symbol":"sub","kind":"function","lang":"python","code":"def sub():\n return None"} {"repo":"flask","file":"tests/test_reqctx.py","line":106,"symbol":"test_context_binding","kind":"function","lang":"python","code":"def test_context_binding(app):\n @app.route(\"/\")\n def index():\n return f\"Hello {flask.request.args['name']}!\"\n\n @app.route(\"/meh\")\n def meh():\n return flask.request.url\n\n with app.test_request_context(\"/?name=World\"):\n assert index() == \"Hello World!\"\n with app.test_request_context(\"/meh\"):\n assert meh() == \"http://localhost/meh\"\n assert not flask.request"} {"repo":"flask","file":"tests/test_reqctx.py","line":108,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return f\"Hello {flask.request.args['name']}!\""} {"repo":"flask","file":"tests/test_reqctx.py","line":112,"symbol":"meh","kind":"function","lang":"python","code":"def meh():\n return flask.request.url"} {"repo":"flask","file":"tests/test_reqctx.py","line":122,"symbol":"test_context_test","kind":"function","lang":"python","code":"def test_context_test(app):\n assert not flask.request\n assert not flask.has_request_context()\n ctx = app.test_request_context()\n ctx.push()\n try:\n assert flask.request\n assert flask.has_request_context()\n finally:\n ctx.pop()"} {"repo":"flask","file":"tests/test_reqctx.py","line":134,"symbol":"test_manual_context_binding","kind":"function","lang":"python","code":"def test_manual_context_binding(app):\n @app.route(\"/\")\n def index():\n return f\"Hello {flask.request.args['name']}!\"\n\n ctx = app.test_request_context(\"/?name=World\")\n ctx.push()\n assert index() == \"Hello World!\"\n ctx.pop()\n with pytest.raises(RuntimeError):\n index()"} {"repo":"flask","file":"tests/test_reqctx.py","line":136,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return f\"Hello {flask.request.args['name']}!\""} {"repo":"flask","file":"tests/test_reqctx.py","line":147,"symbol":"test_copy_context_thread","kind":"function","lang":"python","code":"def test_copy_context_thread(\n request: pytest.FixtureRequest, app: flask.Flask, client: FlaskClient\n) -> None:\n executor = futures.ThreadPoolExecutor(max_workers=2)\n request.addfinalizer(lambda: executor.shutdown(cancel_futures=True))\n result: cabc.Iterator[int] | None = None\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n\n @flask.copy_current_request_context\n def work(n: int) -> int:\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session[\"fizz\"] == \"buzz\"\n return n\n\n nonlocal result\n result = executor.map(work, range(10))\n return \"Hello World!\"\n\n rv = client.get(query_string={\"foo\": \"bar\"})\n assert rv.text == \"Hello World!\"\n\n assert result is not None\n assert set(result) == set(range(10))"} {"repo":"flask","file":"tests/test_reqctx.py","line":155,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"fizz\"] = \"buzz\"\n\n @flask.copy_current_request_context\n def work(n: int) -> int:\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session[\"fizz\"] == \"buzz\"\n return n\n\n nonlocal result\n result = executor.map(work, range(10))\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_reqctx.py","line":159,"symbol":"work","kind":"function","lang":"python","code":"def work(n: int) -> int:\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session[\"fizz\"] == \"buzz\"\n return n"} {"repo":"flask","file":"tests/test_reqctx.py","line":177,"symbol":"test_session_error_pops_context","kind":"function","lang":"python","code":"def test_session_error_pops_context():\n class SessionError(Exception):\n pass\n\n class FailingSessionInterface(SessionInterface):\n def open_session(self, app, request):\n raise SessionError()\n\n class CustomFlask(flask.Flask):\n session_interface = FailingSessionInterface()\n\n app = CustomFlask(__name__)\n\n @app.route(\"/\")\n def index():\n # shouldn't get here\n AssertionError()\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 500\n assert not flask.request\n assert not flask.current_app"} {"repo":"flask","file":"tests/test_reqctx.py","line":178,"symbol":"SessionError","kind":"class","lang":"python","code":"class SessionError(Exception):\n pass"} {"repo":"flask","file":"tests/test_reqctx.py","line":181,"symbol":"FailingSessionInterface","kind":"class","lang":"python","code":"class FailingSessionInterface(SessionInterface):\n def open_session(self, app, request):\n raise SessionError()"} {"repo":"flask","file":"tests/test_reqctx.py","line":182,"symbol":"open_session","kind":"function","lang":"python","code":"def open_session(self, app, request):\n raise SessionError()"} {"repo":"flask","file":"tests/test_reqctx.py","line":185,"symbol":"CustomFlask","kind":"class","lang":"python","code":"class CustomFlask(flask.Flask):\n session_interface = FailingSessionInterface()"} {"repo":"flask","file":"tests/test_reqctx.py","line":191,"symbol":"index","kind":"function","lang":"python","code":"def index():\n # shouldn't get here\n AssertionError()"} {"repo":"flask","file":"tests/test_reqctx.py","line":201,"symbol":"test_session_dynamic_cookie_name","kind":"function","lang":"python","code":"def test_session_dynamic_cookie_name():\n # This session interface will use a cookie with a different name if the\n # requested url ends with the string \"dynamic_cookie\"\n class PathAwareSessionInterface(SecureCookieSessionInterface):\n def get_cookie_name(self, app):\n if flask.request.url.endswith(\"dynamic_cookie\"):\n return \"dynamic_cookie_name\"\n else:\n return super().get_cookie_name(app)\n\n class CustomFlask(flask.Flask):\n session_interface = PathAwareSessionInterface()\n\n app = CustomFlask(__name__)\n app.secret_key = \"secret_key\"\n\n @app.route(\"/set\", methods=[\"POST\"])\n def set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.route(\"/get\")\n def get():\n v = flask.session.get(\"value\", \"None\")\n return v\n\n @app.route(\"/set_dynamic_cookie\", methods=[\"POST\"])\n def set_dynamic_cookie():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.route(\"/get_dynamic_cookie\")\n def get_dynamic_cookie():\n v = flask.session.get(\"value\", \"None\")\n return v\n\n test_client = app.test"} {"repo":"flask","file":"tests/test_reqctx.py","line":204,"symbol":"PathAwareSessionInterface","kind":"class","lang":"python","doc":"This session interface will use a cookie with a different name if the requested url ends with the string \"dynamic_cookie\"","code":"class PathAwareSessionInterface(SecureCookieSessionInterface):\n def get_cookie_name(self, app):\n if flask.request.url.endswith(\"dynamic_cookie\"):\n return \"dynamic_cookie_name\"\n else:\n return super().get_cookie_name(app)"} {"repo":"flask","file":"tests/test_reqctx.py","line":205,"symbol":"get_cookie_name","kind":"function","lang":"python","code":"def get_cookie_name(self, app):\n if flask.request.url.endswith(\"dynamic_cookie\"):\n return \"dynamic_cookie_name\"\n else:\n return super().get_cookie_name(app)"} {"repo":"flask","file":"tests/test_reqctx.py","line":211,"symbol":"CustomFlask","kind":"class","lang":"python","code":"class CustomFlask(flask.Flask):\n session_interface = PathAwareSessionInterface()"} {"repo":"flask","file":"tests/test_reqctx.py","line":218,"symbol":"set","kind":"function","lang":"python","code":"def set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\""} {"repo":"flask","file":"tests/test_reqctx.py","line":223,"symbol":"get","kind":"function","lang":"python","code":"def get():\n v = flask.session.get(\"value\", \"None\")\n return v"} {"repo":"flask","file":"tests/test_reqctx.py","line":228,"symbol":"set_dynamic_cookie","kind":"function","lang":"python","code":"def set_dynamic_cookie():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\""} {"repo":"flask","file":"tests/test_reqctx.py","line":233,"symbol":"get_dynamic_cookie","kind":"function","lang":"python","code":"def get_dynamic_cookie():\n v = flask.session.get(\"value\", \"None\")\n return v"} {"repo":"flask","file":"tests/test_request.py","line":9,"symbol":"test_max_content_length","kind":"function","lang":"python","code":"def test_max_content_length(app: Flask, client: FlaskClient) -> None:\n app.config[\"MAX_CONTENT_LENGTH\"] = 50\n\n @app.post(\"/\")\n def index():\n request.form[\"myfile\"]\n AssertionError()\n\n @app.errorhandler(413)\n def catcher(error):\n return \"42\"\n\n rv = client.post(\"/\", data={\"myfile\": \"foo\" * 50})\n assert rv.data == b\"42\""} {"repo":"flask","file":"tests/test_request.py","line":13,"symbol":"index","kind":"function","lang":"python","code":"def index():\n request.form[\"myfile\"]\n AssertionError()"} {"repo":"flask","file":"tests/test_request.py","line":18,"symbol":"catcher","kind":"function","lang":"python","code":"def catcher(error):\n return \"42\""} {"repo":"flask","file":"tests/test_request.py","line":25,"symbol":"test_limit_config","kind":"function","lang":"python","code":"def test_limit_config(app: Flask):\n app.config[\"MAX_CONTENT_LENGTH\"] = 100\n app.config[\"MAX_FORM_MEMORY_SIZE\"] = 50\n app.config[\"MAX_FORM_PARTS\"] = 3\n r = Request({})\n\n # no app context, use Werkzeug defaults\n assert r.max_content_length is None\n assert r.max_form_memory_size == 500_000\n assert r.max_form_parts == 1_000\n\n # in app context, use config\n with app.app_context():\n assert r.max_content_length == 100\n assert r.max_form_memory_size == 50\n assert r.max_form_parts == 3\n\n # regardless of app context, use override\n r.max_content_length = 90\n r.max_form_memory_size = 30\n r.max_form_parts = 4\n\n assert r.max_content_length == 90\n assert r.max_form_memory_size == 30\n assert r.max_form_parts == 4\n\n with app.app_context():\n assert r.max_content_length == 90\n assert r.max_form_memory_size == 30\n assert r.max_form_parts == 4"} {"repo":"flask","file":"tests/test_request.py","line":57,"symbol":"test_trusted_hosts_config","kind":"function","lang":"python","code":"def test_trusted_hosts_config(app: Flask) -> None:\n app.config[\"TRUSTED_HOSTS\"] = [\"example.test\", \".other.test\"]\n\n @app.get(\"/\")\n def index() -> str:\n return \"\"\n\n client = app.test_client()\n r = client.get(base_url=\"http://example.test\")\n assert r.status_code == 200\n r = client.get(base_url=\"http://a.other.test\")\n assert r.status_code == 200\n r = client.get(base_url=\"http://bad.test\")\n assert r.status_code == 400"} {"repo":"flask","file":"tests/test_request.py","line":61,"symbol":"index","kind":"function","lang":"python","code":"def index() -> str:\n return \"\""} {"repo":"flask","file":"tests/test_session_interface.py","line":6,"symbol":"test_open_session_with_endpoint","kind":"function","lang":"python","code":"def test_open_session_with_endpoint():\n \"\"\"If request.endpoint (or other URL matching behavior) is needed\n while loading the session, RequestContext.match_request() can be\n called manually.\n \"\"\"\n\n class MySessionInterface(SessionInterface):\n def save_session(self, app, session, response):\n pass\n\n def open_session(self, app, request):\n app_ctx.match_request()\n assert request.endpoint is not None\n\n app = flask.Flask(__name__)\n app.session_interface = MySessionInterface()\n\n @app.get(\"/\")\n def index():\n return \"Hello, World!\"\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 200"} {"repo":"flask","file":"tests/test_session_interface.py","line":12,"symbol":"MySessionInterface","kind":"class","lang":"python","code":"class MySessionInterface(SessionInterface):\n def save_session(self, app, session, response):\n pass\n\n def open_session(self, app, request):\n app_ctx.match_request()\n assert request.endpoint is not None"} {"repo":"flask","file":"tests/test_session_interface.py","line":13,"symbol":"save_session","kind":"function","lang":"python","code":"def save_session(self, app, session, response):\n pass"} {"repo":"flask","file":"tests/test_session_interface.py","line":16,"symbol":"open_session","kind":"function","lang":"python","code":"def open_session(self, app, request):\n app_ctx.match_request()\n assert request.endpoint is not None"} {"repo":"flask","file":"tests/test_session_interface.py","line":24,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello, World!\""} {"repo":"flask","file":"tests/test_signals.py","line":4,"symbol":"test_template_rendered","kind":"function","lang":"python","code":"def test_template_rendered(app, client):\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n recorded.append((template, context))\n\n flask.template_rendered.connect(record, app)\n try:\n client.get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 42\n finally:\n flask.template_rendered.disconnect(record, app)"} {"repo":"flask","file":"tests/test_signals.py","line":6,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)"} {"repo":"flask","file":"tests/test_signals.py","line":11,"symbol":"record","kind":"function","lang":"python","code":"def record(sender, template, context):\n recorded.append((template, context))"} {"repo":"flask","file":"tests/test_signals.py","line":25,"symbol":"test_before_render_template","kind":"function","lang":"python","code":"def test_before_render_template():\n app = flask.Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n context[\"whiskey\"] = 43\n recorded.append((template, context))\n\n flask.before_render_template.connect(record, app)\n try:\n rv = app.test_client().get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 43\n assert rv.data == b\"

43

\"\n finally:\n flask.before_render_template.disconnect(record, app)"} {"repo":"flask","file":"tests/test_signals.py","line":29,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)"} {"repo":"flask","file":"tests/test_signals.py","line":34,"symbol":"record","kind":"function","lang":"python","code":"def record(sender, template, context):\n context[\"whiskey\"] = 43\n recorded.append((template, context))"} {"repo":"flask","file":"tests/test_signals.py","line":50,"symbol":"test_request_signals","kind":"function","lang":"python","code":"def test_request_signals():\n app = flask.Flask(__name__)\n calls = []\n\n def before_request_signal(sender):\n calls.append(\"before-signal\")\n\n def after_request_signal(sender, response):\n assert response.data == b\"stuff\"\n calls.append(\"after-signal\")\n\n @app.before_request\n def before_request_handler():\n calls.append(\"before-handler\")\n\n @app.after_request\n def after_request_handler(response):\n calls.append(\"after-handler\")\n response.data = \"stuff\"\n return response\n\n @app.route(\"/\")\n def index():\n calls.append(\"handler\")\n return \"ignored anyway\"\n\n flask.request_started.connect(before_request_signal, app)\n flask.request_finished.connect(after_request_signal, app)\n\n try:\n rv = app.test_client().get(\"/\")\n assert rv.data == b\"stuff\"\n\n assert calls == [\n \"before-signal\",\n \"before-handler\",\n \"handler\",\n \"after-handler\",\n \"after-signal\",\n ]\n finally:\n flask.request_started.disconnect(before_request_signal, app)\n flask.request_finished.disconnect(after_request_signal, app)"} {"repo":"flask","file":"tests/test_signals.py","line":54,"symbol":"before_request_signal","kind":"function","lang":"python","code":"def before_request_signal(sender):\n calls.append(\"before-signal\")"} {"repo":"flask","file":"tests/test_signals.py","line":57,"symbol":"after_request_signal","kind":"function","lang":"python","code":"def after_request_signal(sender, response):\n assert response.data == b\"stuff\"\n calls.append(\"after-signal\")"} {"repo":"flask","file":"tests/test_signals.py","line":62,"symbol":"before_request_handler","kind":"function","lang":"python","code":"def before_request_handler():\n calls.append(\"before-handler\")"} {"repo":"flask","file":"tests/test_signals.py","line":66,"symbol":"after_request_handler","kind":"function","lang":"python","code":"def after_request_handler(response):\n calls.append(\"after-handler\")\n response.data = \"stuff\"\n return response"} {"repo":"flask","file":"tests/test_signals.py","line":72,"symbol":"index","kind":"function","lang":"python","code":"def index():\n calls.append(\"handler\")\n return \"ignored anyway\""} {"repo":"flask","file":"tests/test_signals.py","line":95,"symbol":"test_request_exception_signal","kind":"function","lang":"python","code":"def test_request_exception_signal():\n app = flask.Flask(__name__)\n recorded = []\n\n @app.route(\"/\")\n def index():\n raise ZeroDivisionError\n\n def record(sender, exception):\n recorded.append(exception)\n\n flask.got_request_exception.connect(record, app)\n try:\n assert app.test_client().get(\"/\").status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.got_request_exception.disconnect(record, app)"} {"repo":"flask","file":"tests/test_signals.py","line":100,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_signals.py","line":103,"symbol":"record","kind":"function","lang":"python","code":"def record(sender, exception):\n recorded.append(exception)"} {"repo":"flask","file":"tests/test_signals.py","line":115,"symbol":"test_appcontext_signals","kind":"function","lang":"python","code":"def test_appcontext_signals(app, client):\n recorded = []\n\n def record_push(sender, **kwargs):\n recorded.append(\"push\")\n\n def record_pop(sender, **kwargs):\n recorded.append(\"pop\")\n\n @app.route(\"/\")\n def index():\n return \"Hello\"\n\n flask.appcontext_pushed.connect(record_push, app)\n flask.appcontext_popped.connect(record_pop, app)\n try:\n rv = client.get(\"/\")\n assert rv.data == b\"Hello\"\n assert recorded == [\"push\", \"pop\"]\n finally:\n flask.appcontext_pushed.disconnect(record_push, app)\n flask.appcontext_popped.disconnect(record_pop, app)"} {"repo":"flask","file":"tests/test_signals.py","line":118,"symbol":"record_push","kind":"function","lang":"python","code":"def record_push(sender, **kwargs):\n recorded.append(\"push\")"} {"repo":"flask","file":"tests/test_signals.py","line":121,"symbol":"record_pop","kind":"function","lang":"python","code":"def record_pop(sender, **kwargs):\n recorded.append(\"pop\")"} {"repo":"flask","file":"tests/test_signals.py","line":125,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return \"Hello\""} {"repo":"flask","file":"tests/test_signals.py","line":139,"symbol":"test_flash_signal","kind":"function","lang":"python","code":"def test_flash_signal(app):\n @app.route(\"/\")\n def index():\n flask.flash(\"This is a flash message\", category=\"notice\")\n return flask.redirect(\"/other\")\n\n recorded = []\n\n def record(sender, message, category):\n recorded.append((message, category))\n\n flask.message_flashed.connect(record, app)\n try:\n client = app.test_client()\n with client.session_transaction():\n client.get(\"/\")\n assert len(recorded) == 1\n message, category = recorded[0]\n assert message == \"This is a flash message\"\n assert category == \"notice\"\n finally:\n flask.message_flashed.disconnect(record, app)"} {"repo":"flask","file":"tests/test_signals.py","line":141,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.flash(\"This is a flash message\", category=\"notice\")\n return flask.redirect(\"/other\")"} {"repo":"flask","file":"tests/test_signals.py","line":147,"symbol":"record","kind":"function","lang":"python","code":"def record(sender, message, category):\n recorded.append((message, category))"} {"repo":"flask","file":"tests/test_signals.py","line":163,"symbol":"test_appcontext_tearing_down_signal","kind":"function","lang":"python","code":"def test_appcontext_tearing_down_signal(app, client):\n app.testing = False\n recorded = []\n\n def record_teardown(sender, exc):\n recorded.append(exc)\n\n @app.route(\"/\")\n def index():\n raise ZeroDivisionError\n\n flask.appcontext_tearing_down.connect(record_teardown, app)\n try:\n rv = client.get(\"/\")\n assert rv.status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.appcontext_tearing_down.disconnect(record_teardown, app)"} {"repo":"flask","file":"tests/test_signals.py","line":167,"symbol":"record_teardown","kind":"function","lang":"python","code":"def record_teardown(sender, exc):\n recorded.append(exc)"} {"repo":"flask","file":"tests/test_signals.py","line":171,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_subclassing.py","line":6,"symbol":"test_suppressed_exception_logging","kind":"function","lang":"python","code":"def test_suppressed_exception_logging():\n class SuppressedFlask(flask.Flask):\n def log_exception(self, ctx, exc_info):\n pass\n\n out = StringIO()\n app = SuppressedFlask(__name__)\n\n @app.route(\"/\")\n def index():\n raise Exception(\"test\")\n\n rv = app.test_client().get(\"/\", errors_stream=out)\n assert rv.status_code == 500\n assert b\"Internal Server Error\" in rv.data\n assert not out.getvalue()"} {"repo":"flask","file":"tests/test_subclassing.py","line":7,"symbol":"SuppressedFlask","kind":"class","lang":"python","code":"class SuppressedFlask(flask.Flask):\n def log_exception(self, ctx, exc_info):\n pass"} {"repo":"flask","file":"tests/test_subclassing.py","line":8,"symbol":"log_exception","kind":"function","lang":"python","code":"def log_exception(self, ctx, exc_info):\n pass"} {"repo":"flask","file":"tests/test_subclassing.py","line":15,"symbol":"index","kind":"function","lang":"python","code":"def index():\n raise Exception(\"test\")"} {"repo":"flask","file":"tests/test_templating.py","line":11,"symbol":"test_context_processing","kind":"function","lang":"python","code":"def test_context_processing(app, client):\n @app.context_processor\n def context_processor():\n return {\"injected_value\": 42}\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"context_template.html\", value=23)\n\n rv = client.get(\"/\")\n assert rv.data == b\"

23|42\""} {"repo":"flask","file":"tests/test_templating.py","line":13,"symbol":"context_processor","kind":"function","lang":"python","code":"def context_processor():\n return {\"injected_value\": 42}"} {"repo":"flask","file":"tests/test_templating.py","line":17,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"context_template.html\", value=23)"} {"repo":"flask","file":"tests/test_templating.py","line":24,"symbol":"test_original_win","kind":"function","lang":"python","code":"def test_original_win(app, client):\n @app.route(\"/\")\n def index():\n return flask.render_template_string(\"{{ config }}\", config=42)\n\n rv = client.get(\"/\")\n assert rv.data == b\"42\""} {"repo":"flask","file":"tests/test_templating.py","line":26,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template_string(\"{{ config }}\", config=42)"} {"repo":"flask","file":"tests/test_templating.py","line":33,"symbol":"test_simple_stream","kind":"function","lang":"python","code":"def test_simple_stream(app, client):\n @app.route(\"/\")\n def index():\n return flask.stream_template_string(\"{{ config }}\", config=42)\n\n rv = client.get(\"/\")\n assert rv.data == b\"42\""} {"repo":"flask","file":"tests/test_templating.py","line":35,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.stream_template_string(\"{{ config }}\", config=42)"} {"repo":"flask","file":"tests/test_templating.py","line":42,"symbol":"test_request_less_rendering","kind":"function","lang":"python","code":"def test_request_less_rendering(app, app_ctx):\n app.config[\"WORLD_NAME\"] = \"Special World\"\n\n @app.context_processor\n def context_processor():\n return dict(foo=42)\n\n rv = flask.render_template_string(\"Hello {{ config.WORLD_NAME }} {{ foo }}\")\n assert rv == \"Hello Special World 42\""} {"repo":"flask","file":"tests/test_templating.py","line":46,"symbol":"context_processor","kind":"function","lang":"python","code":"def context_processor():\n return dict(foo=42)"} {"repo":"flask","file":"tests/test_templating.py","line":53,"symbol":"test_standard_context","kind":"function","lang":"python","code":"def test_standard_context(app, client):\n @app.route(\"/\")\n def index():\n flask.g.foo = 23\n flask.session[\"test\"] = \"aha\"\n return flask.render_template_string(\n \"\"\"\n {{ request.args.foo }}\n {{ g.foo }}\n {{ config.DEBUG }}\n {{ session.test }}\n \"\"\"\n )\n\n rv = client.get(\"/?foo=42\")\n assert rv.data.split() == [b\"42\", b\"23\", b\"False\", b\"aha\"]"} {"repo":"flask","file":"tests/test_templating.py","line":55,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.g.foo = 23\n flask.session[\"test\"] = \"aha\"\n return flask.render_template_string(\n \"\"\"\n {{ request.args.foo }}\n {{ g.foo }}\n {{ config.DEBUG }}\n {{ session.test }}\n \"\"\"\n )"} {"repo":"flask","file":"tests/test_templating.py","line":71,"symbol":"test_escaping","kind":"function","lang":"python","code":"def test_escaping(app, client):\n text = \"

Hello World!\"\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\n \"escaping_template.html\", text=text, html=Markup(text)\n )\n\n lines = client.get(\"/\").data.splitlines()\n assert lines == [\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n ]"} {"repo":"flask","file":"tests/test_templating.py","line":75,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\n \"escaping_template.html\", text=text, html=Markup(text)\n )"} {"repo":"flask","file":"tests/test_templating.py","line":91,"symbol":"test_no_escaping","kind":"function","lang":"python","code":"def test_no_escaping(app, client):\n text = \"

Hello World!\"\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\n \"non_escaping_template.txt\", text=text, html=Markup(text)\n )\n\n lines = client.get(\"/\").data.splitlines()\n assert lines == [\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n ]"} {"repo":"flask","file":"tests/test_templating.py","line":95,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\n \"non_escaping_template.txt\", text=text, html=Markup(text)\n )"} {"repo":"flask","file":"tests/test_templating.py","line":113,"symbol":"test_escaping_without_template_filename","kind":"function","lang":"python","code":"def test_escaping_without_template_filename(app, client, req_ctx):\n assert flask.render_template_string(\"{{ foo }}\", foo=\"\") == \"<test>\"\n assert flask.render_template(\"mail.txt\", foo=\"\") == \" Mail\""} {"repo":"flask","file":"tests/test_templating.py","line":118,"symbol":"test_macros","kind":"function","lang":"python","code":"def test_macros(app, req_ctx):\n macro = flask.get_template_attribute(\"_macro.html\", \"hello\")\n assert macro(\"World\") == \"Hello World!\""} {"repo":"flask","file":"tests/test_templating.py","line":123,"symbol":"test_template_filter","kind":"function","lang":"python","code":"def test_template_filter(app):\n @app.template_filter()\n def my_reverse(s):\n return s[::-1]\n\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\"\n\n @app.template_filter\n def my_reverse_2(s):\n return s[::-1]\n\n assert \"my_reverse_2\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse_2\"] == my_reverse_2\n assert app.jinja_env.filters[\"my_reverse_2\"](\"abcd\") == \"dcba\"\n\n @app.template_filter(\"my_reverse_custom_name_3\")\n def my_reverse_3(s):\n return s[::-1]\n\n assert \"my_reverse_custom_name_3\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse_custom_name_3\"] == my_reverse_3\n assert app.jinja_env.filters[\"my_reverse_custom_name_3\"](\"abcd\") == \"dcba\"\n\n @app.template_filter(name=\"my_reverse_custom_name_4\")\n def my_reverse_4(s):\n return s[::-1]\n\n assert \"my_reverse_custom_name_4\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse_custom_name_4\"] == my_reverse_4\n assert app.jinja_env.filters[\"my_reverse_custom_name_4\"](\"ab"} {"repo":"flask","file":"tests/test_templating.py","line":125,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":133,"symbol":"my_reverse_2","kind":"function","lang":"python","code":"def my_reverse_2(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":141,"symbol":"my_reverse_3","kind":"function","lang":"python","code":"def my_reverse_3(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":149,"symbol":"my_reverse_4","kind":"function","lang":"python","code":"def my_reverse_4(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":157,"symbol":"test_add_template_filter","kind":"function","lang":"python","code":"def test_add_template_filter(app):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse)\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":158,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":167,"symbol":"test_template_filter_with_name","kind":"function","lang":"python","code":"def test_template_filter_with_name(app):\n @app.template_filter(\"strrev\")\n def my_reverse(s):\n return s[::-1]\n\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":169,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":177,"symbol":"test_add_template_filter_with_name","kind":"function","lang":"python","code":"def test_add_template_filter_with_name(app):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse, \"strrev\")\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":178,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":187,"symbol":"test_template_filter_with_template","kind":"function","lang":"python","code":"def test_template_filter_with_template(app, client):\n @app.template_filter()\n def super_reverse(s):\n return s[::-1]\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":189,"symbol":"super_reverse","kind":"function","lang":"python","code":"def super_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":193,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")"} {"repo":"flask","file":"tests/test_templating.py","line":200,"symbol":"test_add_template_filter_with_template","kind":"function","lang":"python","code":"def test_add_template_filter_with_template(app, client):\n def super_reverse(s):\n return s[::-1]\n\n app.add_template_filter(super_reverse)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":201,"symbol":"super_reverse","kind":"function","lang":"python","code":"def super_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":207,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")"} {"repo":"flask","file":"tests/test_templating.py","line":214,"symbol":"test_template_filter_with_name_and_template","kind":"function","lang":"python","code":"def test_template_filter_with_name_and_template(app, client):\n @app.template_filter(\"super_reverse\")\n def my_reverse(s):\n return s[::-1]\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":216,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":220,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")"} {"repo":"flask","file":"tests/test_templating.py","line":227,"symbol":"test_add_template_filter_with_name_and_template","kind":"function","lang":"python","code":"def test_add_template_filter_with_name_and_template(app, client):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse, \"super_reverse\")\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\""} {"repo":"flask","file":"tests/test_templating.py","line":228,"symbol":"my_reverse","kind":"function","lang":"python","code":"def my_reverse(s):\n return s[::-1]"} {"repo":"flask","file":"tests/test_templating.py","line":234,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")"} {"repo":"flask","file":"tests/test_templating.py","line":241,"symbol":"test_template_test","kind":"function","lang":"python","code":"def test_template_test(app):\n @app.template_test()\n def boolean(value):\n return isinstance(value, bool)\n\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == boolean\n assert app.jinja_env.tests[\"boolean\"](False)\n\n @app.template_test\n def boolean_2(value):\n return isinstance(value, bool)\n\n assert \"boolean_2\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean_2\"] == boolean_2\n assert app.jinja_env.tests[\"boolean_2\"](False)\n\n @app.template_test(\"my_boolean_custom_name\")\n def boolean_3(value):\n return isinstance(value, bool)\n\n assert \"my_boolean_custom_name\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"my_boolean_custom_name\"] == boolean_3\n assert app.jinja_env.tests[\"my_boolean_custom_name\"](False)\n\n @app.template_test(name=\"my_boolean_custom_name_2\")\n def boolean_4(value):\n return isinstance(value, bool)\n\n assert \"my_boolean_custom_name_2\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"my_boolean_custom_name_2\"] == boolean_4\n assert app.jinja_env.tests[\"my_boolean_custom_name_2\"](False)"} {"repo":"flask","file":"tests/test_templating.py","line":243,"symbol":"boolean","kind":"function","lang":"python","code":"def boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":251,"symbol":"boolean_2","kind":"function","lang":"python","code":"def boolean_2(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":259,"symbol":"boolean_3","kind":"function","lang":"python","code":"def boolean_3(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":267,"symbol":"boolean_4","kind":"function","lang":"python","code":"def boolean_4(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":275,"symbol":"test_add_template_test","kind":"function","lang":"python","code":"def test_add_template_test(app):\n def boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(boolean)\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == boolean\n assert app.jinja_env.tests[\"boolean\"](False)"} {"repo":"flask","file":"tests/test_templating.py","line":276,"symbol":"boolean","kind":"function","lang":"python","code":"def boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":285,"symbol":"test_template_test_with_name","kind":"function","lang":"python","code":"def test_template_test_with_name(app):\n @app.template_test(\"boolean\")\n def is_boolean(value):\n return isinstance(value, bool)\n\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == is_boolean\n assert app.jinja_env.tests[\"boolean\"](False)"} {"repo":"flask","file":"tests/test_templating.py","line":287,"symbol":"is_boolean","kind":"function","lang":"python","code":"def is_boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":295,"symbol":"test_add_template_test_with_name","kind":"function","lang":"python","code":"def test_add_template_test_with_name(app):\n def is_boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(is_boolean, \"boolean\")\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == is_boolean\n assert app.jinja_env.tests[\"boolean\"](False)"} {"repo":"flask","file":"tests/test_templating.py","line":296,"symbol":"is_boolean","kind":"function","lang":"python","code":"def is_boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":305,"symbol":"test_template_test_with_template","kind":"function","lang":"python","code":"def test_template_test_with_template(app, client):\n @app.template_test()\n def boolean(value):\n return isinstance(value, bool)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data"} {"repo":"flask","file":"tests/test_templating.py","line":307,"symbol":"boolean","kind":"function","lang":"python","code":"def boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":311,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_test.html\", value=False)"} {"repo":"flask","file":"tests/test_templating.py","line":318,"symbol":"test_add_template_test_with_template","kind":"function","lang":"python","code":"def test_add_template_test_with_template(app, client):\n def boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(boolean)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data"} {"repo":"flask","file":"tests/test_templating.py","line":319,"symbol":"boolean","kind":"function","lang":"python","code":"def boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":325,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_test.html\", value=False)"} {"repo":"flask","file":"tests/test_templating.py","line":332,"symbol":"test_template_test_with_name_and_template","kind":"function","lang":"python","code":"def test_template_test_with_name_and_template(app, client):\n @app.template_test(\"boolean\")\n def is_boolean(value):\n return isinstance(value, bool)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data"} {"repo":"flask","file":"tests/test_templating.py","line":334,"symbol":"is_boolean","kind":"function","lang":"python","code":"def is_boolean(value):\n return isinstance(value, bool)"} {"repo":"flask","file":"tests/test_templating.py","line":338,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.render_template(\"template_test.html\", value=False)"} {"repo":"flask","file":"tests/test_testing.py","line":15,"symbol":"test_environ_defaults_from_config","kind":"function","lang":"python","code":"def test_environ_defaults_from_config(app, client):\n app.config[\"SERVER_NAME\"] = \"example.com:1234\"\n app.config[\"APPLICATION_ROOT\"] = \"/foo\"\n\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context()\n assert ctx.request.url == \"http://example.com:1234/foo/\"\n\n rv = client.get(\"/\")\n assert rv.data == b\"http://example.com:1234/foo/\""} {"repo":"flask","file":"tests/test_testing.py","line":20,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.url"} {"repo":"flask","file":"tests/test_testing.py","line":30,"symbol":"test_environ_defaults","kind":"function","lang":"python","code":"def test_environ_defaults(app, client, app_ctx, req_ctx):\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context()\n assert ctx.request.url == \"http://localhost/\"\n with client:\n rv = client.get(\"/\")\n assert rv.data == b\"http://localhost/\""} {"repo":"flask","file":"tests/test_testing.py","line":32,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.url"} {"repo":"flask","file":"tests/test_testing.py","line":42,"symbol":"test_environ_base_default","kind":"function","lang":"python","code":"def test_environ_base_default(app, client):\n @app.route(\"/\")\n def index():\n flask.g.remote_addr = flask.request.remote_addr\n flask.g.user_agent = flask.request.user_agent.string\n return \"\"\n\n with client:\n client.get(\"/\")\n assert flask.g.remote_addr == \"127.0.0.1\"\n assert flask.g.user_agent == (\n f\"Werkzeug/{importlib.metadata.version('werkzeug')}\"\n )"} {"repo":"flask","file":"tests/test_testing.py","line":44,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.g.remote_addr = flask.request.remote_addr\n flask.g.user_agent = flask.request.user_agent.string\n return \"\""} {"repo":"flask","file":"tests/test_testing.py","line":57,"symbol":"test_environ_base_modified","kind":"function","lang":"python","code":"def test_environ_base_modified(app, client):\n @app.route(\"/\")\n def index():\n flask.g.remote_addr = flask.request.remote_addr\n flask.g.user_agent = flask.request.user_agent.string\n return \"\"\n\n client.environ_base[\"REMOTE_ADDR\"] = \"192.168.0.22\"\n client.environ_base[\"HTTP_USER_AGENT\"] = \"Foo\"\n\n with client:\n client.get(\"/\")\n assert flask.g.remote_addr == \"192.168.0.22\"\n assert flask.g.user_agent == \"Foo\""} {"repo":"flask","file":"tests/test_testing.py","line":59,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.g.remote_addr = flask.request.remote_addr\n flask.g.user_agent = flask.request.user_agent.string\n return \"\""} {"repo":"flask","file":"tests/test_testing.py","line":73,"symbol":"test_client_open_environ","kind":"function","lang":"python","code":"def test_client_open_environ(app, client, request):\n @app.route(\"/index\")\n def index():\n return flask.request.remote_addr\n\n builder = EnvironBuilder(app, path=\"/index\", method=\"GET\")\n\n rv = client.open(builder)\n assert rv.data == b\"127.0.0.1\"\n\n environ = builder.get_environ()\n client.environ_base[\"REMOTE_ADDR\"] = \"127.0.0.2\"\n rv = client.open(environ)\n assert rv.data == b\"127.0.0.2\""} {"repo":"flask","file":"tests/test_testing.py","line":75,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.remote_addr"} {"repo":"flask","file":"tests/test_testing.py","line":89,"symbol":"test_specify_url_scheme","kind":"function","lang":"python","code":"def test_specify_url_scheme(app, client):\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context(url_scheme=\"https\")\n assert ctx.request.url == \"https://localhost/\"\n\n rv = client.get(\"/\", url_scheme=\"https\")\n assert rv.data == b\"https://localhost/\""} {"repo":"flask","file":"tests/test_testing.py","line":91,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.url"} {"repo":"flask","file":"tests/test_testing.py","line":101,"symbol":"test_path_is_url","kind":"function","lang":"python","code":"def test_path_is_url(app):\n eb = EnvironBuilder(app, \"https://example.com/\")\n assert eb.url_scheme == \"https\"\n assert eb.host == \"example.com\"\n assert eb.script_root == \"\"\n assert eb.path == \"/\""} {"repo":"flask","file":"tests/test_testing.py","line":109,"symbol":"test_environbuilder_json_dumps","kind":"function","lang":"python","code":"def test_environbuilder_json_dumps(app):\n \"\"\"EnvironBuilder.json_dumps() takes settings from the app.\"\"\"\n app.json.ensure_ascii = False\n eb = EnvironBuilder(app, json=\"\\u20ac\")\n assert eb.input_stream.read().decode(\"utf8\") == '\"\\u20ac\"'"} {"repo":"flask","file":"tests/test_testing.py","line":116,"symbol":"test_blueprint_with_subdomain","kind":"function","lang":"python","code":"def test_blueprint_with_subdomain():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"example.com:1234\"\n app.config[\"APPLICATION_ROOT\"] = \"/foo\"\n client = app.test_client()\n\n bp = flask.Blueprint(\"company\", __name__, subdomain=\"xxx\")\n\n @bp.route(\"/\")\n def index():\n return flask.request.url\n\n app.register_blueprint(bp)\n\n ctx = app.test_request_context(\"/\", subdomain=\"xxx\")\n assert ctx.request.url == \"http://xxx.example.com:1234/foo/\"\n\n with ctx:\n assert ctx.request.blueprint == bp.name\n\n rv = client.get(\"/\", subdomain=\"xxx\")\n assert rv.data == b\"http://xxx.example.com:1234/foo/\""} {"repo":"flask","file":"tests/test_testing.py","line":125,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return flask.request.url"} {"repo":"flask","file":"tests/test_testing.py","line":140,"symbol":"test_redirect_session","kind":"function","lang":"python","code":"def test_redirect_session(app, client, app_ctx):\n @app.route(\"/redirect\")\n def index():\n flask.session[\"redirect\"] = True\n return flask.redirect(\"/target\")\n\n @app.route(\"/target\")\n def get_session():\n flask.session[\"target\"] = True\n return \"\"\n\n with client:\n client.get(\"/redirect\", follow_redirects=True)\n assert flask.session[\"redirect\"] is True\n assert flask.session[\"target\"] is True"} {"repo":"flask","file":"tests/test_testing.py","line":142,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.session[\"redirect\"] = True\n return flask.redirect(\"/target\")"} {"repo":"flask","file":"tests/test_testing.py","line":147,"symbol":"get_session","kind":"function","lang":"python","code":"def get_session():\n flask.session[\"target\"] = True\n return \"\""} {"repo":"flask","file":"tests/test_testing.py","line":157,"symbol":"test_session_transactions","kind":"function","lang":"python","code":"def test_session_transactions(app, client):\n @app.route(\"/\")\n def index():\n return str(flask.session[\"foo\"])\n\n with client:\n with client.session_transaction() as sess:\n assert len(sess) == 0\n sess[\"foo\"] = [42]\n assert len(sess) == 1\n rv = client.get(\"/\")\n assert rv.data == b\"[42]\"\n with client.session_transaction() as sess:\n assert len(sess) == 1\n assert sess[\"foo\"] == [42]"} {"repo":"flask","file":"tests/test_testing.py","line":159,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return str(flask.session[\"foo\"])"} {"repo":"flask","file":"tests/test_testing.py","line":174,"symbol":"test_session_transaction_ipv6","kind":"function","lang":"python","code":"def test_session_transaction_ipv6(app):\n base_url = \"http://[::1]:8000/\"\n client = app.test_client()\n\n @app.get(\"/\")\n def index():\n return str(flask.session.get(\"value\"))\n\n with client.session_transaction(base_url=base_url) as sess:\n sess[\"value\"] = 42\n\n assert client.get(\"/\", base_url=base_url).text == \"42\""} {"repo":"flask","file":"tests/test_testing.py","line":179,"symbol":"index","kind":"function","lang":"python","code":"def index():\n return str(flask.session.get(\"value\"))"} {"repo":"flask","file":"tests/test_testing.py","line":188,"symbol":"test_session_transactions_no_null_sessions","kind":"function","lang":"python","code":"def test_session_transactions_no_null_sessions():\n app = flask.Flask(__name__)\n\n with app.test_client() as c:\n with pytest.raises(RuntimeError) as e:\n with c.session_transaction():\n pass\n assert \"Session backend did not open a session\" in str(e.value)"} {"repo":"flask","file":"tests/test_testing.py","line":198,"symbol":"test_session_transactions_keep_context","kind":"function","lang":"python","code":"def test_session_transactions_keep_context(app, client, req_ctx):\n client.get(\"/\")\n req = flask.request._get_current_object()\n assert req is not None\n with client.session_transaction():\n assert req is flask.request._get_current_object()"} {"repo":"flask","file":"tests/test_testing.py","line":206,"symbol":"test_session_transaction_needs_cookies","kind":"function","lang":"python","code":"def test_session_transaction_needs_cookies(app):\n c = app.test_client(use_cookies=False)\n\n with pytest.raises(TypeError, match=\"Cookies are disabled.\"):\n with c.session_transaction():\n pass"} {"repo":"flask","file":"tests/test_testing.py","line":214,"symbol":"test_test_client_context_binding","kind":"function","lang":"python","code":"def test_test_client_context_binding(app, client):\n app.testing = False\n\n @app.route(\"/\")\n def index():\n flask.g.value = 42\n return \"Hello World!\"\n\n @app.route(\"/other\")\n def other():\n raise ZeroDivisionError\n\n with client:\n resp = client.get(\"/\")\n assert flask.g.value == 42\n assert resp.data == b\"Hello World!\"\n assert resp.status_code == 200\n\n with client:\n resp = client.get(\"/other\")\n assert not hasattr(flask.g, \"value\")\n assert b\"Internal Server Error\" in resp.data\n assert resp.status_code == 500\n flask.g.value = 23\n\n with pytest.raises(RuntimeError):\n flask.g.value # noqa: B018"} {"repo":"flask","file":"tests/test_testing.py","line":218,"symbol":"index","kind":"function","lang":"python","code":"def index():\n flask.g.value = 42\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_testing.py","line":223,"symbol":"other","kind":"function","lang":"python","code":"def other():\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_testing.py","line":243,"symbol":"test_reuse_client","kind":"function","lang":"python","code":"def test_reuse_client(client):\n c = client\n\n with c:\n assert client.get(\"/\").status_code == 404\n\n with c:\n assert client.get(\"/\").status_code == 404"} {"repo":"flask","file":"tests/test_testing.py","line":253,"symbol":"test_full_url_request","kind":"function","lang":"python","code":"def test_full_url_request(app, client):\n @app.route(\"/action\", methods=[\"POST\"])\n def action():\n return \"x\"\n\n with client:\n rv = client.post(\"http://domain.com/action?vodka=42\", data={\"gin\": 43})\n assert rv.status_code == 200\n assert \"gin\" in flask.request.form\n assert \"vodka\" in flask.request.args"} {"repo":"flask","file":"tests/test_testing.py","line":255,"symbol":"action","kind":"function","lang":"python","code":"def action():\n return \"x\""} {"repo":"flask","file":"tests/test_testing.py","line":265,"symbol":"test_json_request_and_response","kind":"function","lang":"python","code":"def test_json_request_and_response(app, client):\n @app.route(\"/echo\", methods=[\"POST\"])\n def echo():\n return jsonify(flask.request.get_json())\n\n with client:\n json_data = {\"drink\": {\"gin\": 1, \"tonic\": True}, \"price\": 10}\n rv = client.post(\"/echo\", json=json_data)\n\n # Request should be in JSON\n assert flask.request.is_json\n assert flask.request.get_json() == json_data\n\n # Response should be in JSON\n assert rv.status_code == 200\n assert rv.is_json\n assert rv.get_json() == json_data"} {"repo":"flask","file":"tests/test_testing.py","line":267,"symbol":"echo","kind":"function","lang":"python","code":"def echo():\n return jsonify(flask.request.get_json())"} {"repo":"flask","file":"tests/test_testing.py","line":284,"symbol":"test_client_json_no_app_context","kind":"function","lang":"python","code":"def test_client_json_no_app_context(app, client):\n @app.route(\"/hello\", methods=[\"POST\"])\n def hello():\n return f\"Hello, {flask.request.json['name']}!\"\n\n class Namespace:\n count = 0\n\n def add(self, app):\n self.count += 1\n\n ns = Namespace()\n\n with appcontext_popped.connected_to(ns.add, app):\n rv = client.post(\"/hello\", json={\"name\": \"Flask\"})\n\n assert rv.get_data(as_text=True) == \"Hello, Flask!\"\n assert ns.count == 1"} {"repo":"flask","file":"tests/test_testing.py","line":286,"symbol":"hello","kind":"function","lang":"python","code":"def hello():\n return f\"Hello, {flask.request.json['name']}!\""} {"repo":"flask","file":"tests/test_testing.py","line":289,"symbol":"Namespace","kind":"class","lang":"python","code":"class Namespace:\n count = 0\n\n def add(self, app):\n self.count += 1"} {"repo":"flask","file":"tests/test_testing.py","line":292,"symbol":"add","kind":"function","lang":"python","code":"def add(self, app):\n self.count += 1"} {"repo":"flask","file":"tests/test_testing.py","line":304,"symbol":"test_subdomain","kind":"function","lang":"python","code":"def test_subdomain():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"example.com\"\n client = app.test_client()\n\n @app.route(\"/\", subdomain=\"\")\n def view(company_id):\n return company_id\n\n with app.test_request_context():\n url = flask.url_for(\"view\", company_id=\"xxx\")\n\n with client:\n response = client.get(url)\n\n assert 200 == response.status_code\n assert b\"xxx\" == response.data"} {"repo":"flask","file":"tests/test_testing.py","line":310,"symbol":"view","kind":"function","lang":"python","code":"def view(company_id):\n return company_id"} {"repo":"flask","file":"tests/test_testing.py","line":323,"symbol":"test_nosubdomain","kind":"function","lang":"python","code":"def test_nosubdomain(app, client):\n app.config[\"SERVER_NAME\"] = \"example.com\"\n\n @app.route(\"/\")\n def view(company_id):\n return company_id\n\n with app.test_request_context():\n url = flask.url_for(\"view\", company_id=\"xxx\")\n\n with client:\n response = client.get(url)\n\n assert 200 == response.status_code\n assert b\"xxx\" == response.data"} {"repo":"flask","file":"tests/test_testing.py","line":327,"symbol":"view","kind":"function","lang":"python","code":"def view(company_id):\n return company_id"} {"repo":"flask","file":"tests/test_testing.py","line":340,"symbol":"test_cli_runner_class","kind":"function","lang":"python","code":"def test_cli_runner_class(app):\n runner = app.test_cli_runner()\n assert isinstance(runner, FlaskCliRunner)\n\n class SubRunner(FlaskCliRunner):\n pass\n\n app.test_cli_runner_class = SubRunner\n runner = app.test_cli_runner()\n assert isinstance(runner, SubRunner)"} {"repo":"flask","file":"tests/test_testing.py","line":344,"symbol":"SubRunner","kind":"class","lang":"python","code":"class SubRunner(FlaskCliRunner):\n pass"} {"repo":"flask","file":"tests/test_testing.py","line":352,"symbol":"test_cli_invoke","kind":"function","lang":"python","code":"def test_cli_invoke(app):\n @app.cli.command(\"hello\")\n def hello_command():\n click.echo(\"Hello, World!\")\n\n runner = app.test_cli_runner()\n # invoke with command name\n result = runner.invoke(args=[\"hello\"])\n assert \"Hello\" in result.output\n # invoke with command object\n result = runner.invoke(hello_command)\n assert \"Hello\" in result.output"} {"repo":"flask","file":"tests/test_testing.py","line":354,"symbol":"hello_command","kind":"function","lang":"python","code":"def hello_command():\n click.echo(\"Hello, World!\")"} {"repo":"flask","file":"tests/test_testing.py","line":366,"symbol":"test_cli_custom_obj","kind":"function","lang":"python","code":"def test_cli_custom_obj(app):\n class NS:\n called = False\n\n def create_app():\n NS.called = True\n return app\n\n @app.cli.command(\"hello\")\n def hello_command():\n click.echo(\"Hello, World!\")\n\n script_info = ScriptInfo(create_app=create_app)\n runner = app.test_cli_runner()\n runner.invoke(hello_command, obj=script_info)\n assert NS.called"} {"repo":"flask","file":"tests/test_testing.py","line":367,"symbol":"NS","kind":"class","lang":"python","code":"class NS:\n called = False"} {"repo":"flask","file":"tests/test_testing.py","line":370,"symbol":"create_app","kind":"function","lang":"python","code":"def create_app():\n NS.called = True\n return app"} {"repo":"flask","file":"tests/test_testing.py","line":375,"symbol":"hello_command","kind":"function","lang":"python","code":"def hello_command():\n click.echo(\"Hello, World!\")"} {"repo":"flask","file":"tests/test_testing.py","line":384,"symbol":"test_client_pop_all_preserved","kind":"function","lang":"python","code":"def test_client_pop_all_preserved(app, req_ctx, client):\n @app.route(\"/\")\n def index():\n # stream_with_context pushes a third context, preserved by response\n return flask.stream_with_context(\"hello\")\n\n # req_ctx fixture pushed an initial context\n with client:\n # request pushes a second request context, preserved by client\n rv = client.get(\"/\")\n\n # close the response, releasing the context held by stream_with_context\n rv.close()\n # only req_ctx fixture should still be pushed\n assert _cv_app.get(None) is req_ctx"} {"repo":"flask","file":"tests/test_testing.py","line":386,"symbol":"index","kind":"function","lang":"python","code":"def index():\n # stream_with_context pushes a third context, preserved by response\n return flask.stream_with_context(\"hello\")"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":10,"symbol":"test_error_handler_no_match","kind":"function","lang":"python","code":"def test_error_handler_no_match(app, client):\n class CustomException(Exception):\n pass\n\n @app.errorhandler(CustomException)\n def custom_exception_handler(e):\n assert isinstance(e, CustomException)\n return \"custom\"\n\n with pytest.raises(TypeError) as exc_info:\n app.register_error_handler(CustomException(), None)\n\n assert \"CustomException() is an instance, not a class.\" in str(exc_info.value)\n\n with pytest.raises(ValueError) as exc_info:\n app.register_error_handler(list, None)\n\n assert \"'list' is not a subclass of Exception.\" in str(exc_info.value)\n\n @app.errorhandler(500)\n def handle_500(e):\n assert isinstance(e, InternalServerError)\n\n if e.original_exception is not None:\n return f\"wrapped {type(e.original_exception).__name__}\"\n\n return \"direct\"\n\n with pytest.raises(ValueError) as exc_info:\n app.register_error_handler(999, None)\n\n assert \"Use a subclass of HTTPException\" in str(exc_info.value)\n\n @app.route(\"/custom\")\n def custom_test():\n raise CustomException()\n\n @app.route(\"/keyerror\")\n def key_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n d"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":11,"symbol":"CustomException","kind":"class","lang":"python","code":"class CustomException(Exception):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":15,"symbol":"custom_exception_handler","kind":"function","lang":"python","code":"def custom_exception_handler(e):\n assert isinstance(e, CustomException)\n return \"custom\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":30,"symbol":"handle_500","kind":"function","lang":"python","code":"def handle_500(e):\n assert isinstance(e, InternalServerError)\n\n if e.original_exception is not None:\n return f\"wrapped {type(e.original_exception).__name__}\"\n\n return \"direct\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":44,"symbol":"custom_test","kind":"function","lang":"python","code":"def custom_test():\n raise CustomException()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":48,"symbol":"key_error","kind":"function","lang":"python","code":"def key_error():\n raise KeyError()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":52,"symbol":"do_abort","kind":"function","lang":"python","code":"def do_abort():\n flask.abort(500)"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":61,"symbol":"test_error_handler_subclass","kind":"function","lang":"python","code":"def test_error_handler_subclass(app):\n class ParentException(Exception):\n pass\n\n class ChildExceptionUnregistered(ParentException):\n pass\n\n class ChildExceptionRegistered(ParentException):\n pass\n\n @app.errorhandler(ParentException)\n def parent_exception_handler(e):\n assert isinstance(e, ParentException)\n return \"parent\"\n\n @app.errorhandler(ChildExceptionRegistered)\n def child_exception_handler(e):\n assert isinstance(e, ChildExceptionRegistered)\n return \"child-registered\"\n\n @app.route(\"/parent\")\n def parent_test():\n raise ParentException()\n\n @app.route(\"/child-unregistered\")\n def unregistered_test():\n raise ChildExceptionUnregistered()\n\n @app.route(\"/child-registered\")\n def registered_test():\n raise ChildExceptionRegistered()\n\n c = app.test_client()\n\n assert c.get(\"/parent\").data == b\"parent\"\n assert c.get(\"/child-unregistered\").data == b\"parent\"\n assert c.get(\"/child-registered\").data == b\"child-registered\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":62,"symbol":"ParentException","kind":"class","lang":"python","code":"class ParentException(Exception):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":65,"symbol":"ChildExceptionUnregistered","kind":"class","lang":"python","code":"class ChildExceptionUnregistered(ParentException):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":68,"symbol":"ChildExceptionRegistered","kind":"class","lang":"python","code":"class ChildExceptionRegistered(ParentException):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":72,"symbol":"parent_exception_handler","kind":"function","lang":"python","code":"def parent_exception_handler(e):\n assert isinstance(e, ParentException)\n return \"parent\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":77,"symbol":"child_exception_handler","kind":"function","lang":"python","code":"def child_exception_handler(e):\n assert isinstance(e, ChildExceptionRegistered)\n return \"child-registered\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":82,"symbol":"parent_test","kind":"function","lang":"python","code":"def parent_test():\n raise ParentException()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":86,"symbol":"unregistered_test","kind":"function","lang":"python","code":"def unregistered_test():\n raise ChildExceptionUnregistered()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":90,"symbol":"registered_test","kind":"function","lang":"python","code":"def registered_test():\n raise ChildExceptionRegistered()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":100,"symbol":"test_error_handler_http_subclass","kind":"function","lang":"python","code":"def test_error_handler_http_subclass(app):\n class ForbiddenSubclassRegistered(Forbidden):\n pass\n\n class ForbiddenSubclassUnregistered(Forbidden):\n pass\n\n @app.errorhandler(403)\n def code_exception_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\"\n\n @app.errorhandler(ForbiddenSubclassRegistered)\n def subclass_exception_handler(e):\n assert isinstance(e, ForbiddenSubclassRegistered)\n return \"forbidden-registered\"\n\n @app.route(\"/forbidden\")\n def forbidden_test():\n raise Forbidden()\n\n @app.route(\"/forbidden-registered\")\n def registered_test():\n raise ForbiddenSubclassRegistered()\n\n @app.route(\"/forbidden-unregistered\")\n def unregistered_test():\n raise ForbiddenSubclassUnregistered()\n\n c = app.test_client()\n\n assert c.get(\"/forbidden\").data == b\"forbidden\"\n assert c.get(\"/forbidden-unregistered\").data == b\"forbidden\"\n assert c.get(\"/forbidden-registered\").data == b\"forbidden-registered\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":101,"symbol":"ForbiddenSubclassRegistered","kind":"class","lang":"python","code":"class ForbiddenSubclassRegistered(Forbidden):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":104,"symbol":"ForbiddenSubclassUnregistered","kind":"class","lang":"python","code":"class ForbiddenSubclassUnregistered(Forbidden):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":108,"symbol":"code_exception_handler","kind":"function","lang":"python","code":"def code_exception_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":113,"symbol":"subclass_exception_handler","kind":"function","lang":"python","code":"def subclass_exception_handler(e):\n assert isinstance(e, ForbiddenSubclassRegistered)\n return \"forbidden-registered\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":118,"symbol":"forbidden_test","kind":"function","lang":"python","code":"def forbidden_test():\n raise Forbidden()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":122,"symbol":"registered_test","kind":"function","lang":"python","code":"def registered_test():\n raise ForbiddenSubclassRegistered()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":126,"symbol":"unregistered_test","kind":"function","lang":"python","code":"def unregistered_test():\n raise ForbiddenSubclassUnregistered()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":136,"symbol":"test_error_handler_blueprint","kind":"function","lang":"python","code":"def test_error_handler_blueprint(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.errorhandler(500)\n def bp_exception_handler(e):\n return \"bp-error\"\n\n @bp.route(\"/error\")\n def bp_test():\n raise InternalServerError()\n\n @app.errorhandler(500)\n def app_exception_handler(e):\n return \"app-error\"\n\n @app.route(\"/error\")\n def app_test():\n raise InternalServerError()\n\n app.register_blueprint(bp, url_prefix=\"/bp\")\n\n c = app.test_client()\n\n assert c.get(\"/error\").data == b\"app-error\"\n assert c.get(\"/bp/error\").data == b\"bp-error\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":140,"symbol":"bp_exception_handler","kind":"function","lang":"python","code":"def bp_exception_handler(e):\n return \"bp-error\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":144,"symbol":"bp_test","kind":"function","lang":"python","code":"def bp_test():\n raise InternalServerError()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":148,"symbol":"app_exception_handler","kind":"function","lang":"python","code":"def app_exception_handler(e):\n return \"app-error\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":152,"symbol":"app_test","kind":"function","lang":"python","code":"def app_test():\n raise InternalServerError()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":163,"symbol":"test_default_error_handler","kind":"function","lang":"python","code":"def test_default_error_handler():\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.errorhandler(HTTPException)\n def bp_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"bp-default\"\n\n @bp.errorhandler(Forbidden)\n def bp_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"bp-forbidden\"\n\n @bp.route(\"/undefined\")\n def bp_registered_test():\n raise NotFound()\n\n @bp.route(\"/forbidden\")\n def bp_forbidden_test():\n raise Forbidden()\n\n app = flask.Flask(__name__)\n\n @app.errorhandler(HTTPException)\n def catchall_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"default\"\n\n @app.errorhandler(Forbidden)\n def catchall_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\"\n\n @app.route(\"/forbidden\")\n def forbidden():\n raise Forbidden()\n\n @app.route(\"/slash/\")\n def slash():\n return \"slash\"\n\n app.register_blueprint(bp, url_prefix=\"/bp\")\n\n c = app.test_client()\n assert c.get(\"/bp/undefined\").data == b\"bp-default\"\n a"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":167,"symbol":"bp_exception_handler","kind":"function","lang":"python","code":"def bp_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"bp-default\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":173,"symbol":"bp_forbidden_handler","kind":"function","lang":"python","code":"def bp_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"bp-forbidden\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":178,"symbol":"bp_registered_test","kind":"function","lang":"python","code":"def bp_registered_test():\n raise NotFound()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":182,"symbol":"bp_forbidden_test","kind":"function","lang":"python","code":"def bp_forbidden_test():\n raise Forbidden()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":188,"symbol":"catchall_exception_handler","kind":"function","lang":"python","code":"def catchall_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"default\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":194,"symbol":"catchall_forbidden_handler","kind":"function","lang":"python","code":"def catchall_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":199,"symbol":"forbidden","kind":"function","lang":"python","code":"def forbidden():\n raise Forbidden()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":203,"symbol":"slash","kind":"function","lang":"python","code":"def slash():\n return \"slash\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":217,"symbol":"TestGenericHandlers","kind":"class","lang":"python","code":"class TestGenericHandlers:\n \"\"\"Test how very generic handlers are dispatched to.\"\"\"\n\n class Custom(Exception):\n pass\n\n @pytest.fixture()\n def app(self, app):\n @app.route(\"/custom\")\n def do_custom():\n raise self.Custom()\n\n @app.route(\"/error\")\n def do_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n @app.route(\"/raise\")\n def do_raise():\n raise InternalServerError()\n\n app.config[\"PROPAGATE_EXCEPTIONS\"] = False\n return app\n\n def report_error(self, e):\n original = getattr(e, \"original_exception\", None)\n\n if original is not None:\n return f\"wrapped {type(original).__name__}\"\n\n return f\"direct {type(e).__name__}\"\n\n @pytest.mark.parametrize(\"to_handle\", (InternalServerError, 500))\n def test_handle_class_or_code(self, app, client, to_handle):\n \"\"\"``InternalServerError`` and ``500`` are aliases, they should\n have the same behavior. Both should only receive\n ``InternalServerError``, which might wrap another error.\n \"\"\"\n\n @app.errorhandler(to_handle)\n"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":220,"symbol":"Custom","kind":"class","lang":"python","code":"class Custom(Exception):\n pass"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":224,"symbol":"app","kind":"function","lang":"python","code":"def app(self, app):\n @app.route(\"/custom\")\n def do_custom():\n raise self.Custom()\n\n @app.route(\"/error\")\n def do_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n @app.route(\"/raise\")\n def do_raise():\n raise InternalServerError()\n\n app.config[\"PROPAGATE_EXCEPTIONS\"] = False\n return app"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":226,"symbol":"do_custom","kind":"function","lang":"python","code":"def do_custom():\n raise self.Custom()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":230,"symbol":"do_error","kind":"function","lang":"python","code":"def do_error():\n raise KeyError()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":234,"symbol":"do_abort","kind":"function","lang":"python","code":"def do_abort():\n flask.abort(500)"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":238,"symbol":"do_raise","kind":"function","lang":"python","code":"def do_raise():\n raise InternalServerError()"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":244,"symbol":"report_error","kind":"function","lang":"python","code":"def report_error(self, e):\n original = getattr(e, \"original_exception\", None)\n\n if original is not None:\n return f\"wrapped {type(original).__name__}\"\n\n return f\"direct {type(e).__name__}\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":253,"symbol":"test_handle_class_or_code","kind":"function","lang":"python","code":"def test_handle_class_or_code(self, app, client, to_handle):\n \"\"\"``InternalServerError`` and ``500`` are aliases, they should\n have the same behavior. Both should only receive\n ``InternalServerError``, which might wrap another error.\n \"\"\"\n\n @app.errorhandler(to_handle)\n def handle_500(e):\n assert isinstance(e, InternalServerError)\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"wrapped Custom\"\n assert client.get(\"/error\").data == b\"wrapped KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/raise\").data == b\"direct InternalServerError\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":260,"symbol":"handle_500","kind":"function","lang":"python","code":"def handle_500(e):\n assert isinstance(e, InternalServerError)\n return self.report_error(e)"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":269,"symbol":"test_handle_generic_http","kind":"function","lang":"python","code":"def test_handle_generic_http(self, app, client):\n \"\"\"``HTTPException`` should only receive ``HTTPException``\n subclasses. It will receive ``404`` routing exceptions.\n \"\"\"\n\n @app.errorhandler(HTTPException)\n def handle_http(e):\n assert isinstance(e, HTTPException)\n return str(e.code)\n\n assert client.get(\"/error\").data == b\"500\"\n assert client.get(\"/abort\").data == b\"500\"\n assert client.get(\"/not-found\").data == b\"404\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":275,"symbol":"handle_http","kind":"function","lang":"python","code":"def handle_http(e):\n assert isinstance(e, HTTPException)\n return str(e.code)"} {"repo":"flask","file":"tests/test_user_error_handler.py","line":283,"symbol":"test_handle_generic","kind":"function","lang":"python","code":"def test_handle_generic(self, app, client):\n \"\"\"Generic ``Exception`` will handle all exceptions directly,\n including ``HTTPExceptions``.\n \"\"\"\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"direct Custom\"\n assert client.get(\"/error\").data == b\"direct KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/not-found\").data == b\"direct NotFound\""} {"repo":"flask","file":"tests/test_user_error_handler.py","line":289,"symbol":"handle_exception","kind":"function","lang":"python","code":"def handle_exception(e):\n return self.report_error(e)"} {"repo":"flask","file":"tests/test_views.py","line":7,"symbol":"common_test","kind":"function","lang":"python","code":"def common_test(app):\n c = app.test_client()\n\n assert c.get(\"/\").data == b\"GET\"\n assert c.post(\"/\").data == b\"POST\"\n assert c.put(\"/\").status_code == 405\n meths = c.open(\"/\", method=\"OPTIONS\").allow\n assert meths == {\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"}"} {"repo":"flask","file":"tests/test_views.py","line":17,"symbol":"test_basic_view","kind":"function","lang":"python","code":"def test_basic_view(app):\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n common_test(app)"} {"repo":"flask","file":"tests/test_views.py","line":18,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method"} {"repo":"flask","file":"tests/test_views.py","line":21,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return flask.request.method"} {"repo":"flask","file":"tests/test_views.py","line":28,"symbol":"test_method_based_view","kind":"function","lang":"python","code":"def test_method_based_view(app):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n common_test(app)"} {"repo":"flask","file":"tests/test_views.py","line":29,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":30,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":33,"symbol":"post","kind":"function","lang":"python","code":"def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":41,"symbol":"test_view_patching","kind":"function","lang":"python","code":"def test_view_patching(app):\n class Index(flask.views.MethodView):\n def get(self):\n raise ZeroDivisionError\n\n def post(self):\n raise ZeroDivisionError\n\n class Other(Index):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n view = Index.as_view(\"index\")\n view.view_class = Other\n app.add_url_rule(\"/\", view_func=view)\n common_test(app)"} {"repo":"flask","file":"tests/test_views.py","line":42,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.MethodView):\n def get(self):\n raise ZeroDivisionError\n\n def post(self):\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_views.py","line":43,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_views.py","line":46,"symbol":"post","kind":"function","lang":"python","code":"def post(self):\n raise ZeroDivisionError"} {"repo":"flask","file":"tests/test_views.py","line":49,"symbol":"Other","kind":"class","lang":"python","code":"class Other(Index):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":50,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":53,"symbol":"post","kind":"function","lang":"python","code":"def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":62,"symbol":"test_view_inheritance","kind":"function","lang":"python","code":"def test_view_inheritance(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n class BetterIndex(Index):\n def delete(self):\n return \"DELETE\"\n\n app.add_url_rule(\"/\", view_func=BetterIndex.as_view(\"index\"))\n\n meths = client.open(\"/\", method=\"OPTIONS\").allow\n assert meths == {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"POST\"}"} {"repo":"flask","file":"tests/test_views.py","line":63,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":64,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":67,"symbol":"post","kind":"function","lang":"python","code":"def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/test_views.py","line":70,"symbol":"BetterIndex","kind":"class","lang":"python","code":"class BetterIndex(Index):\n def delete(self):\n return \"DELETE\""} {"repo":"flask","file":"tests/test_views.py","line":71,"symbol":"delete","kind":"function","lang":"python","code":"def delete(self):\n return \"DELETE\""} {"repo":"flask","file":"tests/test_views.py","line":80,"symbol":"test_view_decorators","kind":"function","lang":"python","code":"def test_view_decorators(app, client):\n def add_x_parachute(f):\n def new_function(*args, **kwargs):\n resp = flask.make_response(f(*args, **kwargs))\n resp.headers[\"X-Parachute\"] = \"awesome\"\n return resp\n\n return new_function\n\n class Index(flask.views.View):\n decorators = [add_x_parachute]\n\n def dispatch_request(self):\n return \"Awesome\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.headers[\"X-Parachute\"] == \"awesome\"\n assert rv.data == b\"Awesome\""} {"repo":"flask","file":"tests/test_views.py","line":81,"symbol":"add_x_parachute","kind":"function","lang":"python","code":"def add_x_parachute(f):\n def new_function(*args, **kwargs):\n resp = flask.make_response(f(*args, **kwargs))\n resp.headers[\"X-Parachute\"] = \"awesome\"\n return resp\n\n return new_function"} {"repo":"flask","file":"tests/test_views.py","line":82,"symbol":"new_function","kind":"function","lang":"python","code":"def new_function(*args, **kwargs):\n resp = flask.make_response(f(*args, **kwargs))\n resp.headers[\"X-Parachute\"] = \"awesome\"\n return resp"} {"repo":"flask","file":"tests/test_views.py","line":89,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n decorators = [add_x_parachute]\n\n def dispatch_request(self):\n return \"Awesome\""} {"repo":"flask","file":"tests/test_views.py","line":92,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return \"Awesome\""} {"repo":"flask","file":"tests/test_views.py","line":101,"symbol":"test_view_provide_automatic_options_attr_disable","kind":"function","lang":"python","code":"def test_view_provide_automatic_options_attr_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options can be disabled by the view class attribute.\"\"\"\n\n class Index(flask.views.View):\n provide_automatic_options = False\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.options()\n assert rv.status_code == 405"} {"repo":"flask","file":"tests/test_views.py","line":106,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n provide_automatic_options = False\n\n def dispatch_request(self):\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_views.py","line":109,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_views.py","line":117,"symbol":"test_view_provide_automatic_options_attr_enable","kind":"function","lang":"python","code":"def test_view_provide_automatic_options_attr_enable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"When default automatic options is disabled in config, it can still be\n enabled by the view class attribute.\n \"\"\"\n app.config[\"PROVIDE_AUTOMATIC_OPTIONS\"] = False\n\n class Index(flask.views.View):\n provide_automatic_options = True\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.options(\"/\")\n assert rv.allow == {\"GET\", \"HEAD\", \"OPTIONS\"}"} {"repo":"flask","file":"tests/test_views.py","line":125,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n provide_automatic_options = True\n\n def dispatch_request(self):\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_views.py","line":128,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return \"Hello World!\""} {"repo":"flask","file":"tests/test_views.py","line":136,"symbol":"test_provide_automatic_options_method_disable","kind":"function","lang":"python","code":"def test_provide_automatic_options_method_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options is ignored if the route handles options.\"\"\"\n\n class Index(flask.views.View):\n methods = [\"OPTIONS\"]\n\n def dispatch_request(self):\n return \"\", {\"X-Test\": \"test\"}\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.options()\n assert rv.headers[\"X-Test\"] == \"test\""} {"repo":"flask","file":"tests/test_views.py","line":141,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n methods = [\"OPTIONS\"]\n\n def dispatch_request(self):\n return \"\", {\"X-Test\": \"test\"}"} {"repo":"flask","file":"tests/test_views.py","line":144,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return \"\", {\"X-Test\": \"test\"}"} {"repo":"flask","file":"tests/test_views.py","line":152,"symbol":"test_implicit_head","kind":"function","lang":"python","code":"def test_implicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return flask.Response(\"Blub\", headers={\"X-Method\": flask.request.method})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"Blub\"\n assert rv.headers[\"X-Method\"] == \"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\""} {"repo":"flask","file":"tests/test_views.py","line":153,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.MethodView):\n def get(self):\n return flask.Response(\"Blub\", headers={\"X-Method\": flask.request.method})"} {"repo":"flask","file":"tests/test_views.py","line":154,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return flask.Response(\"Blub\", headers={\"X-Method\": flask.request.method})"} {"repo":"flask","file":"tests/test_views.py","line":166,"symbol":"test_explicit_head","kind":"function","lang":"python","code":"def test_explicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def head(self):\n return flask.Response(\"\", headers={\"X-Method\": \"HEAD\"})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\""} {"repo":"flask","file":"tests/test_views.py","line":167,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def head(self):\n return flask.Response(\"\", headers={\"X-Method\": \"HEAD\"})"} {"repo":"flask","file":"tests/test_views.py","line":168,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":171,"symbol":"head","kind":"function","lang":"python","code":"def head(self):\n return flask.Response(\"\", headers={\"X-Method\": \"HEAD\"})"} {"repo":"flask","file":"tests/test_views.py","line":182,"symbol":"test_endpoint_override","kind":"function","lang":"python","code":"def test_endpoint_override(app):\n app.debug = True\n\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n with pytest.raises(AssertionError):\n app.add_url_rule(\"/other\", view_func=Index.as_view(\"index\"))\n\n # But these tests should still pass. We just log a warning.\n common_test(app)"} {"repo":"flask","file":"tests/test_views.py","line":185,"symbol":"Index","kind":"class","lang":"python","code":"class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method"} {"repo":"flask","file":"tests/test_views.py","line":188,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self):\n return flask.request.method"} {"repo":"flask","file":"tests/test_views.py","line":200,"symbol":"test_methods_var_inheritance","kind":"function","lang":"python","code":"def test_methods_var_inheritance(app, client):\n class BaseView(flask.views.MethodView):\n methods = [\"GET\", \"PROPFIND\"]\n\n class ChildView(BaseView):\n def get(self):\n return \"GET\"\n\n def propfind(self):\n return \"PROPFIND\"\n\n app.add_url_rule(\"/\", view_func=ChildView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.open(\"/\", method=\"PROPFIND\").data == b\"PROPFIND\"\n assert ChildView.methods == {\"PROPFIND\", \"GET\"}"} {"repo":"flask","file":"tests/test_views.py","line":201,"symbol":"BaseView","kind":"class","lang":"python","code":"class BaseView(flask.views.MethodView):\n methods = [\"GET\", \"PROPFIND\"]"} {"repo":"flask","file":"tests/test_views.py","line":204,"symbol":"ChildView","kind":"class","lang":"python","code":"class ChildView(BaseView):\n def get(self):\n return \"GET\"\n\n def propfind(self):\n return \"PROPFIND\""} {"repo":"flask","file":"tests/test_views.py","line":205,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":208,"symbol":"propfind","kind":"function","lang":"python","code":"def propfind(self):\n return \"PROPFIND\""} {"repo":"flask","file":"tests/test_views.py","line":218,"symbol":"test_multiple_inheritance","kind":"function","lang":"python","code":"def test_multiple_inheritance(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class DeleteView(flask.views.MethodView):\n def delete(self):\n return \"DELETE\"\n\n class GetDeleteView(GetView, DeleteView):\n pass\n\n app.add_url_rule(\"/\", view_func=GetDeleteView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.delete(\"/\").data == b\"DELETE\"\n assert sorted(GetDeleteView.methods) == [\"DELETE\", \"GET\"]"} {"repo":"flask","file":"tests/test_views.py","line":219,"symbol":"GetView","kind":"class","lang":"python","code":"class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":220,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":223,"symbol":"DeleteView","kind":"class","lang":"python","code":"class DeleteView(flask.views.MethodView):\n def delete(self):\n return \"DELETE\""} {"repo":"flask","file":"tests/test_views.py","line":224,"symbol":"delete","kind":"function","lang":"python","code":"def delete(self):\n return \"DELETE\""} {"repo":"flask","file":"tests/test_views.py","line":227,"symbol":"GetDeleteView","kind":"class","lang":"python","code":"class GetDeleteView(GetView, DeleteView):\n pass"} {"repo":"flask","file":"tests/test_views.py","line":237,"symbol":"test_remove_method_from_parent","kind":"function","lang":"python","code":"def test_remove_method_from_parent(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class OtherView(flask.views.MethodView):\n def post(self):\n return \"POST\"\n\n class View(GetView, OtherView):\n methods = [\"GET\"]\n\n app.add_url_rule(\"/\", view_func=View.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.post(\"/\").status_code == 405\n assert sorted(View.methods) == [\"GET\"]"} {"repo":"flask","file":"tests/test_views.py","line":238,"symbol":"GetView","kind":"class","lang":"python","code":"class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":239,"symbol":"get","kind":"function","lang":"python","code":"def get(self):\n return \"GET\""} {"repo":"flask","file":"tests/test_views.py","line":242,"symbol":"OtherView","kind":"class","lang":"python","code":"class OtherView(flask.views.MethodView):\n def post(self):\n return \"POST\""} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":10,"symbol":"after_sync","kind":"function","lang":"python","code":"def after_sync(response: Response) -> Response:\n return Response()"} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":15,"symbol":"after_async","kind":"function","lang":"python","code":"async def after_async(response: Response) -> Response:\n return Response()"} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":20,"symbol":"before_sync","kind":"function","lang":"python","code":"def before_sync() -> None: ..."} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":24,"symbol":"before_async","kind":"function","lang":"python","code":"async def before_async() -> None: ..."} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":28,"symbol":"teardown_sync","kind":"function","lang":"python","code":"def teardown_sync(exc: BaseException | None) -> None: ..."} {"repo":"flask","file":"tests/type_check/typing_app_decorators.py","line":32,"symbol":"teardown_async","kind":"function","lang":"python","code":"async def teardown_async(exc: BaseException | None) -> None: ..."} {"repo":"flask","file":"tests/type_check/typing_error_handler.py","line":16,"symbol":"handle_400","kind":"function","lang":"python","code":"def handle_400(e: BadRequest) -> str:\n return \"\""} {"repo":"flask","file":"tests/type_check/typing_error_handler.py","line":21,"symbol":"handle_custom","kind":"function","lang":"python","code":"def handle_custom(e: ValueError) -> str:\n return \"\""} {"repo":"flask","file":"tests/type_check/typing_error_handler.py","line":26,"symbol":"handle_accept_base","kind":"function","lang":"python","code":"def handle_accept_base(e: Exception) -> str:\n return \"\""} {"repo":"flask","file":"tests/type_check/typing_error_handler.py","line":32,"symbol":"handle_multiple","kind":"function","lang":"python","code":"def handle_multiple(e: BadRequest | NotFound) -> str:\n return \"\""} {"repo":"flask","file":"tests/type_check/typing_route.py","line":17,"symbol":"hello_str","kind":"function","lang":"python","code":"def hello_str() -> str:\n return \"

Hello, World!

\""} {"repo":"flask","file":"tests/type_check/typing_route.py","line":22,"symbol":"hello_bytes","kind":"function","lang":"python","code":"def hello_bytes() -> bytes:\n return b\"

Hello, World!

\""} {"repo":"flask","file":"tests/type_check/typing_route.py","line":27,"symbol":"hello_json","kind":"function","lang":"python","code":"def hello_json() -> Response:\n return jsonify(\"Hello, World!\")"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":32,"symbol":"hello_json_dict","kind":"function","lang":"python","code":"def hello_json_dict() -> dict[str, t.Any]:\n return {\"response\": \"Hello, World!\"}"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":37,"symbol":"hello_json_list","kind":"function","lang":"python","code":"def hello_json_list() -> list[t.Any]:\n return [{\"message\": \"Hello\"}, {\"message\": \"World\"}]"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":41,"symbol":"StatusJSON","kind":"class","lang":"python","code":"class StatusJSON(t.TypedDict):\n status: str"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":46,"symbol":"typed_dict","kind":"function","lang":"python","code":"def typed_dict() -> StatusJSON:\n return {\"status\": \"ok\"}"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":51,"symbol":"hello_generator","kind":"function","lang":"python","code":"def hello_generator() -> t.Generator[str, None, None]:\n def show() -> t.Generator[str, None, None]:\n for x in range(100):\n yield f\"data:{x}\\n\\n\"\n\n return show()"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":52,"symbol":"show","kind":"function","lang":"python","code":"def show() -> t.Generator[str, None, None]:\n for x in range(100):\n yield f\"data:{x}\\n\\n\""} {"repo":"flask","file":"tests/type_check/typing_route.py","line":60,"symbol":"hello_generator_expression","kind":"function","lang":"python","code":"def hello_generator_expression() -> t.Iterator[bytes]:\n return (f\"data:{x}\\n\\n\".encode() for x in range(100))"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":65,"symbol":"hello_iterator","kind":"function","lang":"python","code":"def hello_iterator() -> t.Iterator[str]:\n return iter([f\"data:{x}\\n\\n\" for x in range(100)])"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":71,"symbol":"tuple_status","kind":"function","lang":"python","code":"def tuple_status(code: int = 200) -> tuple[str, int]:\n return \"hello\", code"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":76,"symbol":"tuple_status_enum","kind":"function","lang":"python","code":"def tuple_status_enum() -> tuple[str, int]:\n return \"hello\", HTTPStatus.OK"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":81,"symbol":"tuple_headers","kind":"function","lang":"python","code":"def tuple_headers() -> tuple[str, dict[str, str]]:\n return \"Hello, World!\", {\"Content-Type\": \"text/plain\"}"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":87,"symbol":"return_template","kind":"function","lang":"python","code":"def return_template(name: str | None = None) -> str:\n return render_template(\"index.html\", name=name)"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":92,"symbol":"return_template_stream","kind":"function","lang":"python","code":"def return_template_stream() -> t.Iterator[str]:\n return stream_template(\"index.html\", name=\"Hello\")"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":97,"symbol":"async_route","kind":"function","lang":"python","code":"async def async_route() -> str:\n return \"Hello\""} {"repo":"flask","file":"tests/type_check/typing_route.py","line":101,"symbol":"RenderTemplateView","kind":"class","lang":"python","code":"class RenderTemplateView(View):\n def __init__(self: RenderTemplateView, template_name: str) -> None:\n self.template_name = template_name\n\n def dispatch_request(self: RenderTemplateView) -> str:\n return render_template(self.template_name)"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":102,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self: RenderTemplateView, template_name: str) -> None:\n self.template_name = template_name"} {"repo":"flask","file":"tests/type_check/typing_route.py","line":105,"symbol":"dispatch_request","kind":"function","lang":"python","code":"def dispatch_request(self: RenderTemplateView) -> str:\n return render_template(self.template_name)"}