### Install BlackSheep Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Install the BlackSheep framework using pip. This is the first step to start building web applications. ```bash pip install blacksheep ``` -------------------------------- ### Start Integration Test Server Source: https://github.com/neoteroi/blacksheep/blob/main/itests/README.md Run this command from the root of the repository to start the integration test server. Ensure PYTHONPATH is set correctly. ```bash # from the root of the repository export PYTHONPATH="." export APP_DEFAULT_ROUTER=false python itests/app_1.py ``` -------------------------------- ### Install Benchmark Dependencies Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Installs the necessary requirements for running the benchmarks. Ensure you are in the root folder of the project. ```bash pip install -r req.txt ``` -------------------------------- ### BlackSheep HTTP Client Example Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Demonstrates how to use the BlackSheep HTTP client to make a GET request and retrieve the response text. Requires `h11` and `h2` libraries for HTTP/2 support. ```python import asyncio from blacksheep.client import ClientSession async def client_example(): async with ClientSession() as client: response = await client.get("https://docs.python.org/3/") text = await response.text() print(text) asyncio.run(client_example()) ``` -------------------------------- ### Install BlackSheep CLI Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Install the BlackSheep command-line interface tool to quickly bootstrap new projects. This package provides project templates. ```bash pip install blacksheep-cli ``` -------------------------------- ### Install ASGI Server (uvicorn) Source: https://github.com/neoteroi/blacksheep/blob/main/README.md BlackSheep requires an ASGI HTTP server to run. Install uvicorn using pip. Other servers like hypercorn or granian can also be used. ```bash $ pip install uvicorn ``` -------------------------------- ### Common Lorem Ipsum Text Example Source: https://github.com/neoteroi/blacksheep/blob/main/perf/benchmarks/res/lorem.txt A standard rendition of Lorem Ipsum used as placeholder content in design and development. ```plaintext Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` -------------------------------- ### BlackSheep Authentication and Authorization Strategies Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Shows how to configure authentication and authorization strategies in BlackSheep. Includes examples for setting up custom authentication handlers, policies, and route-level access control for authenticated users and specific roles like 'admin'. ```python app.use_authentication() .add(ExampleAuthenticationHandler()) app.use_authorization() .add(AdminsPolicy()) @auth("admin") @get("/") async def only_for_admins(): ... @auth() @get("/") async def only_for_authenticated_users(): ... ``` -------------------------------- ### Basic BlackSheep Application Source: https://github.com/neoteroi/blacksheep/blob/main/README.md A minimal BlackSheep application with a single route that returns a "Hello, World!" message with the current UTC time. Ensure you have the necessary imports. ```python from datetime import datetime, timezone from blacksheep import Application, get app = Application() @get("/") async def home(): return f"Hello, World! {datetime.now(timezone.utc).isoformat()}" ``` -------------------------------- ### Run Benchmark Suite Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Executes the main benchmark suite. Set PYTHONPATH to the project root. Can be run multiple times by specifying the --times argument. ```bash export PYTHONPATH="." python perf/main.py ``` ```bash python perf/main.py --times 3 ``` -------------------------------- ### Run Single Benchmark Interactively Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Allows running a single benchmark file interactively using IPython or profiling with cProfile. Ensure PYTHONPATH is set. ```bash export PYTHONPATH="." ipython perf/benchmarks/writeresponse.py timeit ``` ```bash python -m cProfile -s tottime perf/benchmarks/writeresponse.py | head -n 50 ``` -------------------------------- ### Initialize Swagger UI Bundle Source: https://github.com/neoteroi/blacksheep/blob/main/blacksheep/server/res/swagger-ui.html This code initializes the Swagger UI bundle, configuring it to load API specifications from a given URL and setting up OAuth2 redirect. It's used to display interactive API documentation. ```javascript const ui = SwaggerUIBundle({ url: "##SPEC_URL##", oauth2RedirectUrl: window.location.origin + window.location.pathname.replace(/\/$/, "") + "/oauth2-redirect", dom_id: "#swagger-ui", presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", deepLinking: true, showExtensions: true, showCommonExtensions: true }); ``` -------------------------------- ### Run BlackSheep Application with Uvicorn Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Run a BlackSheep application using the uvicorn ASGI server. Assumes your application instance is named 'app' in a file named 'server.py'. ```bash # if the BlackSheep app is defined in a file `server.py` $ uvicorn server:app ``` -------------------------------- ### Reset and Rerun Benchmarks Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Command to clean previous benchmark results, run the main benchmark suite, and generate a new report. Useful when modifying benchmark code. ```bash export PYTHONPATH="." rm -rf benchmark_results && python perf/main.py && python perf/genreport.py ``` -------------------------------- ### Run Historical Benchmarks Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Executes benchmarks for specific Git commit SHAs to compare performance across history. Requires specifying commit hashes as arguments. ```bash python perf/historyrun.py --commits 82ed065 1237b1e ``` -------------------------------- ### Configure Scalar UI Theme Source: https://github.com/neoteroi/blacksheep/blob/main/blacksheep/server/res/scalar-ui.html Set the theme for the Scalar UI by stringifying a JSON object and assigning it to the 'configuration' dataset property of the 'api-reference' element. This is useful for applying custom themes or default settings. ```javascript document.getElementById("api-reference").dataset.configuration = JSON.stringify({ theme: "default" }) ``` -------------------------------- ### VS Code Debug Configuration Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md A launch.json configuration for Visual Studio Code to debug Python files within the project. Sets the PYTHONPATH environment variable for the debugger. ```json { "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Current File", "type": "debugpy", "request": "launch", "program": "${file}", "console": "integratedTerminal", "env": { "PYTHONPATH": "${workspaceFolder}" } } ] } ``` -------------------------------- ### Cicero's De finibus bonorum et malorum (Source Fragment) Source: https://github.com/neoteroi/blacksheep/blob/main/perf/benchmarks/res/lorem.txt A section from Cicero's work, which is the origin of Lorem Ipsum, with fragments used in Lorem Ipsum highlighted. Letters in brackets were added to Lorem Ipsum and were not present in the source text. ```latin [32] Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum[d] exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? [D]Quis autem vel eum i[r]ure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? [33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem reru[d]um facilis est e[r]t expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellend[a]us. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. ``` -------------------------------- ### Automatic Request Data Binding in BlackSheep Source: https://github.com/neoteroi/blacksheep/blob/main/README.md Demonstrates automatic binding of request data using type annotations and conventions for JSON payloads, route parameters, and query strings. Supports implicit and explicit query parameter handling with default values. ```python from dataclasses import dataclass from blacksheep import Application, FromJSON, FromQuery, get, post app = Application() @dataclass class CreateCatInput: name: str @post("/api/cats") async def example(data: FromJSON[CreateCatInput]): # in this example, data is bound automatically reading the JSON # payload and creating an instance of `CreateCatInput` ... @get("/:culture_code/:area") async def home(culture_code, area): # in this example, both parameters are obtained from routes with # matching names return f"Request for: {culture_code} {area}" @get("/api/products") def get_products( page: int = 1, size: int = 30, search: str = "", ): # this example illustrates support for implicit query parameters with # default values # since the source of page, size, and search is not specified and no # route parameter matches their name, they are obtained from query string ... @get("/api/products2") def get_products2( page: FromQuery[int] = FromQuery(1), size: FromQuery[int] = FromQuery(30), search: FromQuery[str] = FromQuery(""), ): # this example illustrates support for explicit query parameters with # default values # in this case, parameters are explicitly read from query string ... ``` -------------------------------- ### Generate XLSX Report Source: https://github.com/neoteroi/blacksheep/blob/main/perf/README.md Generates an Excel report from the benchmark results. This script processes the collected data into a readable format. ```bash python perf/genreport.py ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.