Choose configuration at runtime#

Import the necessary modules.

import os

from example_httpserver_plugin import LauncherConfig

from ansys.tools.local_product_launcher import launch_product

Default configuration#

First, launch the product without any configuration. This falls back to the default configuration.

product_instance = launch_product(product_name="example_httpserver")
product_instance.urls
{'main': 'localhost:45397'}

To ensure that the server is running, use the wait() method.

product_instance.wait(timeout=5)

Retrieve the content of the server’s main page. This simply serves a list of files in the directory where the server was launched.

import requests

res = requests.get(f"http://{product_instance.urls['main']}")
print(res.content.decode("utf-8"))
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
<li><a href="cli_configure.py">cli_configure.py</a></li>
<li><a href="index.rst">index.rst</a></li>
<li><a href="plugin.rst">plugin.rst</a></li>
<li><a href="py_configure.py">py_configure.py</a></li>
</ul>
<hr>
</body>
</html>

Custom configuration#

Now, try to launch the product with a custom configuration. This is done by passing the config and launch_mode arguments to the launch_product() function.

directory = os.path.join(os.getcwd(), "..")
product_instance = launch_product(
    product_name="example_httpserver",
    config=LauncherConfig(directory=directory),
    launch_mode="direct",
)
product_instance.urls
{'main': 'localhost:44023'}

Again, ensure that the server is running.

product_instance.wait(timeout=5)

Get the content of the main page.

full_url = f"http://{product_instance.urls['main']}"
res = requests.get(full_url)
print(res.content.decode("utf-8"))
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
<li><a href="example_httpserver_plugin/">example_httpserver_plugin/</a></li>
<li><a href="example_scripts/">example_scripts/</a></li>
</ul>
<hr>
</body>
</html>

You can see that the server is now showing the files from the parent directory.

Teardown#

You can manually stop the server using the stop() method. Alternatively, the server is stopped when all references to product_instance are deleted.

product_instance.stop()

To ensure that the server is down, try to access the main page again.

try:
    requests.get(full_url)
except requests.ConnectionError:
    print("The server is down.")
The server is down.

Total running time of the script: (0 minutes 0.347 seconds)

Gallery generated by Sphinx-Gallery