Saravanan666/pypi-org huggingface dataset:
Package: asgi_context
ASGI ContextZero dependency middleware for storing HTTP request data in scoped context.
By default the library exposes the middleware for creating the context and
header extrator builder which can be used e.g. for storing tracing headers.InstallationThe project is available on PyPI:pipinstallasgi_contextor you can use pre-built sdist and wheels fromReleasespage.Example usageFastAPIfromhttpimportHTTPStatusfromfastapiimportFastAPIfromasgi_contextimport(http_requst_context,ContextMiddleware,HeadersExtractorMiddlewareFactory,ValidationConfig,)app=FastAPI()defexample_headers_validator(header_value:str)->bool:return"example"invalue# will return 400 when missing specified headers or headers don't pass validationexample_headers_extractor_with_validation=HeadersExtractorMiddlewareFactory.build(base_name="example_with_validation",header_names=("X-Example",),validation_config=ValidationConfig(err_on_missing=HTTPStatus.BAD_REQUEST,err_on_invalid=HTTPStatus.BAD_REQUEST,validators={"X-Example":example_headers_validator,},),)example_headers_extractor_without_validation=HeadersExtractorMiddlewareFactory.build(base_name="example_without_validation",header_names=("X-Not-Validated-Example",))app.add_middleware(example_headers_extractor_with_validation)app.add_middleware(example_headers_extractor_without_validation)app.add_middleware(ContextMiddleware)@app.get("/")defindex():returnhttp_request_context["X-Example"]StarlitefromhttpimportHTTPStatusfromstarliteimportStarlite,getfromasgi_contextimport(http_requst_context,ContextMiddleware,HeadersExtractorMiddlewareFactory,ValidationConfig,)defexample_headers_validator(header_value:str)->bool:return"example"invalue# will return 400 when missing specified headers or headers don't pass validationexample_headers_extractor_with_validation=HeadersExtractorMiddlewareFactory.build(base_name="example",header_names=("X-Example",)validation_config=ValidationConfig(err_on_missing=HTTPStatus.BAD_REQUEST,err_on_invalid=HTTPStatus.BAD_REQUEST,validators={"X-Example":example_headers_validator,},),)example_headers_extractor_without_validation=HeadersExtractorMiddlewareFactory.build(base_name="example_without_validation",header_names=("X-Not-Validated-Example",))@get("/")defindex()->str:returnhttp_request_context["X-Example"]app=Starlite(route_handlers=[index],middleware=[ContextMiddleware,example_headers_extractor_with_validation,example_headers_extractor_without_validation,])
Package: asgi-cors-middleware
asgi-cors-middlewarePython package that allows whitelisting of urls on ASGI applications making it possible to perform cross origin requests from the browser.CORS in a nutshellCross-Origin Resource Sharing (CORS)allows a server to define any
origins other than its own that are safe for the browser to load resources from.Mozilla does a good job of explaining CORShere.BackgroundAssuming you have a web application that follows a client-server architecture, it's possible the frontend would be running on a server
different from the API. If the frontend application made a request to the API, this kind of request would be blocked by the browser.For security reasons, browsers block cross origin requests by default.A cross origin request is a request made to a server with a different url/ origin. To mitigate around this, we could simply add the url of the frontend application as an allowed origin on the API server.
Most web frameworks provide a way to do this or have third party libraries that achieve the same.asgi-cors-middlewareaims to provide a simple way to achieve the above for ASGI applications.FeaturesSimpleWorks with most ASGI frameworks (Django, Starlette, FastAPI, channels)Works with AriadneInstallationCan be installed via pippipinstallasgi-cors-middlewareUsageTo use the middleware, just import it like so:fromasgi_cors_middlewareimportCorsASGIAppTo start whitelisting origins, just wrap your asgi application instance withCorsASGIApp.app=CorsASGIApp(app=asgi_app_instance,origins=["www.example.com"])ExampleA simple HelloWorld application that whitelists the origins below:www.example.comlocalhost:9000Install an ASGI serverpipinstalluvicornCreate a file called example.py and update it with the code below:fromasgi_cors_middlewareimportCorsASGIAppclassHelloWorld:def__init__(self,scope):passasyncdef__call__(self,receive,send):awaitsend({'type':'http.response.start','status':200,'headers':[[b'content-type',b'text/plain'],]})awaitsend({'type':'http.response.body','body':b'Hello, world!',})app=CorsASGIApp(app=HelloWorld,origins=["www.example.com","localhost:9000"])That's it. For real, that's really it. Now your application is all set to allow requests fromwww.example.comand localhost:9000.Run the appuvicornexample:appContributingFor guidance and instructions, please seeCONTRIBUTING.md
Package: asgi-cors-strawberry
asgi-cors-strawberryASGI middleware to apply CORS header especially for Strawberry GraphQLinstallationpip install asgi-cors-strawberrywhen to useAccording to mdnMDN - CORS, cross-origin requests are
preflighted using OPTIONS method.
The response from preflight has Access-Control-Allow-Origin, Access-Control-Allow-Headers, etc.SinceStrawberry GraphQL Consumeris
designed to handle only GET and POST methods, if you use general ASGI CORS middleware, you will get a 405 code as a
response to preflight.Our middleware responds with Okay status in case of OPTIONS methodOur middleware checks Access-Control-Allow-Origin from hosts, wildcards setting,All hosts are allowed by default!Our middleware adds Content-Type in Access-Control-Allow-Headers, because gql will be passed to the requesthow to use# in django asgi.pyfromasgi_cors_strawberryimportCorsMiddleware...application=ProtocolTypeRouter({"http":URLRouter([re_path(r"^graphql",GraphQLHTTPConsumer.as_asgi(schema=schema)),re_path(r"^",get_asgi_application()),]),"websocket":URLRouter([re_path(r"^graphql",GraphQLWSConsumer.as_asgi(schema=schema))])})application=CorsMiddleware(application)The example above is an ASGI application
usingStrawberry-GraphQL[Channels]CorsMiddleware parametersCorsMiddleware(application, allow_all=True, hosts=[ ], host_wildcards=[ ], headers=["content-type", "authorization"])allow_allTrue if all hosts are allowedhostsif allow_all is False, hosts is a list of allowed hostshost_wildcardsyou can use wildcards in hosts, like ["*.example.com"]headersyou can add headers to Access-Control-Allow-Headersdefault header is "content-type" because gql will be passed to the requestTODOtestcase
Package: asgi-debug
asgi-debugASGI middleware for debugging ASGI applicationsInstallationpip install asgi-debugUsageWrap your application in the middleware like this:fromasgi_debugimportasgi_debug_decorator@asgi_debug_decorator()asyncdefhello_world_app(scope,receive,send):assertscope["type"]=="http"awaitsend({"type":"http.response.start","status":200,"headers":[[b"content-type",b"application/json"]],})awaitsend({"type":"http.response.body","body":b'{"hello": "world"}'})When you run the app, debugging information will print to your terminal.If you save the above indemo.pyyou canpip install uvicornand run it like this:uvicorn demo:hello_world_app
Package: asgi-dispatcher-middleware
asgi-dispatcher-middlewareMiddleware to Dispatch to multiple ASGI applications, extracted from hypercorn.Dispatch to multiple ASGI applicationsIt is often useful serve multiple ASGI applications at once, under differing root paths.
This middleware allows multiple applications to be served on different mounts.TheDispatcherMiddlewaretakes a dictionary of applications keyed by the root path.
The order of entry in this dictionary is important, as the root paths will be checked in
this order. Hence it is important to add/a/bbefore/aor the latter will match
everything first. Also note that the root path should not include the trailing slash.An example usage is to to serve a graphql application alongside a static file serving
application. Using the graphql app is calledgraphql_appserving everything with the
root path/graphqland a static file app calledstatic_appserving everything else
i.e. a root path of/theDispatcherMiddlewarecan be setup as,from asgi_dispatcher_middleware import DispatcherMiddleware

dispatcher_app = DispatcherMiddleware({
    "/graphql": graphql_app,
    "/": static_app,
})which can then be served by any asgi framework,$ hypercorn module:dispatcher_app
$ uvicorn module:dispatcher_appSee alsohypercorn:https://pgjones.gitlab.io/hypercorn/how_to_guides/dispatch_apps.html
Package: asgi_etags
asgi_etagsSimple etags middleware for asgi apps.InstallationThe library is available on PyPI:pipinstallasgi_etagsOr in theReleasestab, both insdistformat as well aswheels.Supported Python versionsCurrently the library supports Python 3.11 only.Example usage:With FastAPIfromfastapiimportFastAPIfromhashlibimportmd5fromasgi_etagsimportETagMiddlewareapp=FastAPI()app.add_middleware(ETagMiddleware,etag_generator=lambdabody:md5(body).hexdigest())@app.get("/")defhello_world():return{"hello":"world"}With LitestarfromlitestarimportLitestarfromhashlibimportmd5fromasgi_etagsimportETagMiddlewareFactory@get(path="/",media_type="application/json",sync_to_thread=False)defhello_world()->dict[str,str]:return{"hello":"world"}app=Litestar(route_handlers=[hello_world],middleware=[ETagMiddlewareFactory(lambdabody:md5(body).hexdigest())],)
Package: asgi-gzip
asgi-gzipgzip middleware for ASGI applications, extracted from StarletteInstallationInstall this library usingpip:pip install asgi-gzipUsagefromasgi_gzipimportGZipMiddlewarefrommy_asgi_appimportappgzip_app=GZipMiddleware(app)Consult theStarlette GZipMiddleware documentationfor full details.Should you use this package?This package exists purely for use by ASGI applications that want to add gzip support without adding the whole ofStarletteas a dependency.But... Starlette is actually a very light dependency! It's a small codebase and it only depends on two other small libraries - check itsinstall_requiresin the Starlettesetup.py module.So if you don't mind adding Starlette as a dependency, you should consider using that directly instead.Tracking StarletteSince this code is extracted from Starlette, it's important to keep watch for changes and bug fixes to the Starlette implementation that should be replicated here.The GitHub repository for this library usesGit scrapingto track changes to a copy of the Starlettegzip.pymodule, which is kept in thetracking/folder.Any time a change to that file is detected, an issue will be automatically created in the repository. This issue should be closed once the change to Starlette has been applied here, if necessary.For more details on how this works, seeAutomatically opening issues when tracked file content changes.DevelopmentTo contribute to this library, first checkout the code. Then create a new virtual environment:cd asgi-gzip
python -m venv venv
source venv/bin/activateNow install the dependencies and test dependencies:pip install -e '.[test]'To run the tests:pytest
Package: asgi_headers
asgi_headersSimple middleware for injecting headers in ASGI apps.InstallationThe library is available on PyPI:pipinstallasgi_headersOr in theReleasestab, both insdistformat as well aswheels.Supported Python versionsCurrently the library supports Python 3.11 only.Example usage:With FastAPIfromfastapiimportFastAPIfromasgi_headersimportInjectHeadersMiddlewareapp=FastAPI()app.add_middleware(InjectHeadersMiddleware,injections={("GET","/hello"):{"This-Header-Will-Be-Injected-To-All-GET-Requests-Starting-With-/foo-path":1},("*","/hello","This-Header-Will-Be-Injected-To-All-Requests-Starting-With-/foo-path","1")("GET","*","This-Header-Will-Be-Injected-To-All-GET-Requests","1")("*","*","This-Header-Will-Be-Injected-To-All-Requests","1")})@app.get("/hello")defhello_world():return{"hello":"world"}With LitestarfromlitestarimportLitestarfromasgi_headersimportInjectHeadersMiddlewareFactory@get(path="/",media_type="application/json",sync_to_thread=False)defhello_world()->dict[str,str]:return{"hello":"world"}app=Litestar(route_handlers=[hello_world],middleware=[InjectHeadersMiddlewareFactory(injections={("GET","/hello"):{"This-Header-Will-Be-Injected-To-All-GET-Requests-Starting-With-/foo-path":1},("*","/hello","This-Header-Will-Be-Injected-To-All-Requests-Starting-With-/foo-path","1")("GET","*","This-Header-Will-Be-Injected-To-All-GET-Requests","1")("*","*","This-Header-Will-Be-Injected-To-All-Requests","1")}),])
Package: asgikit
Asgikit - ASGI ToolkitAsgikit is a toolkit for building asgi applications and frameworks.It is intended to be a minimal library and provide the building blocks for other libraries.Theexamples directorycontain usage examples of several use casesFeatures:RequestHeadersCookiesBody (bytes, str, json, stream)FormResponsePlain textJsonStreamingFileWebsocketsRequest and ResponseAsgikitRequestandResponsewere designed to be have minimal interfaces,
so they only provide very few methods to read from the request and write to the response.
In particular, theResponseworks differently from most tools, in which you do not
return a response, but you write data into it.It is provided several functions to interact with the request and the response, for instance,
to read form data from the request and write json to the response.This strategy allows for simpler extensibility. For example, to parse json from the request
using an alternative json parser, you just need to write a function that reads the request.
Similarly, to write another data format into the response, you just write a function that
writes to the response.Example request and responsefromasgikit.requestsimportRequest,read_jsonfromasgikit.responsesimportrespond_jsonasyncdefmain(scope,receive,send):request=Request(scope,receive,send)# request methodmethod=request.method# request pathpath=request.path# request headersheaders=request.headers# read body as jsonbody_json=awaitread_json(request)data={"lang":"Python","async":True,"platform":"asgi","method":method,"path":path,"headers":dict(headers.items()),"body":body_json,}# send json responseawaitrespond_json(request.response,data)Example websocketfromasgikit.requestsimportRequestfromasgikit.errors.websocketimportWebSocketDisconnectErrorasyncdefapp(scope,receive,send):request=Request(scope,receive,send)ws=request.websocketawaitws.accept()whileTrue:try:message=awaitws.receive()awaitws.send(message)exceptWebSocketDisconnectError:print("Client disconnect")break
Package: asgi-lifespan-middleware
asgi-lifespan-middlewareASGI middlewate to support ASGI lifespans using a simple async context manager interface.This middleware accepts an ASGI application to wrap and an async context manager lifespan.
It will run both the lifespan it was handed directly and that of the ASGI app (if the wrapped ASGI app supports lifespans).Example (Starlette)Starlette apps already support lifespans so we'll just be using the TestClient against a plain ASGI app that does nothing.fromcontextlibimportasynccontextmanagerfromtypingimportAsyncIteratorfromstarlette.testclientimportTestClientfromstarlette.typesimportASGIApp,Scope,Send,Receivefromasgi_lifespan_middlewareimportLifespanMiddleware@asynccontextmanagerasyncdeflifespan(# you'll get the wrapped app injectedapp:ASGIApp,)->AsyncIterator[None]:print("setup")yieldprint("teardown")asyncdefapp(scope:Scope,receive:Receive,send:Send)->None:...# do nothingwrapped_app=LifespanMiddleware(app,lifespan=lifespan,)withTestClient(wrapped_app):pass
Package: asgi-log-to-sqlite
asgi-log-to-sqliteASGI middleware for logging traffic to a SQLite databaseSeeLogging to SQLite using ASGI middlewarefor background on this project.Installationpip install asgi-log-to-sqliteUsagefromasgi_log_to_sqliteimportAsgiLogToSqlitefrommy_asgi_appimportappapp=AsgiLogToSqlite(app,"/tmp/log.db")Requests to your ASGI app will now be logged to the SQLite database file at/tmp/log.db.SchemaThe database used to log requests has one key table -requests- and 6 lookup tables:paths,user_agents,referers,accept_languages,content_typesandquery_strings.The full schema is as follows:CREATETABLE[paths]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_paths_nameONpaths(name);CREATETABLE[user_agents]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_user_agents_nameONuser_agents(name);CREATETABLE[referers]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_referers_nameONreferers(name);CREATETABLE[accept_languages]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_accept_languages_nameONaccept_languages(name);CREATETABLE[content_types]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_content_types_nameONcontent_types(name);CREATETABLE[query_strings]([id]INTEGERPRIMARYKEY,[name]TEXT);CREATEUNIQUEINDEXidx_query_strings_nameONquery_strings(name);CREATETABLE[requests]([start]FLOAT,[method]TEXT,[path]INTEGERREFERENCES[paths]([id]),[query_string]INTEGERREFERENCES[query_strings]([id]),[user_agent]INTEGERREFERENCES[user_agents]([id]),[referer]INTEGERREFERENCES[referers]([id]),[accept_language]INTEGERREFERENCES[accept_languages]([id]),[http_status]INTEGER,[content_type]INTEGERREFERENCES[content_types]([id]),[client_ip]TEXT,[duration]FLOAT,[body_size]INTEGER);
Package: asgimqtt
asgimqttis a simpleMQTTinterface forASGI.UsageConnect the server to a runningMQTTbroker:asgimqtt --host localhost --port 1883 django_project.asgi:channel_layerIn your Django code:# routing.py
channels_routing = [
    route("mqtt.sub", mqtt_consumer),
]Note: you can only receive messages published inMQTTbroker (channelmqtt.sub).The keys are:host: host of theMQTTbrokerport: port of theMQTTbrokertopic: topic of theMQTTmessagepayload: payload of theMQTTmessageqos: quality of service of theMQTTmessage (0, 1 or 2)
Package: asgi-prometheus
asgi-prometheus– Support Prometheus metrics for ASGI applications (Asyncio/Trio, /Curio)ContentsRequirementsInstallationUsageOptionsBug trackerContributingLicenseRequirementspython >= 3.7Installationasgi-prometheusshould be installed using pip:pip install asgi-prometheusUsageCommon ASGI applications:fromasgi_prometheusimportPrometheusMiddlewareasyncdefmy_app(scope,receive,send):"""Read session and get the current user data from it or from request query."""awaitsend({"type":"http.response.start","status":status,"headers":headers})awaitsend({"type":"http.response.body","body":b"Hello World!"})app=PrometheusMiddleware(my_app,metrics_url="/metrics",group_paths=['/'])# http GET / -> OK# http GET /metrics -> [Prometheus metrics]AsASGI-ToolsInternal middlewarefromasgi_toolsimportAppfromasgi_prometheusimportPrometheusMiddlewareapp=App()app.middleware(PrometheusMiddleware.setup(group_paths=['/views','/api']))@app.route('/')asyncdefindex(request):return'Hello World!'# http GET / -> OK# http GET /prometheus -> [Prometheus metrics (default URL)]Optionsfromasgi_sessionsimportPrometheusMiddlewareapp=PrometheusMiddleware(# Your ASGI applicationapp,# Metrics URL for Prometheus (set empty string to disable)metrics_url='/prometheus',# List of path's prefixes to group. A path which starts from the prefix will be grouped.# For example: group_paths=['/api/users'], "/api/users/1", "/api/users/2" will be grouped into "/api/users*"group_paths=[],)Bug trackerIf you have any suggestions, bug reports or
annoyances please report them to the issue tracker
athttps://github.com/klen/asgi-prometheus/issuesContributingDevelopment of the project happens at:https://github.com/klen/asgi-prometheusLicenseLicensed under aMIT license.
Package: asgiproxify
AsgiproxifyAsgiproxify is an ASGI middleware for dynamic reverse proxy.InstallationOf course, you can directly install from PyPI.(venv) $ pip install asgiproxifyGetting StartedYou can easily make a running example from these lines:import uvicorn

from asgiproxify import Asgiproxify

proxify = Asgiproxify()
uvicorn.run(proxify)Oh, you have an ASGI server already? You can set a fallback:import uvicorn

from app import app
from asgiproxify import Asgiproxify

proxify = Asgiproxify(app) # or proxify.to(app)
uvicorn.run(proxify)Adding a new reverse proxy endpoint is as simple as:import uvicorn

from asgiproxify import Asgiproxify, AsgiproxifyHandler

proxify = Asgiproxify()


@proxify.register('/example/')
class FooProxyHanlder(AsgiproxifyHandler):
	pass

uvicorn.run(proxify)This will register a handler to handle all requests to/example/*.
By default, an AsgiproxifyHandler will proxy any request to example.org.AsgiproxifyHandler can be smarter than that, like proxy to any URL
you wish, like this:import uvicorn

from asgiproxify import Asgiproxify, AsgiproxifyHandler

proxify = Asgiproxify()


@proxify.register('/LICENSE')
class FooProxyHanlder(AsgiproxifyHandler):
	def make_request_url(self):
		return 'https://www.gnu.org/licenses/gpl-3.0.txt'

uvicorn.run(proxify)You may dynamically make revrese proxy by reading self.scope. Its
content is specified inASGI Specification.A little example for that will be:import uvicorn

from asgiproxify import Asgiproxify, AsgiproxifyHandler

proxify = Asgiproxify()


@proxify.register('/')
class FooProxyHanlder(AsgiproxifyHandler):
	def make_request_url(self):
		return 'https://ftp.gnu.org' + self.scope['path']

uvicorn.run(proxify)You can do more with it by utilizing the scope and other infomation.
The parameters you can tweek from the hander arerequest_url,request_cookies,request_headersandresponse_headers. If that's
not enough for you, you can overridemake_requestwhich will allow
you to create your own aiohttp request!You can consultproxify.pyfor more technical infomation.LicenseThis project is proudly licensed in GNU General Public License v3
or later.Please refer toCOPYINGfor more infomation.
Package: asgi-proxy-lib
asgi-proxy-libAn ASGI function for proxying to a backend over HTTP⚠️ Warning: this is an early alpha.InstallationInstall this library usingpip:pip install asgi-proxy-libUsageThis library provides a single ASGI function calledasgi_proxy. You can use it like this:fromasgi_proxyimportasgi_proxyapp=asgi_proxy("https://datasette.io")Nowappis an ASGI application that will proxy all incoming HTTP requests to the equivalent URL onhttps://datasette.io.The function takes an optional second argument,log=- set this to a Python logger, or any object that has.info(msg)and.error(msg)methods, and the proxy will log information about each request it proxies.CLI toolYou can try this module out like so:python-masgi_proxyhttps://datasette.ioThis will start a server on port 8000 that proxies tohttps://datasette.io.Add-p PORTto specify a different port,--verboseto see debug logging, and--host 127.0.0.1to listen on a different host (the default is0.0.0.0).DevelopmentTo contribute to this library, first checkout the code. Then create a new virtual environment:cd asgi-proxy-lib
python -m venv venv
source venv/bin/activateNow install the dependencies and test dependencies:pip install -e '.[test]'To run the tests:pytest