Package: yasgi
Yasgi framework a tiny, small, easy to learn, fast to code ⚡️Yasgi is a tiny, small (high-performance), web framework for building APIs with Python 3.9+ using orjson.The key features are:Tiny: Small size and performance.Fewer bugs: Reduce about 40% of human (developer) induced errors.Intuitive: Great editor support.Completioneverywhere. Less time debugging.Easy: Designed to be easy to use, Play and Plug.Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.Installation$pipinstallyasgi---> 100%You will also need an ASGI server, for production such asUvicornorHypercorn.$pipinstall"uvicorn[standard]"---> 100%ExampleCreate itCreate a filemain.pywith:fromyasgiimportYASGI,Routingapp=YASGI(content_type="text/html")@Routing("/endpoint",methods=["GET","POST"])asyncdefendpoint(Request,Response):# set response headerResponse.add_header("X-header","hello")# set response cookieResponse.set_cookie("cookie_from_server","384")# set response bodyreturn"hello world"Now you should run it!Run itRun the server with:$uvicornmain:app--reloadINFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO:     Started reloader process [28720]INFO:     Started server process [28722]INFO:     Waiting for application startup.INFO:     Application startup complete.The commanduvicorn main:apprefers to:main: the filemain.py(the Python "module").app: the object created inside ofmain.pywith the lineapp = YASGI().--reload: make the server restart after code changes. Only do this for development.InitializingfromyasgiimportYASGIapplication=YASGI(content_type="application/json",allow="*",charset="UTF-8")ASGI parameterscontent_type- specifies the default content type of generated responses (optional, default:application/json)charset- specifies the default charset generated responses (optional, default:UTF-8)allow- specifies global setting forAccess-Control-Allow-Originheader - can be overwrite by passing that header to response headers (optional, defaultNone- for public API should be set to*)RoutingRouters parametersendpoint- object should contain str or regex Pattern to match request path (mandatory)type- defines that routed is serving HTTP or WebSocket protocol (possible values:http,websocket; default:http)methods- list of HTTP methods to match request method - higher priority than method (optional, default: [GET], should be only be specified onhttptype routes)*kwargs - other arguments - can be accessed by middleware in statesroutedandendcontent-typeUsageRoute is used as a decorator callable object you want to use as router method.
Router method takes two mandatory argumentsRequestandResponse(explained below in a separate section).
Router method can also take variables from router regex match (if used).HTTP ExamplesimportrefromyasgiimportRouting# simple route@Routing("/endpoint",method="GET")# simple route methodasyncdefrouted_method_1(request,response):# response return without status code & mime typereturn"Response from route 1"# re package import needed@Routing(re.compile("/endpoint/(\d+)$"),methods=["GET","POST"])# regex route, with multiple methodsasyncdefrouted_method_2(request,response,number):# full response returnreturnf"Response from route - url_number is:{number}","200 OK","text/html"@Routing("/endpoint3",methods=["GET","POST"])#simple route, with multiple methodsasyncdefrouted_method_2(request,response):# alternatively can be called response method set to set responseresponse.set("Response by set")Raise HTTP statusRaise HTTPStatus is used to raise HTTP status code, and optional message.fromhttpimportHTTPStatusfromyasgiimportRouting@Routing("/raise_endpoint",methods=["POST"])asyncdefrouted_method_2(request,response):ifnotrequest.data:raiseHTTPStatus("400 BAD REQUEST","400 BAD REQUEST")return"data sent"Request & Response objectsInstances of these object are given to every function that is called with@Routingdecorator.fromyasgiimportRouting@Routing("/endpoint",method="GET")asyncdefendpoint(Request,Response):# instances of Request and Response objectspassRequest items and methods (HTTP)method- request method (GET, POST etc.) : read onlypath- request path: read onlyquery_params-dictof query_string parametersdata- request parsed data (json, -www-form-urlencoded, multipart/form-data) : read onlyheaders- HTTP headers : read only (may containcontent_lengthandcontent_typein post requests)cookies- dict containsSimpleCookieobject of every cookie loadedscope- raw asgi scope objectevent- raw asgi event objectResponse  items and methods (HTTP)content_type- response content-type : read only - can be specified in routecharset- response encoding; default:UTF-8headers-listof response headers:redirect(location, status)- redirects response to (location,statusif not provide is set to302)set_cookie(name, value, expires=None, maxAge=None, **kwargs)- adds cookie to response with obvious parameters, you can alow add additional arguments (kwargs) such asDomain,Path,Secure,HttpOnlyadd_header(name, value)- adds header to responseprocess(data, status=200)- allow to manual process responseDevelopment 🚧Setup environment 📦You should create a virtual environment and activate it:python-mvenvvenv/sourcevenv/bin/activateAnd then install the development dependencies:# Install Flitpipinstallflit# Install dependenciesflitinstall--symlinkRun tests 🌝You can run all the tests with:bashscripts/test.shNote: You can also generate a coverage report with:bashscripts/test_html.shFormat the code 🍂Execute the following command to applypre-commitformatting:bashscripts/format.shExecute the following command to applymypytype checking:bashscripts/lint.shLicenseThis project is licensed under the terms of theGNU GENERAL PUBLIC LICENSE Version 3.