Package: ngrok
Python SDK for ngrokngrok-pythonis the official Python SDK for ngrok that requires no binaries. Quickly enable secure production-ready connectivity to your applications and services directly from your code.ngrokis a globally distributed gateway that provides secure connectivity for applications and services running in any environment.InstallationThengrok-pythonSDK can be installed fromPyPIviapip:pipinstallngrokQuickstartInstallngrok-pythonExport yourauthtoken from the ngrok dashboardasNGROK_AUTHTOKENin your terminalAdd the following code to your application to establish connectivity via theforward methodthrough port9000onlocalhost:# import ngrok python sdkimportngrok# Establish connectivitylistener=ngrok.forward(9000,authtoken_from_env=True)# Output ngrok url to consoleprint(f"Ingress established at{listener.url()}")That's it! Your application should now be available through the url output in your terminal.NoteYou can find more examples inthe examples directory.DocumentationA full quickstart guide and API reference can be found in thengrok-python documentation.AuthenticationTo use most of ngrok's features, you'll need an authtoken. To obtain one, sign up for free atngrok.comand retrieve it from theauthtoken page in your ngrok dashboard. Once you have copied your authtoken, you can reference it in several ways.You can set it in theNGROK_AUTHTOKENenvironment variable and passauthtoken_from_env=Trueto theforwardmethod:ngrok.forward(authtoken_from_env=True,...)Or pass the authtoken directly to theforwardmethod:ngrok.forward(authtoken=token,...)Or set it for all connections with theset_auth_tokenmethod:ngrok.set_auth_token(token)ConnectionTheforwardmethod is the easiest way to start an ngrok session and establish a listener to a specified address. If an asynchronous runtime is running, theforwardmethod returns a promise that resolves to the public listener object.With no arguments, theforwardmethod will start an HTTP listener tolocalhostport80:listener=ngrok.forward()You can pass the port number to forward onlocalhost:listener=ngrok.forward(4242)Or you can specify the host and port via a string:listener=ngrok.forward("localhost:4242")More options can be passed to theforwardmethod to customize the connection:listener=ngrok.forward(8080,basic_auth="ngrok:online1line"})listener=ngrok.forward(8080,oauth_provider="google",oauth_allow_domains="example.com")The second (optional) argument is the listener type, which defaults tohttp. To create a TCP listener:listener=ngrok.forward(25565,"tcp")Since the options are kwargs, you can also use the**operator to pass a dictionary for configuration:options={"authtoken_from_env":True,"response_header_add":"X-Awesome:yes"}listener=ngrok.forward(8080,**options)SeeFull Configurationfor the list of possible configuration options.DisconnectionTo close a listener use thedisconnectmethod with theurlof the listener to close. If there is an asynchronous runtime running thedisconnectmethod returns a promise that resolves when the call is complete.ngrok.disconnect(url)Or omit theurlto close all listeners:ngrok.disconnect()Theclosemethod on a listener will shut it down, and also stop the ngrok session if it is no longer needed. This method returns a promise that resolves when the listener is closed.awaitlistener.close()List all ListenersTo list all current non-closed listeners use theget_listenersmethod. If there is an asynchronous runtime running theget_listenersmethod returns a promise that resolves to the list of listener objects.listeners=ngrok.get_listeners()TLS BackendsAs of version0.10.0there is backend TLS connection support, validated by a filepath specified in theSSL_CERT_FILEenvironment variable, or falling back to the host OS installed trusted certificate authorities. So it is now possible to do this to connect:ngrok.forward("https://127.0.0.1:3000",authtoken_from_env=True)If the service is using certs not trusted by the OS, such as self-signed certificates, add an environment variable like this before running:SSL_CERT_FILE=/path/to/ca.crt.Unix SocketsYou may also choose to use Unix Sockets instead of TCP. You can view an example of thishere.A socket address may be passed directly into the listenerforward()call as well by prefixing the address withunix:, for exampleunix:/tmp/socket-123.BuildersFor more control over Sessions and Listeners, the builder classes can be used.A minimal example using the builder class looks likethe following:asyncdefcreate_listener():session=awaitngrok.NgrokSessionBuilder().authtoken_from_env().connect()listener=awaitsession.http_endpoint().listen()print(f"Ingress established at{listener.url()}")listener.forward("localhost:9000")See here for aFull Configuration ExampleFull ConfigurationThis example showsall the possible configuration items of ngrok.forward:listener=ngrok.forward(# session configurationaddr="localhost:8080",authtoken="<authtoken>",authtoken_from_env=True,session_metadata="Online in One Line",# listener configurationmetadata="example listener metadata from python",domain="<domain>",schemes=["HTTPS"],proto="http",proxy_proto="",# One of: "", "1", "2"labels="edge:edghts_2G...",# Along with proto="labeled"# module configurationbasic_auth=["ngrok:online1line"],circuit_breaker=0.1,compression=True,allow_user_agent="^mozilla.*",deny_user_agent="^curl.*",allow_cidr="0.0.0.0/0",deny_cidr="10.1.1.1/32",crt=load_file("crt.pem"),key=load_file("key.pem"),mutual_tls_cas=load_file("ca.crt"),oauth_provider="google",oauth_allow_domains=["<domain>"],oauth_allow_emails=["<email>"],oauth_scopes=["<scope>"],oauth_client_id="<id>",oauth_client_secret="<id>",oidc_issuer_url="<url>",oidc_client_id="<id>",oidc_client_secret="<secret>",oidc_allow_domains=["<domain>"],oidc_allow_emails=["<email>"],oidc_scopes=["<scope>"],policy="<policy_json>",request_header_remove="X-Req-Nope",response_header_remove="X-Res-Nope",request_header_add="X-Req-Yup:true",response_header_add="X-Res-Yup:true",verify_webhook_provider="twilio",verify_webhook_secret="asdf",websocket_tcp_converter=True,)ASGI Runnerngrok-pythoncomes bundled with an ASGI (Asynchronous Server Gateway Interface) runnerngrok-asgithat can be used for Uvicorn, Gunicorn, Django and more, with no code.To use prefix your start up command for a Uvicorn or Gunicorn web server with eitherngrok-asgiorpython -m ngrok.Any TCP or Unix Domain Socket arguments will be used to establish connectivity automatically. The ngrok listener can be configured using command flags, for instance adding--basic-auth ngrok online1linewill introduce basic authentication to the ingress listener.Uvicorn# Basic Usagengrok-asgiuvicornmysite.asgi:application# With custom host and portngrok-asgiuvicornmysite.asgi:application\--hostlocalhost\--port1234# Using basic authngrok-asgiuvicornmysite.asgi:application\--hostlocalhost\--port1234\--basic-authngrokonline1line# Using custom sock filengrok-asgiuvicornmysite.asgi:application\--uds/tmp/uvicorn.sock# Using module namepython-mngrokuvicornmysite.asgi:application\--oauth-providergoogle\--allow-emailsbob@example.comGunicorn# Basic Usagengrok-asgigunicornmysite.asgi:application-kuvicorn.workers.UvicornWorker# With custom host and portngrok-asgigunicornmysite.asgi:application-kuvicorn.workers.UvicornWorker\--bindlocalhost:1234# Using webhook verificationsngrok-asgigunicornmysite.asgi:application-kuvicorn.workers.UvicornWorker\--webhook-verificationtwilios3cr3t# Using custom sock filengrok-asgigunicornmysite.asgi:application-kuvicorn.workers.UvicornWorker\--bindunix:/tmp/gunicorn.sock# Using module namepython-mngrokgunicornmysite.asgi:application-kuvicorn.workers.UvicornWorker--response-headerX-AwesomeTrueExamplesListenersHTTPFull Configuration ExampleLabeledTCPTLSFrameworksAIOHTTPAWS APP Runnerwithchanges for PythonDjangoSingle File ExampleModify manage.py ExampleModify asgi.py Exampleorviangrok-asgiFlaskGunicornStreamlitTornadoUvicornMachine LearningGradiongrok-asgi Examplegradio CLI ExampleOpenPlaygroundGPT4ALLStable Diffusion WebUIby AUTOMATIC1111ngrok-pythonis now built-in, see the--ngrokand--ngrok-optionsarguments.Text Generation WebUIby oobaboogangrok-pythonis now built-in, see the--extension ngrokargument.Platform SupportPre-built binaries are provided on PyPI for the following platforms:OSi686x64aarch64armWindows✓✓*MacOS✓✓Linux✓✓✓Linux musl✓✓FreeBSD*Notengrok-python, andngrok-rustwhich it depends on, are open source, so it may be possible to build them for other platforms.Windows-aarch64 will be supported after the next release ofRing.FreeBSD-x64 is built by the release process, but PyPI won't accept BSD flavors.DependenciesThis project relies onPyO3, an excellent system to ease development and building of Rust plugins for Python.Thank you toOpenIoTHubfor handing over the ngrok name on PyPI.ChangelogChanges tongrok-pythonare tracked underCHANGELOG.md.Join the ngrok CommunityCheck outour official docsRead about updates onour blogOpen anissueorpull requestJoin ourSlack communityFollow us onX / Twitter (@ngrokHQ)Subscribe to ourYoutube channel (@ngrokHQ)LicenseThis project is dual-licensed underApache, Version 2.0andMIT.
You can choose between one of them if you use this work.ContributionsUnless you explicitly state otherwise, any contribution intentionally submitted
for inclusion inngrok-pythonby you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.Development: Getting StartedPrerequisites:a valid Ngrokauthtokenmakeavailable in your PATHUpdateCargo.tomlwith thelatest supportedngrok = { version = "=VERSION_HERE" }fromngrok-rust.ngrok-rustis used for the bindings insrc/rust_files_here.rsRunmake build(builds therustbindings /pythondependencies)Happy developing!Example Commands:building the projectmakedeveloprunning the entire test suite# running the entire test suiteexportNGROK_AUTHTOKEN="YOUR_AUTHTOKEN_HERE";maketestrunning an individual test# running an individual testexportNGROK_AUTHTOKEN="YOUR_AUTHTOKEN_HERE";maketest="-k TEST_CLASS.NAME_OF_TEST"testSee the MakeFile for more examples