def test_application_supports_dynamic_attributes(): app = Application() foo = object() assert hasattr(app, 'foo') is False, 'This test makes sense if such attribute is not defined' app.foo = foo assert app.foo is foo
def use_templates(app: Application, loader: PackageLoader, enable_async: bool = False): try: env = app.services['jinja_environment'] except KeyError: env = Environment(loader=loader, autoescape=select_autoescape(['html', 'xml']), auto_reload=app.debug, enable_async=enable_async) app.services['jinja_environment'] = env env.globals['app'] = app if enable_async: async def async_view(name: str, *args, **kwargs): return get_response(await render_template_async( env.get_template(template_name(name)), *args, **kwargs)) return async_view def sync_view(name: str, *args, **kwargs): return get_response( render_template(env.get_template(template_name(name)), *args, **kwargs)) return sync_view
def test_use_templates_throws_for_invalid_services(): app = Application(services={}) # type: ignore with pytest.raises(TypeError): use_templates(app, loader=PackageLoader("tests.testapp", "templates"), enable_async=False)
def configure_application(services: Container, context: ServicesRegistrationContext, configuration: Configuration): app = Application(services=services, show_error_details=configuration.show_error_details, debug=configuration.debug) app.on_start += context.initialize app.on_stop += context.dispose configure_error_handlers(app) configure_authentication(app) configure_templating(app, configuration) app.serve_files('app/static') return app
def test_application_use_templates_with_services(): app = Application(services=Services()) use_templates(app, loader=PackageLoader("tests.testapp", "templates"), enable_async=False) assert isinstance(app.services, Services) assert app.services["jinja_environment"] is not None
def use_templates(app: Application, loader: PackageLoader): try: env = app.services['jinja_environment'] except KeyError: env = Environment( loader=loader, autoescape=select_autoescape(['html', 'xml']) ) app.services['jinja_environment'] = env env.globals['app'] = app def view(name: str, model=None): return get_response(render_template(env.get_template(template_name(name)), model)) return view
def configure_application( services: Container, context: ServicesRegistrationContext, configuration: Configuration, ) -> Application: app = Application(services=services, show_error_details=configuration.show_error_details) configure_routes(app) app.on_start += context.initialize app.on_stop += context.dispose configure_error_handlers(app) configure_authentication(app) return app
import io import uvicorn import asyncio from blacksheep import Request, Response, Content, Cookie from blacksheep.server import Application from blacksheep.server.responses import text, json, file, ContentDispositionType from blacksheep.server.bindings import FromQuery from itests.utils import CrashTest, ensure_folder app = Application(show_error_details=True) app.serve_files('static', discovery=True) @app.route('/hello-world') async def hello_world(): return text(f'Hello, World!') @app.router.head('/echo-headers') async def echo_headers(request): response = Response(200) for header in request.headers: response.add_header(header[0], header[1]) return response @app.route('/echo-cookies') async def echo_cookies(request):
# Disable all logging features import logging logging.disable() from blacksheep.server import Application from blacksheep.server.responses import text app = Application() @app.router.get("/") async def home(_): return text(f"") @app.router.get("/user/:id") async def user_info(_, id: int): return text(f"{id}") @app.router.post("/user") async def user(_): return text(f"") app.start()
import asyncio import io import os import pathlib import uvicorn from blacksheep import Content, Cookie, Request, Response from blacksheep.server import Application from blacksheep.server.bindings import FromQuery from blacksheep.server.files import ServeFilesOptions from blacksheep.server.responses import ContentDispositionType, file, json, text from itests.utils import CrashTest, ensure_folder app = Application(show_error_details=True) static_folder_path = pathlib.Path(__file__).parent.absolute() / "static" def get_static_path(file_name): static_folder_path = pathlib.Path(__file__).parent.absolute() / "static" return os.path.join(str(static_folder_path), file_name) app.serve_files(ServeFilesOptions(static_folder_path, discovery=True)) @app.route("/hello-world") async def hello_world(): return text(f"Hello, World!")
import os from datetime import datetime from blacksheep.server import Application from blacksheep.options import ServerOptions from blacksheep.server.responses import text app = Application(options=ServerOptions( '0.0.0.0', int(os.environ.get('SERVER_PORT', '44555')))) @app.route('/') async def home(request): return text(f'Hello, World! {datetime.utcnow().isoformat()}') app.start()
user=os.getenv("PGUSER", "benchmarkdbuser"), password=os.getenv("PGPASS", "benchmarkdbpass"), database="hello_world", host="tfb-database", port=5432, ) jinja_env = Environment( loader=PackageLoader("app", "templates"), autoescape=select_autoescape(["html", "xml"]), ) fortune_template = jinja_env.get_template("fortune.html") app = Application(options=ServerOptions(host="", port=8080, processes_count=workers)) app.on_start += configure_db def get_num_queries(request): try: value = request.query.get("queries") if value is None: return 1 query_count = int(value[0]) except (KeyError, IndexError, ValueError): return 1
async def test_application_post_multipart_formdata_handler(): app = Application(debug=True) @app.router.post(b'/files/upload') async def upload_files(request): data = await request.form() assert data is not None assert data[0].name == b'text1' assert data[0].file_name is None assert data[0].content_type is None assert data[0].data == b'text default' assert data[1].name == b'text2' assert data[1].file_name is None assert data[1].content_type is None assert data[1].data == 'aωb'.encode('utf8') assert data[2].name == b'file1' assert data[2].file_name == b'a.txt' assert data[2].content_type == b'text/plain' assert data[2].data == b'Content of a.txt.\n' assert data[3].name == b'file2' assert data[3].file_name == b'a.html' assert data[3].content_type == b'text/html' assert data[3].data == b'<!DOCTYPE html><title>Content of a.html.</title>\n' assert data[4].name == b'file3' assert data[4].file_name == b'binary' assert data[4].content_type == b'application/octet-stream' assert data[4].data == 'aωb'.encode('utf8') files = await request.files() assert files[0].name == b'file1' assert files[0].file_name == b'a.txt' assert files[0].content_type == b'text/plain' assert files[0].data == b'Content of a.txt.\n' assert files[1].name == b'file2' assert files[1].file_name == b'a.html' assert files[1].content_type == b'text/html' assert files[1].data == b'<!DOCTYPE html><title>Content of a.html.</title>\n' assert files[2].name == b'file3' assert files[2].file_name == b'binary' assert files[2].content_type == b'application/octet-stream' assert files[2].data == 'aωb'.encode('utf8') file_one = await request.files('file1') assert file_one[0].name == b'file1' return Response(200) handler = get_new_connection_handler(app) boundary = b'---------------------0000000000000000000000001' content = b'\n'.join([ boundary, b'Content-Disposition: form-data; name="text1"', b'', b'text default', boundary, b'Content-Disposition: form-data; name="text2"', b'', 'aωb'.encode('utf8'), boundary, b'Content-Disposition: form-data; name="file1"; filename="a.txt"', b'Content-Type: text/plain', b'', b'Content of a.txt.', b'', boundary, b'Content-Disposition: form-data; name="file2"; filename="a.html"', b'Content-Type: text/html', b'', b'<!DOCTYPE html><title>Content of a.html.</title>', b'', boundary, b'Content-Disposition: form-data; name="file3"; filename="binary"', b'Content-Type: application/octet-stream', b'', 'aωb'.encode('utf8'), boundary + b'--' ]) message = b'\n'.join([ b'POST /files/upload HTTP/1.1', b'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0', b'Content-Type: multipart/form-data; boundary=' + boundary, b'Content-Length: ' + str(len(content)).encode(), b'Host: foo\n', content, b'\r\n\r\n' ]) handler.data_received(message)
from blacksheep.server import Application, ServerOptions import multiprocessing from blacksheep.server.responses import text app = Application( ServerOptions(host="0.0.0.0", port=3000, processes_count=multiprocessing.cpu_count()), debug=False, ) @app.router.get("/") async def home(_): return text(f"") @app.router.get("/user/:id") async def user_info(_, id: int): return text(f"{id}") @app.router.post("/user") async def user(_): return text(f"") app.start()
from datetime import datetime from blacksheep.server import Application from blacksheep.server import text app = Application() @app.route('/') async def home(request): return text(f'Hello, World! {datetime.utcnow().isoformat()}')
import json from base64 import urlsafe_b64decode import uvicorn from guardpost.authentication import Identity from guardpost.authorization import AuthorizationContext from guardpost.common import AuthenticatedRequirement from blacksheep import Response, TextContent from blacksheep.server import Application from blacksheep.server.authentication import AuthenticationHandler from blacksheep.server.authorization import Policy, Requirement, auth from itests.utils import CrashTest app_two = Application() class HandledException(Exception): def __init__(self): super().__init__("Example exception") async def handle_test_exception(app, request, http_exception): return Response(200, content=TextContent(f"Fake exception, to test handlers")) app_two.exceptions_handlers[HandledException] = handle_test_exception class AdminRequirement(Requirement):
import uvicorn from blacksheep.server import Application from blacksheep.server.bindings import FromForm from blacksheep.server.bindings import Request from blacksheep.server.templating import use_templates from blacksheep.server.responses import redirect, status_code, text, json as res_json from jinja2 import PackageLoader from event import Event from fips import get_fips import json from event_risk import event_risk import database as db from datetime import datetime, date from nanoid import generate app = Application() get = app.router.get post = app.router.post view = use_templates(app, loader=PackageLoader('app', 'templates')) @app.route('/') def home(): return view('index', {}) @app.route('/create-event') def create_event(): return view('create-event', {})