cryskura


Namecryskura JSON
Version 1.0b2 PyPI version JSON
download
home_pagehttps://github.com/HofNature/CryskuraHTTP
SummaryA straightforward Python package that functions as an HTTP(s) server
upload_time2024-10-28 11:54:30
maintainerNone
docs_urlNone
authorHofNature
requires_python>=3.7
licenseMIT
keywords http https server web http server https server
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # CryskuraHTTP

<div align="center">
    <img src="https://github.com/HofNature/CryskuraHTTP/raw/main/CryskuraHTTP.png" alt="CryskuraHTTP Logo" width="500">



CryskuraHTTP is a lightweight, customizable HTTP(s) server implemented in Python that supports basic HTTP(s) functionalities, including serving files and handling errors, with support for custom services, API calls, and authentication.

</div>

## Features

CryskuraHTTP is an extension of Python's built-in `http.server`, with minimal dependencies. You can leverage it to implement Python HTTP services without needing to install large software or libraries. It can also be used as a file sharing tool, supporting file serving and uploading through the browser, and can be launched from the Windows right-click menu.

- **Customizable Services**: Easily add custom services by extending the `BaseService` class.
- **Customizable API Calls**: Define custom API calls with the `APIService` class.
- **Error Handling**: Customizable error handling via the `ErrorService` class.
- **File Serving**: Serve files from a specified directory via the `FileService` class.
- **File Uploading**: Handle file uploads via POST requests with the `FileService` class.
- **WebPage Serving**: Serve web pages without allowing directory listing via the `PageService` class.
- **Customizable Routes**: Define custom routes for your services with the `Route` class.
- **Customizable Authentication**: Implement custom authentication for your services.
- **Auto uPnP Port Forwarding**: Automatically forward ports using uPnP.
- **Request Handling**: Handle GET, POST, HEAD requests.
- **Resumable Downloads**: Supports resumable downloads for large files when serving files.
- **Redirects**: Supports 301 and 308 redirects.
- **SSL Support**: Optionally enable SSL by providing a certificate file.
- **Threaded Server**: Supports multi-threaded request handling for better performance.
- **Command-Line Interface**: Run the server from the command line with custom settings.
- **Right Click Support**: Supports right-click context menu for launching the server on Windows.

This project is not designed to replace full-scale, production-grade HTTP servers. Instead, it is ideal for small-scale web UI development or for use alongside tools like `pywebview` and `qtwebengine`. So don't expect it to handle thousands of concurrent connections or to have advanced features like load balancing or caching.

## Requirements

- Python 3.x
- `psutil` library

## Installation

1. Install the package using pip:

    ```sh
    pip install cryskura
    ```

2. You can also download whl file from [GitHub Releases](https://github.com/HofNature/CryskuraHTTP/releases) and install it using pip:

    ```sh
    pip install cryskura-1.0-py3-none-any.wh
    ```

3. Clone the repository and install manually if you want to modify the source code:

    ```sh
    git clone https://github.com/HofNature/CryskuraHTTP.git
    cd CryskuraHTTP
    python setup.py install
    ```

## Quick Start

### Starting the Server

To start the server with default settings:

```python
from cryskura import Server
server = HTTPServer(interface="127.0.0.1", port=8080)
server.start()
```

This will start the server on `localhost` at port `8080` and serve files from the current directory.

Or you can run the server from the command line:

```sh
cryskura --interface 127.0.0.1 --port 8080 --path /path/to/serve
```

This will start the server on `localhost` at port `8080` and serve files from `/path/to/serve`.

### Register to Right-Click Menu

You can add the server to the right-click context menu on Windows by running:

```sh
cryskura --addRightClick # You can also use -ar as a short form
```

> **Note**: If arguments like `--interface`, `--port`, `--browser`, etc., are provided, the server will start with the specified settings when launched from the right-click menu.

If you want to remove it from the right-click menu, run:

```sh
cryskura --removeRightClick # You can also use -rr as a short form
```

> **Note**: This feature is only available on Windows. For Windows 11 24h2 and above, if Sudo is enabled, it will be called automatically; otherwise, you need to run it manually with administrator privileges.

### Stopping the Server

When using the Python API, you can stop the server by calling the `stop()` method:

```python
server.stop()
```

> **Note**: Only the threaded server can be stopped using this method. The non-threaded server will block the thread, so it cannot be stopped by calling the `stop()` method. You can stop the non-threaded server by pressing `Ctrl+C` in the terminal.

When using the command line, you can stop the server by pressing `Ctrl+C` in the terminal.

## Command-Line Interface

You can get help on the command-line interface by running:

```sh
cryskura --help
```

This will show the available options:

- `-h, --help`: Show help message and exit.
- `-u, --uPnP`: Enable uPnP port forwarding.
- `-v, --version`: Show program's version number and exit.
- `-b, --browser`: Open the browser after starting the server.
- `-w, --webMode`: Enable web mode, which means only files can be accessed, not directories.
- `-f, --forcePort`: Force to use the specified port even if it is already in use.
- `-t, --allowUpload`: Allow file upload.
- `-r, --allowResume`: Allow resume download.
- `-ar, --addRightClick`: Add to right-click menu.
- `-rr, --removeRightClick`: Remove from right-click menu.
- `-d PATH, --path PATH`: The path to the directory to serve.
- `-n NAME, --name NAME`: The name of the server.
- `-p PORT, --port PORT`: The port to listen on.
- `-c CERTFILE, --certfile CERTFILE`: The path to the certificate file.
- `-i INTERFACE, --interface INTERFACE`: The interface to listen on.
- `-j HTTP_TO_HTTPS, --http_to_https HTTP_TO_HTTPS`: Port to redirect HTTP requests to HTTPS.

## Using as a Python Module

### Custom Configuration

You can customize the server by providing different parameters:

```python
from cryskura import Server
from cryskura.Services import FileService,PageService,RedirectService,APIService

# Create services
fs=FileService(r"/path/to/file","/Files",allowResume=True,allowUpload=True)
rs=RedirectService("/Redirect","https://www.google.com")
ps=PageService(r"/path/to/html","/")

# Define API function
def APIFunc(request, path, args, method):
    print(f"API {method} {path} {args}")
    request.send_response(200)
    request.send_header("Content-Type", "text/plain")
    request.end_headers()
    request.wfile.write(b"API Call")

# Create API service
api=APIService("/API",func=APIFunc)

# Start the server
server=Server(services=[fs,rs,api,ps],certfile="/path/to/cert.pem",uPnP=True)
server.start()
```

This will start the server with the following services:

- FileService: Serves files from `/path/to/file` at the `/Files` endpoint, allowing resumable downloads and file uploads.
- RedirectService: Redirects requests from `/Redirect` to `https://www.google.com`.
- PageService: Serves web pages from `/path/to/html` at the root endpoint `/`.
- APIService: Handles API calls at the `/API` endpoint, printing request details and responding with a plain text message.

And with the following settings:

- SSL Support: Uses the certificate file located at `/path/to/cert.pem` for SSL encryption.
- uPnP Port Forwarding: Automatically forwards ports using uPnP.

### Route Priority

If multiple services have conflicting routes, the priority is determined by the order in which the services are listed in the `services` parameter. The service listed first will have the highest priority, and so on.

For example:

```python
from cryskura import Server
from cryskura.Services import FileService, PageService

fs = FileService(r"/path/to/files", "/files")
ps = PageService(r"/path/to/pages", "/")

server = Server(services=[fs,ps])
server.start()
```

In this case, `FileService` will have priority over `PageService` for routes that conflict between the two services. So if a request is made to `/files/index.html`, it will be handled by `FileService` and not `PageService`.

### Authentication

To implement custom authentication, you need to define an authentication function and pass it to the service that requires authentication. The authentication function should accept four parameters: `cookies`, `path`, `args`, and `operation`. It should return `True` if the authentication is successful, and `False` otherwise.

Here is an example of how to implement custom authentication:

```python
from cryskura import Server
from cryskura.Services import FileService

# Define authentication function
def AUTHFunc(cookies, path, args, operation):
    print(f"AUTH {operation} {path} {args}")
    if args.get('passwd') == "passwd" and operation == "GET":
        return True
    elif args.get('passwd') == "admin" and operation == "POST":
        return True
    return False

# Create a file service with authentication
fs = FileService(r"/path/to/files", "/files", allowResume=True, auth_func=AUTHFunc)

# Start the server
server = Server(services=[fs])
server.start()
```

In this example, the `AUTHFunc` function checks the `passwd` parameter in the request arguments to authenticate GET and POST requests. If the `passwd` parameter is `passwd` for GET requests or `admin` for POST requests, the authentication is successful. Otherwise, the authentication fails.  

You can customize the `AUTHFunc` function to implement your own authentication logic, such as checking cookies, headers, or other request parameters.

### Custom Services

To create a custom service, extend the `BaseService` class and implement the required methods:

```python
from cryskura.Services import BaseService, Route

class MyService(BaseService):
    def __init__(self):
        routes = [Route("/myservice", ["GET"], "exact")]
        super().__init__(routes)

    def handle_GET(self, request, path, args):
        request.send_response(200)
        request.send_header("Content-Type", "text/plain")
        request.end_headers()
        request.wfile.write(b"Hello from MyService!")
```

## Using the uPnP Client

CryskuraHTTP includes a built-in uPnP client to facilitate automatic port forwarding. This can be particularly useful when running the server behind a router or firewall.

### Enabling uPnP

To enable uPnP port forwarding, you can use the `--uPnP` flag when starting the server from the command line:

```sh
cryskura --interface 0.0.0.0 --port 8080 --path /path/to/serve --uPnP
```

### Using uPnP in Python

You can also enable uPnP port forwarding when starting the server using the Python API:

```python
from cryskura import Server

server = Server(interface="0.0.0.0", port=8080, uPnP=True)
server.start()
```

###  Custom uPnP Configuration

The built-in uPnP client can be used independently for custom port forwarding needs. Here’s how you can use the `uPnPClient` class directly in your Python code:

#### Initializing the uPnP Client

First, you need to initialize the `uPnPClient` with the desired network interface:

```python
from cryskura import uPnP

# Initialize uPnP client for a specific interface
upnp_client = uPnP(interface="0.0.0.0")
# Use 0.0.0.0 for all IPv4 interfaces

if upnp_client.available:
    print("uPnP client initialized successfully.")
else:
    print("uPnP client is not available.")
```

#### Adding a Port Mapping

To add a port mapping, use the `add_port_mapping` method:

```python
if upnp_client.available:
    success, mappings = upnp_client.add_port_mapping(
        remote_port=8080, 
        local_port=8080, 
        protocol="TCP", 
        description="CryskuraHTTP Server"
    )
    if success:
        print("Port mapping added successfully.")
        for mapping in mappings:
            print(f"Service is available at {mapping[0]}:{mapping[1]}")
    else:
        print("Failed to add port mapping.")
```

This will add a port mapping for port `8080` on the remote device to port `8080` on the local device using the TCP protocol. The description is just a label for the mapping, which can be used to identify it later.

#### Removing All Port Mappings

To remove port mappings, use the `remove_port_mapping` method:

```python
if upnp_client.available:
    upnp_client.remove_port_mapping()
    print("Port mapping removed.")
```

This will remove all port mappings that were added by the client. It's a good practice to remove port mappings when they are no longer needed. You can place this code in a cleanup section of your script or in an exception handler to ensure that the mappings are removed even if an error occurs. For example:

```python
try:
    Your code here...
except Exception as exception:
    upnp_client.remove_port_mapping()
    raise exception
```

This will ensure that the port mappings are removed even if an exception occurs during the execution of your code.

### Troubleshooting uPnP

If you encounter issues with uPnP, ensure that:

- Your router **supports** uPnP and has it **enabled**.
- The `upnpclient` library is installed. You can install it using:

    ```sh
    pip install upnpclient
    ```

    or install the `cryskura` package with the `upnp` extra:

    ```sh
    pip install cryskura[upnp]
    ```

- The network interface specified is correct and accessible.

For more detailed information on the `uPnPClient` class and its methods, refer to the source code in the `uPnP.py` file.

## License

This project is licensed under the MIT License. See the [LICENSE](https://github.com/HofNature/CryskuraHTTP/blob/main/LICENSE) file for details.

## Contributing

Contributions are welcome! Please open an issue or submit a pull request.

## Contact

For any questions or suggestions, please open an issue here on [GitHub](https://github.com/HofNature/CryskuraHTTP/issues).

---

Enjoy using CryskuraHTTP!

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/HofNature/CryskuraHTTP",
    "name": "cryskura",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "http, https, server, web, http server, https server",
    "author": "HofNature",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/f3/08/e814ebc08ba435e77761020f64a6166e4021592f432e6609c0f41c72760d/cryskura-1.0b2.tar.gz",
    "platform": null,
    "description": "# CryskuraHTTP\r\n\r\n<div align=\"center\">\r\n    <img src=\"https://github.com/HofNature/CryskuraHTTP/raw/main/CryskuraHTTP.png\" alt=\"CryskuraHTTP Logo\" width=\"500\">\r\n\r\n\r\n\r\nCryskuraHTTP is a lightweight, customizable HTTP(s) server implemented in Python that supports basic HTTP(s) functionalities, including serving files and handling errors, with support for custom services, API calls, and authentication.\r\n\r\n</div>\r\n\r\n## Features\r\n\r\nCryskuraHTTP is an extension of Python's built-in `http.server`, with minimal dependencies. You can leverage it to implement Python HTTP services without needing to install large software or libraries. It can also be used as a file sharing tool, supporting file serving and uploading through the browser, and can be launched from the Windows right-click menu.\r\n\r\n- **Customizable Services**: Easily add custom services by extending the `BaseService` class.\r\n- **Customizable API Calls**: Define custom API calls with the `APIService` class.\r\n- **Error Handling**: Customizable error handling via the `ErrorService` class.\r\n- **File Serving**: Serve files from a specified directory via the `FileService` class.\r\n- **File Uploading**: Handle file uploads via POST requests with the `FileService` class.\r\n- **WebPage Serving**: Serve web pages without allowing directory listing via the `PageService` class.\r\n- **Customizable Routes**: Define custom routes for your services with the `Route` class.\r\n- **Customizable Authentication**: Implement custom authentication for your services.\r\n- **Auto uPnP Port Forwarding**: Automatically forward ports using uPnP.\r\n- **Request Handling**: Handle GET, POST, HEAD requests.\r\n- **Resumable Downloads**: Supports resumable downloads for large files when serving files.\r\n- **Redirects**: Supports 301 and 308 redirects.\r\n- **SSL Support**: Optionally enable SSL by providing a certificate file.\r\n- **Threaded Server**: Supports multi-threaded request handling for better performance.\r\n- **Command-Line Interface**: Run the server from the command line with custom settings.\r\n- **Right Click Support**: Supports right-click context menu for launching the server on Windows.\r\n\r\nThis project is not designed to replace full-scale, production-grade HTTP servers. Instead, it is ideal for small-scale web UI development or for use alongside tools like `pywebview` and `qtwebengine`. So don't expect it to handle thousands of concurrent connections or to have advanced features like load balancing or caching.\r\n\r\n## Requirements\r\n\r\n- Python 3.x\r\n- `psutil` library\r\n\r\n## Installation\r\n\r\n1. Install the package using pip:\r\n\r\n    ```sh\r\n    pip install cryskura\r\n    ```\r\n\r\n2. You can also download whl file from [GitHub Releases](https://github.com/HofNature/CryskuraHTTP/releases) and install it using pip:\r\n\r\n    ```sh\r\n    pip install cryskura-1.0-py3-none-any.wh\r\n    ```\r\n\r\n3. Clone the repository and install manually if you want to modify the source code:\r\n\r\n    ```sh\r\n    git clone https://github.com/HofNature/CryskuraHTTP.git\r\n    cd CryskuraHTTP\r\n    python setup.py install\r\n    ```\r\n\r\n## Quick Start\r\n\r\n### Starting the Server\r\n\r\nTo start the server with default settings:\r\n\r\n```python\r\nfrom cryskura import Server\r\nserver = HTTPServer(interface=\"127.0.0.1\", port=8080)\r\nserver.start()\r\n```\r\n\r\nThis will start the server on `localhost` at port `8080` and serve files from the current directory.\r\n\r\nOr you can run the server from the command line:\r\n\r\n```sh\r\ncryskura --interface 127.0.0.1 --port 8080 --path /path/to/serve\r\n```\r\n\r\nThis will start the server on `localhost` at port `8080` and serve files from `/path/to/serve`.\r\n\r\n### Register to Right-Click Menu\r\n\r\nYou can add the server to the right-click context menu on Windows by running:\r\n\r\n```sh\r\ncryskura --addRightClick # You can also use -ar as a short form\r\n```\r\n\r\n> **Note**: If arguments like `--interface`, `--port`, `--browser`, etc., are provided, the server will start with the specified settings when launched from the right-click menu.\r\n\r\nIf you want to remove it from the right-click menu, run:\r\n\r\n```sh\r\ncryskura --removeRightClick # You can also use -rr as a short form\r\n```\r\n\r\n> **Note**: This feature is only available on Windows. For Windows 11 24h2 and above, if Sudo is enabled, it will be called automatically; otherwise, you need to run it manually with administrator privileges.\r\n\r\n### Stopping the Server\r\n\r\nWhen using the Python API, you can stop the server by calling the `stop()` method:\r\n\r\n```python\r\nserver.stop()\r\n```\r\n\r\n> **Note**: Only the threaded server can be stopped using this method. The non-threaded server will block the thread, so it cannot be stopped by calling the `stop()` method. You can stop the non-threaded server by pressing `Ctrl+C` in the terminal.\r\n\r\nWhen using the command line, you can stop the server by pressing `Ctrl+C` in the terminal.\r\n\r\n## Command-Line Interface\r\n\r\nYou can get help on the command-line interface by running:\r\n\r\n```sh\r\ncryskura --help\r\n```\r\n\r\nThis will show the available options:\r\n\r\n- `-h, --help`: Show help message and exit.\r\n- `-u, --uPnP`: Enable uPnP port forwarding.\r\n- `-v, --version`: Show program's version number and exit.\r\n- `-b, --browser`: Open the browser after starting the server.\r\n- `-w, --webMode`: Enable web mode, which means only files can be accessed, not directories.\r\n- `-f, --forcePort`: Force to use the specified port even if it is already in use.\r\n- `-t, --allowUpload`: Allow file upload.\r\n- `-r, --allowResume`: Allow resume download.\r\n- `-ar, --addRightClick`: Add to right-click menu.\r\n- `-rr, --removeRightClick`: Remove from right-click menu.\r\n- `-d PATH, --path PATH`: The path to the directory to serve.\r\n- `-n NAME, --name NAME`: The name of the server.\r\n- `-p PORT, --port PORT`: The port to listen on.\r\n- `-c CERTFILE, --certfile CERTFILE`: The path to the certificate file.\r\n- `-i INTERFACE, --interface INTERFACE`: The interface to listen on.\r\n- `-j HTTP_TO_HTTPS, --http_to_https HTTP_TO_HTTPS`: Port to redirect HTTP requests to HTTPS.\r\n\r\n## Using as a Python Module\r\n\r\n### Custom Configuration\r\n\r\nYou can customize the server by providing different parameters:\r\n\r\n```python\r\nfrom cryskura import Server\r\nfrom cryskura.Services import FileService,PageService,RedirectService,APIService\r\n\r\n# Create services\r\nfs=FileService(r\"/path/to/file\",\"/Files\",allowResume=True,allowUpload=True)\r\nrs=RedirectService(\"/Redirect\",\"https://www.google.com\")\r\nps=PageService(r\"/path/to/html\",\"/\")\r\n\r\n# Define API function\r\ndef APIFunc(request, path, args, method):\r\n    print(f\"API {method} {path} {args}\")\r\n    request.send_response(200)\r\n    request.send_header(\"Content-Type\", \"text/plain\")\r\n    request.end_headers()\r\n    request.wfile.write(b\"API Call\")\r\n\r\n# Create API service\r\napi=APIService(\"/API\",func=APIFunc)\r\n\r\n# Start the server\r\nserver=Server(services=[fs,rs,api,ps],certfile=\"/path/to/cert.pem\",uPnP=True)\r\nserver.start()\r\n```\r\n\r\nThis will start the server with the following services:\r\n\r\n- FileService: Serves files from `/path/to/file` at the `/Files` endpoint, allowing resumable downloads and file uploads.\r\n- RedirectService: Redirects requests from `/Redirect` to `https://www.google.com`.\r\n- PageService: Serves web pages from `/path/to/html` at the root endpoint `/`.\r\n- APIService: Handles API calls at the `/API` endpoint, printing request details and responding with a plain text message.\r\n\r\nAnd with the following settings:\r\n\r\n- SSL Support: Uses the certificate file located at `/path/to/cert.pem` for SSL encryption.\r\n- uPnP Port Forwarding: Automatically forwards ports using uPnP.\r\n\r\n### Route Priority\r\n\r\nIf multiple services have conflicting routes, the priority is determined by the order in which the services are listed in the `services` parameter. The service listed first will have the highest priority, and so on.\r\n\r\nFor example:\r\n\r\n```python\r\nfrom cryskura import Server\r\nfrom cryskura.Services import FileService, PageService\r\n\r\nfs = FileService(r\"/path/to/files\", \"/files\")\r\nps = PageService(r\"/path/to/pages\", \"/\")\r\n\r\nserver = Server(services=[fs,ps])\r\nserver.start()\r\n```\r\n\r\nIn this case, `FileService` will have priority over `PageService` for routes that conflict between the two services. So if a request is made to `/files/index.html`, it will be handled by `FileService` and not `PageService`.\r\n\r\n### Authentication\r\n\r\nTo implement custom authentication, you need to define an authentication function and pass it to the service that requires authentication. The authentication function should accept four parameters: `cookies`, `path`, `args`, and `operation`. It should return `True` if the authentication is successful, and `False` otherwise.\r\n\r\nHere is an example of how to implement custom authentication:\r\n\r\n```python\r\nfrom cryskura import Server\r\nfrom cryskura.Services import FileService\r\n\r\n# Define authentication function\r\ndef AUTHFunc(cookies, path, args, operation):\r\n    print(f\"AUTH {operation} {path} {args}\")\r\n    if args.get('passwd') == \"passwd\" and operation == \"GET\":\r\n        return True\r\n    elif args.get('passwd') == \"admin\" and operation == \"POST\":\r\n        return True\r\n    return False\r\n\r\n# Create a file service with authentication\r\nfs = FileService(r\"/path/to/files\", \"/files\", allowResume=True, auth_func=AUTHFunc)\r\n\r\n# Start the server\r\nserver = Server(services=[fs])\r\nserver.start()\r\n```\r\n\r\nIn this example, the `AUTHFunc` function checks the `passwd` parameter in the request arguments to authenticate GET and POST requests. If the `passwd` parameter is `passwd` for GET requests or `admin` for POST requests, the authentication is successful. Otherwise, the authentication fails.  \r\n\r\nYou can customize the `AUTHFunc` function to implement your own authentication logic, such as checking cookies, headers, or other request parameters.\r\n\r\n### Custom Services\r\n\r\nTo create a custom service, extend the `BaseService` class and implement the required methods:\r\n\r\n```python\r\nfrom cryskura.Services import BaseService, Route\r\n\r\nclass MyService(BaseService):\r\n    def __init__(self):\r\n        routes = [Route(\"/myservice\", [\"GET\"], \"exact\")]\r\n        super().__init__(routes)\r\n\r\n    def handle_GET(self, request, path, args):\r\n        request.send_response(200)\r\n        request.send_header(\"Content-Type\", \"text/plain\")\r\n        request.end_headers()\r\n        request.wfile.write(b\"Hello from MyService!\")\r\n```\r\n\r\n## Using the uPnP Client\r\n\r\nCryskuraHTTP includes a built-in uPnP client to facilitate automatic port forwarding. This can be particularly useful when running the server behind a router or firewall.\r\n\r\n### Enabling uPnP\r\n\r\nTo enable uPnP port forwarding, you can use the `--uPnP` flag when starting the server from the command line:\r\n\r\n```sh\r\ncryskura --interface 0.0.0.0 --port 8080 --path /path/to/serve --uPnP\r\n```\r\n\r\n### Using uPnP in Python\r\n\r\nYou can also enable uPnP port forwarding when starting the server using the Python API:\r\n\r\n```python\r\nfrom cryskura import Server\r\n\r\nserver = Server(interface=\"0.0.0.0\", port=8080, uPnP=True)\r\nserver.start()\r\n```\r\n\r\n###  Custom uPnP Configuration\r\n\r\nThe built-in uPnP client can be used independently for custom port forwarding needs. Here\u2019s how you can use the `uPnPClient` class directly in your Python code:\r\n\r\n#### Initializing the uPnP Client\r\n\r\nFirst, you need to initialize the `uPnPClient` with the desired network interface:\r\n\r\n```python\r\nfrom cryskura import uPnP\r\n\r\n# Initialize uPnP client for a specific interface\r\nupnp_client = uPnP(interface=\"0.0.0.0\")\r\n# Use 0.0.0.0 for all IPv4 interfaces\r\n\r\nif upnp_client.available:\r\n    print(\"uPnP client initialized successfully.\")\r\nelse:\r\n    print(\"uPnP client is not available.\")\r\n```\r\n\r\n#### Adding a Port Mapping\r\n\r\nTo add a port mapping, use the `add_port_mapping` method:\r\n\r\n```python\r\nif upnp_client.available:\r\n    success, mappings = upnp_client.add_port_mapping(\r\n        remote_port=8080, \r\n        local_port=8080, \r\n        protocol=\"TCP\", \r\n        description=\"CryskuraHTTP Server\"\r\n    )\r\n    if success:\r\n        print(\"Port mapping added successfully.\")\r\n        for mapping in mappings:\r\n            print(f\"Service is available at {mapping[0]}:{mapping[1]}\")\r\n    else:\r\n        print(\"Failed to add port mapping.\")\r\n```\r\n\r\nThis will add a port mapping for port `8080` on the remote device to port `8080` on the local device using the TCP protocol. The description is just a label for the mapping, which can be used to identify it later.\r\n\r\n#### Removing All Port Mappings\r\n\r\nTo remove port mappings, use the `remove_port_mapping` method:\r\n\r\n```python\r\nif upnp_client.available:\r\n    upnp_client.remove_port_mapping()\r\n    print(\"Port mapping removed.\")\r\n```\r\n\r\nThis will remove all port mappings that were added by the client. It's a good practice to remove port mappings when they are no longer needed. You can place this code in a cleanup section of your script or in an exception handler to ensure that the mappings are removed even if an error occurs. For example:\r\n\r\n```python\r\ntry:\r\n    Your code here...\r\nexcept Exception as exception:\r\n    upnp_client.remove_port_mapping()\r\n    raise exception\r\n```\r\n\r\nThis will ensure that the port mappings are removed even if an exception occurs during the execution of your code.\r\n\r\n### Troubleshooting uPnP\r\n\r\nIf you encounter issues with uPnP, ensure that:\r\n\r\n- Your router **supports** uPnP and has it **enabled**.\r\n- The `upnpclient` library is installed. You can install it using:\r\n\r\n    ```sh\r\n    pip install upnpclient\r\n    ```\r\n\r\n    or install the `cryskura` package with the `upnp` extra:\r\n\r\n    ```sh\r\n    pip install cryskura[upnp]\r\n    ```\r\n\r\n- The network interface specified is correct and accessible.\r\n\r\nFor more detailed information on the `uPnPClient` class and its methods, refer to the source code in the `uPnP.py` file.\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License. See the [LICENSE](https://github.com/HofNature/CryskuraHTTP/blob/main/LICENSE) file for details.\r\n\r\n## Contributing\r\n\r\nContributions are welcome! Please open an issue or submit a pull request.\r\n\r\n## Contact\r\n\r\nFor any questions or suggestions, please open an issue here on [GitHub](https://github.com/HofNature/CryskuraHTTP/issues).\r\n\r\n---\r\n\r\nEnjoy using CryskuraHTTP!\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A straightforward Python package that functions as an HTTP(s) server",
    "version": "1.0b2",
    "project_urls": {
        "Homepage": "https://github.com/HofNature/CryskuraHTTP"
    },
    "split_keywords": [
        "http",
        " https",
        " server",
        " web",
        " http server",
        " https server"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "37773e91b897d58543e5cfa86f13ace63134b502e5ac8bcc2dbdea6c465fd5be",
                "md5": "c3c2f91f842a0f1e4295a298c2b550b3",
                "sha256": "e8c40bce8422c12a005d297f1f8e7f59394905a8485ccd521a8535a08f8d8b2d"
            },
            "downloads": -1,
            "filename": "cryskura-1.0b2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c3c2f91f842a0f1e4295a298c2b550b3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 162071,
            "upload_time": "2024-10-28T11:54:28",
            "upload_time_iso_8601": "2024-10-28T11:54:28.133445Z",
            "url": "https://files.pythonhosted.org/packages/37/77/3e91b897d58543e5cfa86f13ace63134b502e5ac8bcc2dbdea6c465fd5be/cryskura-1.0b2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f308e814ebc08ba435e77761020f64a6166e4021592f432e6609c0f41c72760d",
                "md5": "81a626c6d4c823d0aaf859e1ece302e6",
                "sha256": "dac167f4bd91e24a2007642fddb6b0d70098dee8e89d9223e7b5a5cd3464d673"
            },
            "downloads": -1,
            "filename": "cryskura-1.0b2.tar.gz",
            "has_sig": false,
            "md5_digest": "81a626c6d4c823d0aaf859e1ece302e6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 163096,
            "upload_time": "2024-10-28T11:54:30",
            "upload_time_iso_8601": "2024-10-28T11:54:30.141295Z",
            "url": "https://files.pythonhosted.org/packages/f3/08/e814ebc08ba435e77761020f64a6166e4021592f432e6609c0f41c72760d/cryskura-1.0b2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-28 11:54:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "HofNature",
    "github_project": "CryskuraHTTP",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "cryskura"
}
        
Elapsed time: 0.38906s