repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
sanic | tests/test_payload_too_large.py | .py | from sanic.exceptions import PayloadTooLarge
from sanic.response import text
def test_payload_too_large_from_error_handler(app):
app.config.REQUEST_MAX_SIZE = 1
@app.route("/1")
async def handler1(request):
return text("OK")
@app.exception(PayloadTooLarge)
def handler_exception(request, ... | 44 | 1,242 |
sanic | tests/test_utf8.py | .py | from json import dumps as json_dumps
from sanic.response import text
# ------------------------------------------------------------ #
# UTF-8
# ------------------------------------------------------------ #
def test_utf8_query_string(app):
@app.route("/")
async def handler(request):
return text("O... | 53 | 1,250 |
sanic | tests/test_unix_socket.py | .py | # import asyncio
import logging
import os
import sys
from asyncio import AbstractEventLoop, sleep
from pathlib import Path
from string import ascii_lowercase
import httpcore
import httpx
import pytest
from pytest import LogCaptureFixture
from sanic import Sanic
from sanic.compat import use_context
from sanic.reques... | 282 | 7,961 |
sanic | tests/test_exceptions_handler.py | .py | import asyncio
import logging
from typing import Callable
from unittest.mock import Mock
import pytest
from bs4 import BeautifulSoup
from pytest import LogCaptureFixture, MonkeyPatch
from sanic import Sanic, handlers
from sanic.exceptions import BadRequest, Forbidden, NotFound, ServerError
from sanic.handlers impor... | 285 | 8,912 |
sanic | tests/test_middleware_priority.py | .py | from functools import partial
import pytest
from sanic import Sanic
from sanic.middleware import Middleware, MiddlewareLocation
from sanic.response import json
PRIORITY_TEST_CASES = (
([0, 1, 2], [1, 1, 1]),
([0, 1, 2], [1, 1, None]),
([0, 1, 2], [1, None, None]),
([0, 1, 2], [2, 1, None]),
([0,... | 165 | 4,931 |
sanic | tests/test_logo.py | .py | import os
import sys
from unittest.mock import patch
import pytest
from sanic.application.logo import (
BASE_LOGO,
COLOR_LOGO,
FULL_COLOR_LOGO,
get_logo,
)
@pytest.mark.parametrize(
"tty,full,expected",
(
(True, False, COLOR_LOGO),
(True, True, FULL_COLOR_LOGO),
(Fal... | 42 | 959 |
sanic | tests/test_response_file.py | .py | from datetime import datetime, timezone
from logging import INFO
import pytest
from sanic.compat import Header
from sanic.response.convenience import guess_content_type, validate_file
@pytest.mark.parametrize(
"ifmod,lastmod,expected",
(
("Sat, 01 Apr 2023 00:00:00 GMT", 1672524000, None),
(... | 89 | 2,666 |
sanic | tests/test_helpers.py | .py | import inspect
import pytest
from sanic import helpers
from sanic.config import Config
def test_has_message_body():
tests = (
(100, False),
(102, False),
(204, False),
(200, True),
(304, False),
(400, True),
)
for status_code, expected in tests:
as... | 57 | 1,254 |
sanic | tests/test_static.py | .py | import logging
import os
import sys
from collections import Counter
from pathlib import Path
from time import gmtime, strftime
from urllib.parse import unquote
import pytest
from sanic import Sanic, text
from sanic.exceptions import FileNotFound, ServerError
from sanic.response import file
pytestmark = pytest.mark.xd... | 707 | 23,003 |
sanic | tests/test_utils.py | .py | from os import environ
from pathlib import Path
from types import ModuleType
import pytest
from sanic.exceptions import LoadFileException
from sanic.utils import load_module_from_file_location
@pytest.mark.parametrize(
"location",
(
Path(__file__).parent / "static" / "app_test_config.py",
st... | 50 | 1,451 |
sanic | tests/test_init.py | .py | from importlib import import_module
import pytest
@pytest.mark.parametrize(
"item",
(
"__version__",
"Sanic",
"Blueprint",
"HTTPMethod",
"HTTPResponse",
"Request",
"Websocket",
"empty",
"file",
"html",
"json",
"re... | 26 | 411 |
sanic | tests/test_response_timeout.py | .py | import asyncio
import logging
from time import sleep
import pytest
from sanic import Sanic
from sanic.exceptions import ServiceUnavailable
from sanic.log import LOGGING_CONFIG_DEFAULTS
from sanic.response import text
@pytest.fixture
def response_timeout_app():
app = Sanic("test_response_timeout")
app.confi... | 108 | 3,127 |
sanic | tests/test_requests.py | .py | import base64
import logging
from json import dumps as json_dumps
from json import loads as json_loads
from urllib.parse import urlparse
import pytest
from sanic_testing.testing import (
ASGI_BASE_URL,
ASGI_PORT,
HOST,
PORT,
SanicTestClient,
)
from sanic import Blueprint, Sanic
from sanic.compat... | 2,359 | 68,435 |
sanic | tests/test_ext_integration.py | .py | import sys
import pytest
from sanic import Sanic
try:
import sanic_ext # noqa: F401
SANIC_EXT_IN_ENV = True
except ImportError:
SANIC_EXT_IN_ENV = False
@pytest.fixture
def stoppable_app(app):
@app.before_server_start
async def stop(*_):
app.stop()
return app
def test_ext_is_l... | 85 | 2,223 |
sanic | tests/conftest.py | .py | import asyncio
import inspect
import logging
import os
import random
import re
import socket
import string
import sys
import uuid
from contextlib import suppress
from logging import LogRecord
from typing import Any
from unittest.mock import MagicMock, Mock, patch
import pytest
from sanic_routing.exceptions import Ro... | 264 | 7,393 |
sanic | tests/performance/sanic/http_response.py | .py | import inspect
import os
import sys
import timeit
from sanic.response import json
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
sys.path.insert(0, currentdir + "/../../../")
print(json({"test": True}).output())
print("Running New 100,000 times")
times = 0
total_time ... | 44 | 943 |
sanic | tests/performance/sanic/simple_server.py | .py | import inspect
import os
import sys
from sanic import Sanic
from sanic.response import json
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
sys.path.insert(0, currentdir + "/../../../")
app = Sanic("test")
@app.route("/")
async def test(request):
return json({"tes... | 25 | 406 |
sanic | tests/performance/sanic/varied_server.py | .py | import inspect
import os
import sys
from sanic import Sanic
from sanic.exceptions import ServerError
from sanic.response import json, text
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
sys.path.insert(0, currentdir + "/../../../")
app = Sanic("test")
@app.route("/")... | 109 | 2,366 |
sanic | tests/certs/createcerts.py | .py | from datetime import datetime, timedelta
from ipaddress import ip_address
from os import path
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.x509 import (
BasicConstraints,
CertificateBuilder,
DNSName,
Ext... | 114 | 3,049 |
sanic | tests/benchmark/test_route_resolution_benchmark.py | .py | from random import choice, seed
from pytest import mark
import sanic.router
from sanic.request import Request
seed("Pack my box with five dozen liquor jugs.")
# Disable Caching for testing purpose
sanic.router.ROUTER_CACHE_SIZE = 0
class TestSanicRouteResolution:
@mark.asyncio
async def test_resolve_rou... | 82 | 2,214 |
sanic | tests/fake/server.py | .py | import json
from sanic import Sanic, text
from sanic.application.constants import Mode
from sanic.config import Config
from sanic.log import LOGGING_CONFIG_DEFAULTS, logger
LOGGING_CONFIG = {**LOGGING_CONFIG_DEFAULTS}
LOGGING_CONFIG["formatters"]["generic"]["format"] = "%(message)s"
LOGGING_CONFIG["loggers"]["sanic.... | 70 | 1,438 |
sanic | tests/http3/test_server.py | .py | import logging
from asyncio import Event
from pathlib import Path
import pytest
from sanic import Sanic
from sanic.http.constants import HTTP
parent_dir = Path(__file__).parent.parent
localhost_dir = parent_dir / "certs/localhost"
@pytest.mark.parametrize("version", (3, HTTP.VERSION_3))
def test_server_starts_ht... | 102 | 2,427 |
sanic | tests/http3/test_session_ticket_store.py | .py | from datetime import datetime
from aioquic.tls import CipherSuite, SessionTicket
from sanic.http.http3 import SessionTicketStore
def _generate_ticket(label):
return SessionTicket(
1,
CipherSuite.AES_128_GCM_SHA256,
datetime.now(),
datetime.now(),
label,
label.deco... | 47 | 924 |
sanic | tests/http3/test_http_receiver.py | .py | from unittest.mock import Mock
import pytest
from aioquic.h3.connection import H3Connection
from aioquic.h3.events import DataReceived, HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import ProtocolNegotiated
from s... | 340 | 10,080 |
sanic | tests/worker/test_loader.py | .py | import sys
from os import getcwd
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch
import pytest
from sanic.app import Sanic
from sanic.worker.loader import AppLoader, CertLoader
STATIC = Path.cwd() / "tests" / "static"
@pytest.mark.parametrize(
"module_input", ... | 96 | 2,646 |
sanic | tests/worker/test_startup.py | .py | import sys
from multiprocessing import set_start_method
from unittest.mock import patch
import pytest
from sanic import Sanic
@pytest.mark.parametrize(
"start_method,platform,expected",
(
(None, "linux", "spawn"),
(None, "other", "spawn"),
("fork", "linux", "fork"),
("fork",... | 45 | 1,294 |
sanic | tests/worker/test_shared_ctx.py | .py | # 18
# 21-29
# 26
# 36-37
# 42
# 55
# 38->
import logging
from ctypes import c_int32
from multiprocessing import Pipe, Queue, Value
from os import environ
from typing import Any
import pytest
from sanic.types.shared_ctx import SharedContext
@pytest.mark.parametrize(
"item,okay",
(
(Pipe(), True),
... | 83 | 1,658 |
sanic | tests/worker/test_socket.py | .py | from pathlib import Path
from sanic.server.socket import (
bind_unix_socket,
configure_socket,
remove_unix_socket,
)
def test_setup_and_teardown_unix():
socket_address = "./test.sock"
path = Path.cwd() / socket_address
assert not path.exists()
bind_unix_socket(socket_address)
assert p... | 28 | 691 |
sanic | tests/worker/test_multiplexer.py | .py | import sys
from multiprocessing import Event
from os import environ, getpid
from typing import Any, Union
from unittest.mock import Mock
import pytest
from sanic import Sanic
from sanic.compat import use_context
from sanic.worker.multiplexer import WorkerMultiplexer
from sanic.worker.state import WorkerState
def n... | 159 | 4,118 |
sanic | tests/worker/test_manager.py | .py | from logging import ERROR, INFO
from signal import SIGINT
from unittest.mock import Mock, call, patch
import pytest
from sanic.compat import OS_IS_WINDOWS
from sanic.exceptions import ServerKilled
from sanic.worker.constants import RestartOrder
from sanic.worker.manager import WorkerManager
from sanic.worker.process ... | 452 | 13,173 |
sanic | tests/worker/test_worker_serve.py | .py | import logging
from os import environ
from unittest.mock import Mock, patch
import pytest
from sanic.app import Sanic
from sanic.worker.loader import AppLoader
from sanic.worker.multiplexer import WorkerMultiplexer
from sanic.worker.process import Worker, WorkerProcess
from sanic.worker.serve import worker_serve
@... | 126 | 3,735 |
sanic | tests/worker/test_runner.py | .py | from unittest.mock import Mock, call, patch
import pytest
from sanic.app import Sanic
from sanic.http.constants import HTTP
from sanic.server.runners import _run_server_forever, serve
@patch("sanic.server.runners._serve_http_1")
@patch("sanic.server.runners._serve_http_3")
def test_run_http_1(_serve_http_3: Mock, _s... | 59 | 1,769 |
sanic | tests/worker/test_restarter.py | .py | from unittest.mock import Mock
import pytest
from sanic.worker.constants import ProcessState, RestartOrder
from sanic.worker.process import WorkerProcess
from sanic.worker.restarter import Restarter
def noop(*args, **kwargs):
pass
def make_worker_process(
name: str, state: ProcessState = ProcessState.STAR... | 90 | 2,504 |
sanic | tests/worker/test_reloader.py | .py | import re
import signal
import threading
from asyncio import Event
from logging import DEBUG
from pathlib import Path
from time import sleep
from unittest.mock import Mock
import pytest
from sanic.app import Sanic
from sanic.worker.constants import ProcessState, RestartOrder
from sanic.worker.loader import AppLoader... | 249 | 6,504 |
sanic | tests/worker/test_inspector.py | .py | try: # no cov
from ujson import dumps
except ModuleNotFoundError: # no cov
from json import dumps # type: ignore
from datetime import datetime
from unittest.mock import Mock, patch
from urllib.error import URLError
import pytest
from sanic_testing import TestManager
from sanic.cli.inspector_client import... | 170 | 4,844 |
sanic | tests/worker/test_state.py | .py | import pytest
from sanic.worker.state import WorkerState
def gen_state(**kwargs):
return WorkerState({"foo": kwargs}, "foo")
def test_set_get_state():
state = gen_state()
state["additional"] = 123
assert state["additional"] == 123
assert state.get("additional") == 123
assert state._state ==... | 92 | 2,103 |
sanic | tests/worker/conftest.py | .py | import pytest
def pytest_collection_modifyitems(items):
"""Group all worker tests to run on same xdist worker.
These tests spawn processes and can conflict with parallel execution.
"""
for item in items:
if "/worker/" in str(item.fspath):
item.add_marker(pytest.mark.xdist_group(na... | 12 | 344 |
sanic | tests/typing/test_typing.py | .py | # flake8: noqa: E501
import subprocess
from pathlib import Path
import pytest
CURRENT_DIR = Path(__file__).parent
def run_check(path_location: str) -> str:
"""Use mypy to check the given path location and return the output."""
mypy_path = "mypy"
path = CURRENT_DIR / path_location
command = [mypy... | 125 | 3,372 |
sanic | tests/typing/samples/app_custom_config.py | .py | from sanic import Sanic
from sanic.config import Config
class CustomConfig(Config):
pass
app = Sanic("test", config=CustomConfig())
reveal_type(app) # noqa
| 11 | 165 |
sanic | tests/typing/samples/request_fully_custom.py | .py | from sanic import Request, Sanic
from sanic.config import Config
class CustomConfig(Config):
pass
class Foo:
pass
class RequestContext:
foo: Foo
class CustomRequest(Request[Sanic[CustomConfig, Foo], RequestContext]):
@staticmethod
def make_context() -> RequestContext:
ctx = RequestCo... | 35 | 628 |
sanic | tests/typing/samples/request_custom_ctx.py | .py | from types import SimpleNamespace
from sanic import Request, Sanic
from sanic.config import Config
class Foo:
pass
app = Sanic("test")
@app.get("/")
async def handler(request: Request[Sanic[Config, SimpleNamespace], Foo]):
reveal_type(request.ctx) # noqa
reveal_type(request.app) # noqa
| 18 | 308 |
sanic | tests/typing/samples/app_custom_ctx.py | .py | from sanic import Sanic
class Foo:
pass
app = Sanic("test", ctx=Foo())
reveal_type(app) # noqa
| 10 | 104 |
sanic | tests/typing/samples/request_custom_sanic.py | .py | from types import SimpleNamespace
from sanic import Request, Sanic
from sanic.config import Config
class CustomConfig(Config):
pass
app = Sanic("test", config=CustomConfig())
@app.get("/")
async def handler(
request: Request[Sanic[CustomConfig, SimpleNamespace], SimpleNamespace],
):
reveal_type(reque... | 20 | 373 |
sanic | tests/typing/samples/app_fully_custom.py | .py | from sanic import Sanic
from sanic.config import Config
class CustomConfig(Config):
pass
class Foo:
pass
app = Sanic("test", config=CustomConfig(), ctx=Foo())
reveal_type(app) # noqa
| 15 | 198 |
sanic | tests/typing/samples/app_default.py | .py | from sanic import Sanic
app = Sanic("test")
reveal_type(app) # noqa
| 6 | 71 |
sanic | scripts/changelog.py | .py | #!/usr/bin/env python
import sys
from os import path
if __name__ == "__main__":
try:
import click
import towncrier
except ImportError:
print(
"Please make sure you have installed towncrier and "
"click before using this tool"
)
sys.exit(1)
... | 64 | 1,449 |
sanic | scripts/release.py | .py | #!/usr/bin/env python
import sys
from argparse import ArgumentParser, Namespace
from collections import OrderedDict
from configparser import RawConfigParser
from datetime import datetime
from json import dumps
from os import chdir, path
from subprocess import PIPE, Popen
import towncrier
from jinja2 import BaseLoad... | 358 | 10,635 |
sanic | examples/logdna_example.py | .py | import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.request import Request
from sanic.response import json
log = logging.getLogger("logdna")
log.setLevel(logging.INFO)
def get_my_ip_ad... | 61 | 1,272 |
sanic | examples/unix_socket.py | .py | from sanic import Sanic, response
app = Sanic("Example")
@app.route("/test")
async def test(request):
return response.text("OK")
if __name__ == "__main__":
app.run(unix="./uds_socket")
| 14 | 199 |
sanic | examples/teapot.py | .py | from sanic import Sanic
from sanic import response as res
app = Sanic("Example")
@app.route("/")
async def test(req):
return res.text("I'm a teapot", status=418)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
| 15 | 238 |
sanic | examples/rollbar_example.py | .py | from os import getenv
import rollbar
from sanic import Sanic
from sanic.exceptions import SanicException
from sanic.handlers import ErrorHandler
rollbar.init(getenv("ROLLBAR_API_KEY"))
class RollbarExceptionHandler(ErrorHandler):
def default(self, request, exception):
rollbar.report_message(str(except... | 29 | 644 |
sanic | examples/run_async_advanced.py | .py | import asyncio
from signal import SIGINT, signal
import uvloop
from sanic import Sanic, response
from sanic.server import AsyncioServer
app = Sanic("Example")
@app.before_server_start
async def before_server_start(app, loop):
print("Async Server starting")
@app.after_server_start
async def after_server_sta... | 70 | 1,813 |
sanic | examples/blueprint_middlware_execution_order.py | .py | from sanic import Blueprint, Sanic
from sanic.response import text
"""
Demonstrates that blueprint request middleware are executed in the order they
are added. And blueprint response middleware are executed in _reverse_ order.
On a valid request, it should print "1 2 3 6 5 4" to terminal
"""
app = Sanic("Example")
... | 55 | 985 |
sanic | examples/amending_request_object.py | .py | from random import randint
from sanic import Sanic
from sanic.response import text
app = Sanic("Example")
@app.middleware("request")
def append_request(request):
request.ctx.num = randint(0, 100)
@app.get("/pop")
def pop_handler(request):
return text(request.ctx.num)
@app.get("/key_exist")
def key_exis... | 31 | 586 |
sanic | examples/exception_monitoring.py | .py | """
Example intercepting uncaught exceptions using Sanic's error handler framework.
This may be useful for developers wishing to use Sentry, Airbrake, etc.
or a custom system to log and monitor unexpected errors in production.
First we create our own class inheriting from Handler in sanic.exceptions,
and pass in an ins... | 56 | 1,785 |
sanic | examples/add_task_sanic.py | .py | # -*- coding: utf-8 -*-
import asyncio
from sanic import Sanic
app = Sanic("Example")
async def notify_server_started_after_five_seconds():
await asyncio.sleep(5)
print("Server successfully started!")
app.add_task(notify_server_started_after_five_seconds())
if __name__ == "__main__":
app.run(host="... | 20 | 341 |
sanic | examples/websocket.py | .py | from sanic import Sanic
from sanic.response import redirect
app = Sanic("Example")
app.static("index.html", "websocket.html")
@app.route("/")
def index(request):
return redirect("index.html")
@app.websocket("/feed")
async def feed(request, ws):
while True:
data = "hello!"
print("Sending:... | 28 | 505 |
sanic | examples/limit_concurrency.py | .py | import asyncio
import httpx
from sanic import Sanic
from sanic.response import json
app = Sanic("Example")
sem = None
@app.before_server_start
def init(sanic, _):
global sem
concurrency_per_worker = 4
sem = asyncio.Semaphore(concurrency_per_worker)
async def bounded_fetch(session, url):
"""
... | 44 | 835 |
sanic | examples/modify_header_example.py | .py | """
Modify header or status in response
"""
from sanic import Sanic, response
app = Sanic("Example")
@app.route("/")
def handle_request(request):
return response.json(
{"message": "Hello world!"},
headers={"X-Served-By": "sanic"},
status=200,
)
@app.route("/unauthorized")
def hand... | 31 | 575 |
sanic | examples/request_timeout.py | .py | import asyncio
from sanic import Sanic, response
from sanic.config import Config
from sanic.exceptions import RequestTimeout
Config.REQUEST_TIMEOUT = 1
app = Sanic("Example")
@app.route("/")
async def test(request):
await asyncio.sleep(3)
return response.text("Hello, world!")
@app.exception(RequestTimeou... | 25 | 492 |
sanic | examples/simple_async_view.py | .py | from sanic import Sanic
from sanic.response import text
from sanic.views import HTTPMethodView
app = Sanic("some_name")
class SimpleView(HTTPMethodView):
def get(self, request):
return text("I am get method")
def post(self, request):
return text("I am post method")
def put(self, reques... | 42 | 964 |
sanic | examples/override_logging.py | .py | import logging
from sanic import Sanic, text
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
logging_format += "%(message)s"
logging.basicConfig(format=logging_format, level=logging.DEBUG)
log = logging.getLogger()
# Set logger to override de... | 25 | 541 |
sanic | examples/authorized_sanic.py | .py | # -*- coding: utf-8 -*-
from functools import wraps
from sanic import Sanic
from sanic.response import json
app = Sanic("Example")
def check_request_for_authorization_status(request):
# Note: Define your check, for instance cookie, session.
flag = True
return flag
def authorized(f):
@wraps(f)
... | 45 | 1,070 |
sanic | examples/try_everything.py | .py | import os
from sanic import Sanic, response
from sanic.exceptions import ServerError
from sanic.log import logger as log
app = Sanic("Example")
@app.route("/")
async def test_async(request):
return response.json({"test": True})
@app.route("/sync", methods=["GET", "POST"])
def test_sync(request):
return r... | 124 | 2,586 |
sanic | examples/raygun_example.py | .py | from os import getenv
from raygun4py.raygunprovider import RaygunSender
from sanic import Sanic
from sanic.exceptions import SanicException
from sanic.handlers import ErrorHandler
class RaygunExceptionReporter(ErrorHandler):
def __init__(self, raygun_api_key=None):
super().__init__()
if raygun_a... | 34 | 879 |
sanic | examples/vhosts.py | .py | from sanic import Sanic, response
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic("Example")
bp = Bl... | 46 | 1,011 |
sanic | examples/pytest_xdist.py | .py | """pytest-xdist example for sanic server
Install testing tools:
$ pip install pytest pytest-xdist
Run with xdist params:
$ pytest examples/pytest_xdist.py -n 8 # 8 workers
"""
import re
import pytest
from sanic_testing import SanicTestClient
from sanic_testing.testing import PORT as PORT_BASE
from sani... | 55 | 1,070 |
sanic | examples/url_for_example.py | .py | from sanic import Sanic, response
app = Sanic("Example")
@app.route("/")
async def index(request):
# generate a URL for the endpoint `post_handler`
url = app.url_for("post_handler", post_id=5)
# the URL is `/posts/5`, redirect to it
return response.redirect(url)
@app.route("/posts/<post_id>")
asyn... | 22 | 492 |
sanic | examples/blueprints.py | .py | from sanic import Blueprint, Sanic
from sanic.response import file, json
app = Sanic("Example")
blueprint = Blueprint("bp_example", url_prefix="/my_blueprint")
blueprint2 = Blueprint("bp_example2", url_prefix="/my_blueprint2")
blueprint3 = Blueprint("bp_example3", url_prefix="/my_blueprint3")
@blueprint.route("/foo... | 42 | 968 |
sanic | examples/static_assets.py | .py | from sanic import Sanic
app = Sanic("Example")
app.static("/", "./static")
| 7 | 78 |
sanic | examples/run_asgi.py | .py | """
1. Create a simple Sanic app
0. Run with an ASGI server:
$ uvicorn run_asgi:app
or
$ hypercorn run_asgi:app
"""
from pathlib import Path
from sanic import Sanic, response
app = Sanic("Example")
@app.route("/text")
def handler_text(request):
return response.text("Hello")
@app.route("/json")
d... | 90 | 1,825 |
sanic | examples/versioned_blueprint_group.py | .py | from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json
app = Sanic(name="blue-print-group-version-example")
bp1 = Blueprint(name="ultron", url_prefix="/ultron")
bp2 = Blueprint(name="vision", url_prefix="/vision", strict_slashes=None)
bpg = Blueprint.group(
bp1, bp2, url_... | 38 | 967 |
sanic | examples/sentry_example.py | .py | from os import getenv
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.sanic import SanicIntegration
from sanic import Sanic
from sanic.response import json
sentry_init(
dsn=getenv("SENTRY_DSN"),
integrations=[SanicIntegration()],
)
app = Sanic("Example")
# noinspection PyUnusedLoc... | 32 | 657 |
sanic | examples/log_request_id.py | .py | import logging
from contextvars import ContextVar
from sanic import Sanic, response
log = logging.getLogger(__name__)
class RequestIdFilter(logging.Filter):
def filter(self, record):
try:
record.request_id = app.ctx.request_id.get(None) or "n/a"
except AttributeError:
r... | 78 | 1,686 |
sanic | examples/http_redirect.py | .py | from sanic import Sanic, response, text
from sanic.handlers import ErrorHandler
from sanic.server.async_server import AsyncioServer
HTTP_PORT = 9999
HTTPS_PORT = 8888
http = Sanic("http")
http.config.SERVER_NAME = f"localhost:{HTTP_PORT}"
https = Sanic("https")
https.config.SERVER_NAME = f"localhost:{HTTPS_PORT}"
... | 75 | 1,734 |
sanic | examples/delayed_response.py | .py | from asyncio import sleep
from sanic import Sanic, response
app = Sanic("DelayedResponseApp", strict_slashes=True)
app.config.AUTO_EXTEND = False
@app.get("/")
async def handler(request):
return response.redirect("/sleep/3")
@app.get("/sleep/<t:float>")
async def handler2(request, t=0.3):
await sleep(t)
... | 23 | 442 |
sanic | examples/hello_world.py | .py | from sanic import Sanic, response
app = Sanic("Example")
@app.route("/")
async def test(request):
return response.json({"test": True})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
| 14 | 211 |
sanic | examples/run_async.py | .py | import asyncio
import uvloop
from sanic import Sanic, response
app = Sanic("Example")
@app.route("/")
async def test(request):
return response.json({"answer": "42"})
async def main():
server = await app.create_server(
port=8000, host="0.0.0.0", return_asyncio_server=True
)
if server is ... | 31 | 507 |
sanic | examples/redirect_example.py | .py | from sanic import Sanic, response
app = Sanic("Example")
@app.route("/")
def handle_request(request):
return response.redirect("/redirect")
@app.route("/redirect")
async def test(request):
return response.json({"Redirected": True})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
| 19 | 314 |
sanic | examples/request_stream/server.py | .py | from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import stream, text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
bp = Blueprint("bp_example")
app = Sanic("Example")
class SimpleView(HTTPMethodView):
@stream_decorator
async def p... | 64 | 1,512 |
sanic | examples/request_stream/client.py | .py | import requests
# Warning: This is a heavy process.
data = ""
for i in range(1, 250000):
data += str(i)
r = requests.post("http://0.0.0.0:8000/stream", data=data)
print(r.text)
| 12 | 185 |
tornado | setup.py | .py | #
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | 136 | 4,636 |
tornado | maint/scripts/test_resolvers.py | .py | #!/usr/bin/env python
"""Basic test for Tornado resolvers.
Queries real domain names and prints the results from each resolver.
Requires a working internet connection, which is why it's not in a
unit test.
Will be removed in Tornado 7.0 when the pluggable resolver system is
removed.
"""
import pprint
import socket
f... | 65 | 1,725 |
tornado | maint/scripts/custom_fixers/fix_future_imports.py | .py | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
return isinstance(stm... | 60 | 2,175 |
tornado | maint/scripts/custom_fixers/fix_unicode_literal.py | .py | from lib2to3 import fixer_base
from lib2to3.fixer_util import String
class FixUnicodeLiteral(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'u'
trailer<
'('
arg=any
')'
>
>
"""
def transform(self, node, results):
... | 20 | 407 |
tornado | maint/vm/windows/bootstrap.py | .py | #!/usr/bin/env python
r"""Installs files needed for tornado testing on windows.
These instructions are compatible with the VMs provided by http://modern.ie.
The bootstrapping script works on the WinXP/IE6 and Win8/IE10 configurations,
although tornado's tests do not pass on XP.
1) Install virtualbox guest additions ... | 90 | 3,262 |
tornado | maint/benchmark/template_benchmark.py | .py | #!/usr/bin/env python
#
# A simple benchmark of tornado template rendering, based on
# https://github.com/mitsuhiko/jinja2/blob/master/examples/bench.py
import sys
from timeit import Timer
from tornado.options import options, define, parse_command_line
from tornado.template import Template
define('num', default=100,... | 72 | 1,596 |
tornado | maint/benchmark/parsing_benchmark.py | .py | #!/usr/bin/env python
import re
import timeit
from enum import Enum
from typing import Callable
from tornado.httputil import HTTPHeaders
from tornado.options import define, options, parse_command_line
define("benchmark", type=str)
define("num_runs", type=int, default=1)
_CRLF_RE = re.compile(r"\r?\n")
_TEST_HEADER... | 113 | 3,085 |
tornado | maint/benchmark/benchmark.py | .py | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | 74 | 2,027 |
tornado | maint/benchmark/gen_benchmark.py | .py | #!/usr/bin/env python
#
# A simple benchmark of the tornado.gen module.
# Runs in two modes, testing new-style (@coroutine and Futures)
# and old-style (@engine and Tasks) coroutines.
from timeit import Timer
from tornado import gen
from tornado.options import options, define, parse_command_line
define('num', defaul... | 54 | 1,195 |
tornado | maint/benchmark/chunk_benchmark.py | .py | #!/usr/bin/env python
#
# Downloads a large file in chunked encoding with both curl and simple clients
import logging
from tornado.curl_httpclient import CurlAsyncHTTPClient
from tornado.simple_httpclient import SimpleAsyncHTTPClient
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_... | 56 | 1,622 |
tornado | maint/test/cython/setup.py | .py | from setuptools import setup
try:
import Cython.Build
except:
Cython = None
if Cython is None:
ext_modules = None
else:
ext_modules = Cython.Build.cythonize('cythonapp.pyx')
setup(
name='cythonapp',
py_modules=['cythonapp_test', 'pythonmodule'],
ext_modules=ext_modules,
setup_requires... | 19 | 341 |
tornado | maint/test/cython/cythonapp_test.py | .py | from tornado.testing import AsyncTestCase, gen_test
from tornado.util import ArgReplacer
import unittest
import cythonapp
class CythonCoroutineTest(AsyncTestCase):
@gen_test
def test_native_coroutine(self):
x = yield cythonapp.native_coroutine()
self.assertEqual(x, "goodbye")
@gen_test
... | 36 | 1,196 |
tornado | maint/test/cython/pythonmodule.py | .py | from tornado import gen
@gen.coroutine
def hello():
yield gen.sleep(0.001)
raise gen.Return("hello")
| 8 | 111 |
tornado | maint/test/websocket/server.py | .py | from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from tornado.websocket import WebSocketHandler
from tornado.web import Application
define('port', default=9000)
class EchoHandler(WebSocketHandler):
def on_message(self, message):
self.write_message(message,... | 24 | 607 |
tornado | maint/test/websocket/client.py | .py | import logging
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from tornado.websocket import websocket_connect
define('url', default='ws://localhost:9001')
define('name', default='Tornado')
@gen.engine
def run_tests():
url = options.url +... | 48 | 1,367 |
tornado | maint/test/mypy/bad.py | .py | from tornado.web import RequestHandler
class MyHandler(RequestHandler):
def get(self) -> str: # Deliberate type error
return "foo"
| 7 | 146 |
tornado | maint/test/mypy/good.py | .py | from tornado import gen
from tornado.web import RequestHandler
class MyHandler(RequestHandler):
def get(self) -> None:
self.write("foo")
async def post(self) -> None:
await gen.sleep(1)
self.write("foo")
| 12 | 239 |
tornado | maint/test/redbot/red_test.py | .py | #!/usr/bin/env python
import logging
from redbot.resource import HttpResource
import redbot.speak as rs
import thor
import threading
from tornado import gen
from tornado.options import parse_command_line
from tornado.testing import AsyncHTTPTestCase
from tornado.web import RequestHandler, Application, asynchronous
imp... | 264 | 8,805 |
tornado | tornado/netutil.py | .py | #
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | 671 | 25,052 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.