text stringlengths 44 42.4k |
|---|
#!/bin/bash
set -e
python3 -m venv --upgrade-deps .venv
. .venv/bin/activate
pip install -r requirements/dev.txt
pip install -e .
pre-commit install --install-hooks |
import packaging.version
from pallets_sphinx_themes import get_version
from pallets_sphinx_themes import ProjectLink
# Project --------------------------------------------------------------
project = "Flask"
copyright = "2010 Pallets"
author = "Pallets"
release, version = get_version("Flask")
# General -------------... |
from celery import Celery
from celery import Task
from flask import Flask
from flask import render_template
def create_app() -> Flask:
app = Flask(__name__)
app.config.from_mapping(
CELERY={
"broker_url": "redis://localhost",
"result_backend": "redis://localhost",
"t... |
import time
from celery import shared_task
from celery import Task
@shared_task(ignore_result=False)
def add(a: int, b: int) -> int:
return a + b
@shared_task()
def block() -> None:
time.sleep(5)
@shared_task(bind=True, ignore_result=False)
def process(self: Task, total: int) -> object:
for i in range(t... |
<!doctype html>
<html>
<head>
<meta charset=UTF-8>
<title>Celery Example</title>
</head>
<body>
<h2>Celery Example</h2>
Execute background tasks with Celery. Submits tasks and shows results using JavaScript.
<hr>
<h4>Add</h4>
<p>Start a task to add two numbers, then poll for the result.
<form id=add method=post ac... |
from celery.result import AsyncResult
from flask import Blueprint
from flask import request
from . import tasks
bp = Blueprint("tasks", __name__, url_prefix="/tasks")
@bp.get("/result/<id>")
def result(id: str) -> dict[str, object]:
result = AsyncResult(id)
ready = result.ready()
return {
"ready"... |
<!doctype html>
<title>JavaScript Example</title>
<link rel="stylesheet" href="https://unpkg.com/normalize.css@8.0.1/normalize.css">
<link rel="stylesheet" href="https://unpkg.com/sakura.css@1.3.1/css/sakura.css">
<style>
ul { margin: 0; padding: 0; display: flex; list-style-type: none; }
li > * { padding: 1em; }
... |
{% extends 'base.html' %}
{% block intro %}
<a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch"><code>fetch</code></a>
is the <em>modern</em> plain JavaScript way to make requests. It's
supported in all modern browsers.
{% endblock %}
{% block script %}
<script>
func... |
{% extends 'base.html' %}
{% block intro %}
<a href="https://jquery.com/">jQuery</a> is a popular library that
adds cross browser APIs for common tasks. However, it requires loading
an extra library.
{% endblock %}
{% block script %}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<scrip... |
{% extends 'base.html' %}
{% block intro %}
<a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a>
is the original JavaScript way to make requests. It's natively supported
by all browsers, but has been superseded by
<a href="{{ url_for("index", js="fetch") }}"... |
from flask import jsonify
from flask import render_template
from flask import request
from . import app
@app.route("/", defaults={"js": "fetch"})
@app.route("/<any(xhr, jquery, fetch):js>")
def index(js):
return render_template(f"{js}.html", js=js)
@app.route("/add", methods=["POST"])
def add():
a = request.... |
import pytest
from js_example import app
@pytest.fixture(name="app")
def fixture_app():
app.testing = True
yield app
app.testing = False
@pytest.fixture
def client(app):
return app.test_client() |
import pytest
from flask import template_rendered
@pytest.mark.parametrize(
("path", "template_name"),
(
("/", "fetch.html"),
("/plain", "xhr.html"),
("/fetch", "fetch.html"),
("/jquery", "jquery.html"),
),
)
def test_index(app, client, path, template_name):
def check(se... |
import os
from flask import Flask
def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
# a default secret that should be overridden by instance config
SECRET_KEY="dev... |
import functools
from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from werkzeug.security import check_password_hash
from werkzeug.security import generate_pa... |
from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from werkzeug.exceptions import abort
from .auth import login_required
from .db import get_db
bp = Blueprint("blog", __name__)
@bp.r... |
import sqlite3
from datetime import datetime
import click
from flask import current_app
from flask import g
def get_db():
"""Connect to the application's configured database. The connection
is unique for each request and will be reused if this is called
again.
"""
if "db" not in g:
g.db = ... |
-- Initialize the database.
-- Drop any existing data and create empty tables.
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE post (
id INTEGER PRIMARY KEY AUTOINCREMENT,
a... |
html {
font-family: sans-serif;
background: #eee;
padding: 1rem;
}
body {
max-width: 960px;
margin: 0 auto;
background: white;
}
h1, h2, h3, h4, h5, h6 {
font-family: serif;
color: #377ba8;
margin: 1rem 0;
}
a {
color: #377ba8;
}
hr {
border: none;
border-top: 1px solid lightgray;
}
nav {
... |
<!doctype html>
<title>{% block title %}{% endblock %} - Flaskr</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<nav>
<h1><a href="{{ url_for('index') }}">Flaskr</a></h1>
<ul>
{% if g.user %}
<li><span>{{ g.user['username'] }}</span>
<li><a href="{{ url_for('auth... |
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}New Post{% endblock %}</h1>
{% endblock %}
{% block content %}
<form method="post">
<label for="title">Title</label>
<input name="title" id="title" value="{{ request.form['title'] }}" required>
<label for="body">Body</label>
<textar... |
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Posts{% endblock %}</h1>
{% if g.user %}
<a class="action" href="{{ url_for('blog.create') }}">New</a>
{% endif %}
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<div>
... |
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>
{% endblock %}
{% block content %}
<form method="post">
<label for="title">Title</label>
<input name="title" id="title" value="{{ request.form['title'] or post['title'] }}" required>
<label ... |
import os
import tempfile
import pytest
from flaskr import create_app
from flaskr.db import get_db
from flaskr.db import init_db
# read in SQL for populating test data
with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:
_data_sql = f.read().decode("utf8")
@pytest.fixture
def app():
""... |
INSERT INTO user (username, password)
VALUES
('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),
('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');
INSERT INTO post (title, body, author_id, created)
VALU... |
import pytest
from flask import g
from flask import session
from flaskr.db import get_db
def test_register(client, app):
# test that viewing the page renders without template errors
assert client.get("/auth/register").status_code == 200
# test that successful registration redirects to the login page
... |
import pytest
from flaskr.db import get_db
def test_index(client, auth):
response = client.get("/")
assert b"Log In" in response.data
assert b"Register" in response.data
auth.login()
response = client.get("/")
assert b"test title" in response.data
assert b"by test on 2018-01-01" in respon... |
import sqlite3
import pytest
from flaskr.db import get_db
def test_get_close_db(app):
with app.app_context():
db = get_db()
assert db is get_db()
with pytest.raises(sqlite3.ProgrammingError) as e:
db.execute("SELECT 1")
assert "closed" in str(e.value)
def test_init_db_command(r... |
from flaskr import create_app
def test_config():
"""Test create_app without passing test config."""
assert not create_app().testing
assert create_app({"TESTING": True}).testing
def test_hello(client):
response = client.get("/hello")
assert response.data == b"Hello, World!" |
from . import json as json
from .app import Flask as Flask
from .blueprints import Blueprint as Blueprint
from .config import Config as Config
from .ctx import after_this_request as after_this_request
from .ctx import copy_current_request_context as copy_current_request_context
from .ctx import has_app_context as has_a... |
from __future__ import annotations
import collections.abc as cabc
import inspect
import os
import sys
import typing as t
import weakref
from datetime import timedelta
from functools import update_wrapper
from inspect import iscoroutinefunction
from itertools import chain
from types import TracebackType
from urllib.par... |
ja-related methods of the app. Changing
:attr:`jinja_options` after this will have no effect. Also adds
Flask-related globals and filters to the environment.
.. versionchanged:: 0.11
``Environment.auto_reload`` set in accordance with
``TEMPLATES_AUTO_RELOAD`` configuration... |
:
"""Logs an exception. This is called by :meth:`handle_exception`
if debugging is disabled and right before the handler is called.
The default implementation logs the exception as error on the
:attr:`logger`.
.. versionadded:: 0.8
"""
self.logger.error(
... |
name in self.teardown_request_funcs:
for func in reversed(self.teardown_request_funcs[name]):
with collect_errors:
self.ensure_sync(func)(exc)
with collect_errors:
request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
... |
from __future__ import annotations
import os
import typing as t
from datetime import timedelta
from .cli import AppGroup
from .globals import current_app
from .helpers import send_from_directory
from .sansio.blueprints import Blueprint as SansioBlueprint
from .sansio.blueprints import BlueprintSetupState as Blueprint... |
from __future__ import annotations
import ast
import collections.abc as cabc
import importlib.metadata
import inspect
import os
import platform
import re
import sys
import traceback
import typing as t
from functools import update_wrapper
from operator import itemgetter
from types import ModuleType
import click
from c... |
flaskenv`
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
:param set_debug_flag: Set the app's debug flag.
.. versionchanged:: 3.1
``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.
... |
.append((rule.host if host_matching else rule.subdomain) or "")
row.append(rule.rule)
rows.append(row)
headers = ["Endpoint", "Methods"]
sorts = ["endpoint", "methods"]
if has_domain:
headers.append("Host" if host_matching else "Subdomain")
sorts.append("domain")
head... |
from __future__ import annotations
import errno
import json
import os
import types
import typing as t
from werkzeug.utils import import_string
if t.TYPE_CHECKING:
import typing_extensions as te
from .sansio.app import App
T = t.TypeVar("T")
class ConfigAttribute(t.Generic[T]):
"""Makes an attribute fo... |
from __future__ import annotations
import contextvars
import typing as t
from functools import update_wrapper
from types import TracebackType
from werkzeug.exceptions import HTTPException
from werkzeug.routing import MapAdapter
from . import typing as ft
from .globals import _cv_app
from .helpers import _CollectErro... |
from __future__ import annotations
import typing as t
from jinja2.loaders import BaseLoader
from werkzeug.routing import RequestRedirect
from .blueprints import Blueprint
from .globals import _cv_app
from .sansio.app import App
if t.TYPE_CHECKING:
from .sansio.scaffold import Scaffold
from .wrappers import ... |
from __future__ import annotations
import typing as t
from contextvars import ContextVar
from werkzeug.local import LocalProxy
if t.TYPE_CHECKING: # pragma: no cover
from .app import Flask
from .ctx import _AppCtxGlobals
from .ctx import AppContext
from .sessions import SessionMixin
from .wrappe... |
from __future__ import annotations
import importlib.util
import os
import sys
import typing as t
from datetime import datetime
from functools import cache
from functools import update_wrapper
from types import TracebackType
import werkzeug.utils
from werkzeug.exceptions import abort as _wz_abort
from werkzeug.utils i... |
_age`` is not set by
default.
.. versionchanged:: 2.0
``etag`` replaces the ``add_etags`` parameter. It can be a
string to use instead of generating one.
.. versionchanged:: 2.0
Passing a file-like object that inherits from
:class:`~io.TextIOBase` will raise a :exc:`Val... |
from __future__ import annotations
import json as _json
import typing as t
from ..globals import current_app
from .provider import _default
if t.TYPE_CHECKING: # pragma: no cover
from ..wrappers import Response
def dumps(obj: t.Any, **kwargs: t.Any) -> str:
"""Serialize data as JSON.
If :data:`~flask.... |
from __future__ import annotations
import dataclasses
import decimal
import json
import typing as t
import uuid
import weakref
from datetime import date
from werkzeug.http import http_date
if t.TYPE_CHECKING: # pragma: no cover
from werkzeug.sansio.response import Response
from ..sansio.app import App
cla... |
"""
Tagged JSON
~~~~~~~~~~~
A compact representation for lossless serialization of non-standard JSON
types. :class:`~flask.sessions.SecureCookieSessionInterface` uses this
to serialize the session data, but it may be useful in other places. It
can be extended to support other types.
.. autoclass:: TaggedJSONSerialize... |
from __future__ import annotations
import logging
import sys
import typing as t
from werkzeug.local import LocalProxy
from .globals import request
if t.TYPE_CHECKING: # pragma: no cover
from .sansio.app import App
@LocalProxy
def wsgi_errors_stream() -> t.TextIO:
"""Find the most appropriate error stream ... |
from __future__ import annotations
import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildE... |
os.path.splitext(os.path.basename(fn))[0]
return self.import_name
@cached_property
def logger(self) -> logging.Logger:
"""A standard Python :class:`~logging.Logger` for the app, with
the same name as :attr:`name`.
In debug mode, the logger's :attr:`~logging.Logger.level` will
... |
``code`` defaults to ``303`` instead of ``302``.
.. versionadded:: 2.2
Moved from ``flask.redirect``, which calls this method.
"""
return _wz_redirect(
location,
code=code,
Response=self.response_class, # type: ignore[arg-type]
... |
from __future__ import annotations
import os
import typing as t
from collections import defaultdict
from functools import update_wrapper
from .. import typing as ft
from .scaffold import _endpoint_from_view_func
from .scaffold import _sentinel
from .scaffold import Scaffold
from .scaffold import setupmethod
if t.TYP... |
Flask.add_template_filter`.
:param f: The function to register.
:param name: The name to register the filter as. If not given, uses the
function's name.
"""
def register_template_filter(state: BlueprintSetupState) -> None:
state.app.add_template_filter(f, name=n... |
from __future__ import annotations
import importlib.util
import os
import pathlib
import sys
import typing as t
from collections import defaultdict
from functools import update_wrapper
from jinja2 import BaseLoader
from jinja2 import FileSystemLoader
from werkzeug.exceptions import default_exceptions
from werkzeug.ex... |
[]).append(f)
return f
@setupmethod
def after_request(self, f: T_after_request) -> T_after_request:
"""Register a function to run after each request to this object.
The function is called with the response object, and must return
a response object. This allows the functions to... |
from __future__ import annotations
import collections.abc as c
import hashlib
import typing as t
from collections.abc import MutableMapping
from datetime import datetime
from datetime import timezone
from itsdangerous import BadSignature
from itsdangerous import URLSafeTimedSerializer
from werkzeug.datastructures imp... |
from __future__ import annotations
from blinker import Namespace
# This namespace is only for signals provided by Flask itself.
_signals = Namespace()
template_rendered = _signals.signal("template-rendered")
before_render_template = _signals.signal("before-render-template")
request_started = _signals.signal("request... |
from __future__ import annotations
import typing as t
from jinja2 import BaseLoader
from jinja2 import Environment as BaseEnvironment
from jinja2 import Template
from jinja2 import TemplateNotFound
from .ctx import AppContext
from .globals import app_ctx
from .helpers import stream_with_context
from .signals import ... |
from __future__ import annotations
import importlib.metadata
import typing as t
from contextlib import contextmanager
from contextlib import ExitStack
from copy import copy
from types import TracebackType
from urllib.parse import urlsplit
import werkzeug.test
from click.testing import CliRunner
from click.testing imp... |
from __future__ import annotations
import collections.abc as cabc
import typing as t
if t.TYPE_CHECKING: # pragma: no cover
from _typeshed.wsgi import WSGIApplication # noqa: F401
from werkzeug.datastructures import Headers # noqa: F401
from werkzeug.sansio.response import Response # noqa: F401
# The... |
from __future__ import annotations
import typing as t
from . import typing as ft
from .globals import current_app
from .globals import request
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
http_method_funcs = frozenset(
["get", "query", "post", "head", "options", "delete", "put", "trace", "patch"]
)
class V... |
from __future__ import annotations
import typing as t
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import HTTPException
from werkzeug.wrappers import Request as RequestBase
from werkzeug.wrappers import Response as ResponseBase
from . import json
from .globals import current_app
from .helpers ... |
import os
import sys
import pytest
from flask import Flask
from flask.globals import app_ctx as _app_ctx
@pytest.fixture(autouse=True)
def _standard_os_environ(monkeypatch):
"""Set up ``os.environ`` at the start of every test to have
standard values.
"""
for key in (
"FLASK_ENV_FILE",
... |
{{ text }}
{{ html }}
{% autoescape false %}{{ text }}
{{ html }}{% endautoescape %}
{% autoescape true %}{{ text }}
{{ html }}{% endautoescape %} |
import sys
import pytest
import flask
from flask.globals import app_ctx
from flask.testing import FlaskClient
def test_basic_url_generation(app):
app.config["SERVER_NAME"] = "localhost"
app.config["PREFERRED_URL_SCHEME"] = "https"
@app.route("/")
def index():
pass
with app.app_context()... |
from flask import Flask
app = Flask(__name__)
app.config["DEBUG"] = True
from blueprintapp.apps.admin import admin # noqa: E402
from blueprintapp.apps.frontend import frontend # noqa: E402
app.register_blueprint(admin)
app.register_blueprint(frontend) |
from flask import Blueprint
from flask import render_template
admin = Blueprint(
"admin",
__name__,
url_prefix="/admin",
template_folder="templates",
static_folder="static",
)
@admin.route("/")
def index():
return render_template("admin/index.html")
@admin.route("/index2")
def index2():
r... |
from flask import Blueprint
from flask import render_template
frontend = Blueprint("frontend", __name__, template_folder="templates")
@frontend.route("/")
def index():
return render_template("frontend/index.html")
@frontend.route("/missing")
def missing_template():
return render_template("missing_template.ht... |
from flask import Flask
def create_app():
return Flask("app")
def create_app2(foo, bar):
return Flask("_".join(["app2", foo, bar]))
def no_app():
pass |
import asyncio
import pytest
from flask import Blueprint
from flask import Flask
from flask import request
from flask.views import MethodView
from flask.views import View
pytest.importorskip("asgiref")
class AppError(Exception):
pass
class BlueprintError(Exception):
pass
class AsyncView(View):
methods... |
import gc
import importlib.metadata
import re
import typing as t
import uuid
import weakref
from contextlib import nullcontext
from datetime import datetime
from datetime import timezone
from functools import partial
from platform import python_implementation
import pytest
import werkzeug.serving
from markupsafe impor... |
def no_vary_header():
return ""
def expect(path, header_value="Cookie"):
rv = client.get(path)
if header_value:
# The 'Vary' key should exist in the headers only once.
assert len(rv.headers.get_all("Vary")) == 1
assert rv.headers["Vary"] == header_value... |
_wsgi():
return lambda: None
c = app.test_client()
with pytest.raises(TypeError) as e:
c.get("/none")
assert "returned None" in str(e.value)
assert "from_none" in str(e.value)
with pytest.raises(TypeError) as e:
c.get("/small_tuple")
assert "tuple must have the form"... |
= client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")
assert rv.data == b"index for mitsuhiko"
@pytest.mark.parametrize("matching", (False, True))
def test_subdomain_matching_other_name(matching):
app = flask.Flask(__name__, subdomain_matching=matching)
app.config["SERVER_NAME"] = "localhost.l... |
import pytest
from jinja2 import TemplateNotFound
import flask
def test_blueprint_specific_error_handling(app, client):
frontend = flask.Blueprint("frontend", __name__)
backend = flask.Blueprint("backend", __name__)
sideend = flask.Blueprint("sideend", __name__)
@frontend.errorhandler(403)
def fr... |
url_prefix="/py")
@app.route("/")
def index():
return flask.render_template("template_test.html", value=False)
rv = client.get("/")
assert b"Success!" in rv.data
def test_template_test_after_route_with_template(app, client):
@app.route("/")
def index():
return flask.render_te... |
# This file was part of Flask-CLI and was modified under the terms of
# its Revised BSD License. Copyright © 2015 CERN.
import importlib.metadata
import os
import platform
import ssl
import sys
import types
from functools import partial
from pathlib import Path
import click
import pytest
from click.testing import CliR... |
first
ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])
assert ctx.params["cert"] == (__file__, __file__)
def test_run_cert_adhoc(monkeypatch):
monkeypatch.setitem(sys.modules, "cryptography", None)
# cryptography not installed
with pytest.raises(click.BadParameter):
... |
import json
import os
import pytest
import flask
# config keys used for the TestConfig
TEST_KEY = "foo"
SECRET_KEY = "[REDACTED]"
def common_object_test(app):
assert app.secret_key == "config"
assert app.config["TEST_KEY"] == "foo"
assert "TestConfig" not in app.config
def test_config_from_pyfile():
... |
from werkzeug.routing import BaseConverter
from flask import request
from flask import session
from flask import url_for
def test_custom_converters(app, client):
class ListConverter(BaseConverter):
def to_python(self, value):
return value.split(",")
def to_url(self, value):
... |
import io
import os
import pytest
import werkzeug.exceptions
import flask
from flask.helpers import get_debug_flag
class FakePath:
"""Fake object to represent a ``PathLike object``.
This represents a ``pathlib.Path`` object in python 3.
See: https://www.python.org/dev/peps/pep-0519/
"""
def __i... |
import os
import pytest
import flask
def test_explicit_instance_paths(modules_tmp_path):
with pytest.raises(ValueError, match=".*must be absolute"):
flask.Flask(__name__, instance_path="instance")
app = flask.Flask(__name__, instance_path=os.fspath(modules_tmp_path))
assert app.instance_path == ... |
import datetime
import decimal
import io
import uuid
import pytest
from werkzeug.http import http_date
import flask
from flask import json
from flask.json.provider import DefaultJSONProvider
@pytest.mark.parametrize("debug", (True, False))
def test_bad_request_debug_message(app, client, debug):
app.config["DEBUG... |
from datetime import datetime
from datetime import timezone
from uuid import uuid4
import pytest
from markupsafe import Markup
from flask.json.tag import JSONTag
from flask.json.tag import TaggedJSONSerializer
@pytest.mark.parametrize(
"data",
(
{" t": (1, 2, 3)},
{" t__": b"a"},
{" d... |
import logging
import sys
from io import StringIO
import pytest
from flask.logging import default_handler
from flask.logging import has_level_handler
from flask.logging import wsgi_errors_stream
@pytest.fixture(autouse=True)
def reset_logging(pytestconfig):
root_handlers = logging.root.handlers[:]
logging.ro... |
import flask
def test_aborting(app):
class Foo(Exception):
whatever = 42
@app.errorhandler(Foo)
def handle_foo(e):
return str(e.whatever)
@app.route("/")
def index():
raise flask.abort(flask.redirect(flask.url_for("test")))
@app.route("/test")
def test():
... |
from __future__ import annotations
import collections.abc as cabc
import warnings
from concurrent import futures
import pytest
import flask
from flask.sessions import SecureCookieSessionInterface
from flask.sessions import SessionInterface
from flask.testing import FlaskClient
def test_teardown_on_pop(app):
buf... |
from __future__ import annotations
from flask import Flask
from flask import Request
from flask import request
from flask.testing import FlaskClient
def test_max_content_length(app: Flask, client: FlaskClient) -> None:
app.config["MAX_CONTENT_LENGTH"] = 50
@app.post("/")
def index():
request.form... |
import flask
from flask.globals import app_ctx
from flask.sessions import SessionInterface
def test_open_session_with_endpoint():
"""If request.endpoint (or other URL matching behavior) is needed
while loading the session, RequestContext.match_request() can be
called manually.
"""
class MySessionI... |
import flask
def test_template_rendered(app, client):
@app.route("/")
def index():
return flask.render_template("simple_template.html", whiskey=42)
recorded = []
def record(sender, template, context):
recorded.append((template, context))
flask.template_rendered.connect(record, ap... |
from io import StringIO
import flask
def test_suppressed_exception_logging():
class SuppressedFlask(flask.Flask):
def log_exception(self, ctx, exc_info):
pass
out = StringIO()
app = SuppressedFlask(__name__)
@app.route("/")
def index():
raise Exception("test")
rv... |
import logging
import pytest
import werkzeug.serving
from jinja2 import TemplateNotFound
from markupsafe import Markup
import flask
def test_context_processing(app, client):
@app.context_processor
def context_processor():
return {"injected_value": 42}
@app.route("/")
def index():
ret... |
import importlib.metadata
import click
import pytest
import flask
from flask import appcontext_popped
from flask.cli import ScriptInfo
from flask.globals import _cv_app
from flask.json import jsonify
from flask.testing import EnvironBuilder
from flask.testing import FlaskCliRunner
def test_environ_defaults_from_conf... |
import pytest
from werkzeug.exceptions import Forbidden
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import InternalServerError
from werkzeug.exceptions import NotFound
import flask
def test_error_handler_no_match(app, client):
class CustomException(Exception):
pass
@app.err... |
import pytest
import flask.views
from flask.testing import FlaskClient
def common_test(app):
c = app.test_client()
assert c.get("/").data == b"GET"
assert c.post("/").data == b"POST"
assert c.put("/").status_code == 405
meths = c.open("/", method="OPTIONS").allow
assert meths == {"GET", "HEAD... |
from __future__ import annotations
from flask import Flask
from flask import Response
app = Flask(__name__)
@app.after_request
def after_sync(response: Response) -> Response:
return Response()
@app.after_request
async def after_async(response: Response) -> Response:
return Response()
@app.before_request
de... |
from __future__ import annotations
from http import HTTPStatus
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import NotFound
from flask import Flask
app = Flask(__name__)
@app.errorhandler(400)
@app.errorhandler(HTTPStatus.BAD_REQUEST)
@app.errorhandler(BadRequest)
def handle_400(e: BadReques... |
from __future__ import annotations
import typing as t
from http import HTTPStatus
from flask import Flask
from flask import jsonify
from flask import stream_template
from flask.templating import render_template
from flask.views import View
from flask.wrappers import Response
app = Flask(__name__)
@app.route("/str")... |
from pallets_sphinx_themes import get_version
from pallets_sphinx_themes import ProjectLink
# Project --------------------------------------------------------------
project = "Werkzeug"
copyright = "2007 Pallets"
author = "Pallets"
release, version = get_version("Werkzeug")
# General --------------------------------... |
from .utils import ThreadedRequest
#: a thread local proxy request object
request = ThreadedRequest()
del ThreadedRequest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.