bbwebservice


Namebbwebservice JSON
Version 1.0.10 PyPI version JSON
download
home_pageNone
SummaryA bare bone webserver
upload_time2024-07-24 19:56:55
maintainerNone
docs_urlNone
authorLukas
requires_python>=3.10
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # bbwebservice

`bbwebservice` is a small Python library for creating simple webservers.

## Installation

To install this library, use the pip command: `pip install bbwebservice`

## Usage

- how to import:

```python
from bbwebservice.webserver import * 
```

1. Register pages for HTTP `GET`:
   - `@register`: When using the `@register` decorator, you must define the named parameters `route` and `type`.
     - `route`: The URL which must be requested via HTTP `GET` method for the decorated function to execute. The decorated function is expected to return the respective response content.
     - `type`: The `type` parameter holds the intended MIME-type of the response.

```python
@register(route='/', type=MIME_TYPE.HTML)
def main_page():
    return load_file('/content/index.html')
```

2. Register pages for HTTP `POST`:
   - `@post_handler`: Works similarly to [1.], with the only difference being that it is mandatory for the decorated function to take a parameter.

```python
@post_handler(route='/makethread', type=MIME_TYPE.HTML)
def makethread(args):
    return load_file('/content/post.html')
```

3. Redirect:
  To redirect a request, you can return a `Redirect` object that specifies the path to which the request should be redirected.

```python
@register(route='/foo', type=MIME_TYPE.HTML)
def redirect():
    return Redirect('/')
```

4. PartialContent and videostreaming:
   To serve partial-content for video streaming or other applications, you can return a `PartialContent` object which takes the location of the streamed file and the chunk size which determines the size of the parts that should be streamed.

```python
@register(route='/video.mp4', type=MIME_TYPE.MP4)
def vid(args):
    return PartialContent("/content/v.mp4", 80000)
```

5. Error handler:
   With the `@error_handler`, it is possible to provide default responses for requests with the specified error code.

```python
@error_handler(error_code=404, type=MIME_TYPE.HTML)
def not_found():
    return load_file('/content/404.html')
```

6. Handler args:
   Setting cookies, getting query strings, or setting custom headers are possible when you give your handler function a parameter.

```python
@post_handler(route='/', type=MIME_TYPE.HTML)
def login(args):
    set_cookie(args, 'id', "test")
    return load_file('/content/index.html')
```

The server-supplied `args` value looks something like this, and changes to the provided value will be reflected in the server answer:

```py
{
    "query_string": {},
    "flags": [],
    "template_args": {},
    "cookies": {},
    "address": ("192.168.56.1", 64361),
    "post": bytearray(b""),
    "request_header": {
        "Host": ["192.168.56.1:5000"],
        "Connection": ["keep-alive"],
        "User-agent": ["Mozilla/5.0 (Windows NT 10.0", "Win64", "x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"],
        "Accept": ["text/html,application/xhtml+xml,application/xml", "q=0.9,image/avif,image/webp,image/apng,*/*", "q=0.8,application/signed-exchange", "v=b3", "q=0.7"],
        "Accept-encoding": ["gzip, deflate"],
        "Accept-language": ["de-DE,de", "q=0.9,en-US", "q=0.8,en", "q=0.7"]
    },
    "response": "<bbwebservice.http_parser.HTTP_Response object at 0x00000151D5718E50>"
}
```

7. Start the server (example of fully functional server):
   To start the server, invoke the `start` function.

```python
from bbwebservice.webserver import *

@register(route='/', type=MIME_TYPE.HTML)
def main():
    return load_file('/content/index.html')

start()
```

8. With URL-templating you are able to match dynamic URLs like `/test/paul/1456379827256`

```py
@register(route= UrlTemplate('/test/{name:str}/{id:int}'), type=MIME_TYPE.TEXT)
def test(args):
    return str(args[STORE_VARS.TEMPLATE_VARS])
```

| Supported Types | Example             |
|-----------------|---------------------|
| `str`           | `{varname:str}`     |
| `int`           | `{varname:int}`     |
| `float`         | `{varname:float}`   |
| `bool`          | `{varname:bool}`    |
| `path`          | `{varname:path}`    |

you can combine the `path` type with `load_file_from_directory` like this:
```py
@register(route= UrlTemplate('/path/{path:path}'), type=MIME_TYPE.TEXT)
def load_from_dir(args):
    return load_file_from_directory('C:/myserver/content',args[STORE_VARS.TEMPLATE_VARS].get('path'))
```

1. Register routes for different domains through which the server is accessed when SNI is enabled in the config file.
```py
@register(route=UrlTemplate('domain1.net:{path:path}'), type=MIME_TYPE.TEXT)
def main1(args):
    print("args:",args)
    return 'domain1.net' +" "+ args[STORE_VARS.TEMPLATE_VARS].get('path')

@register(route=UrlTemplate('domain2.net:{path:path}'), type=MIME_TYPE.TEXT)
def main2(args):
    print("args:",args)
    return 'domain2.net' +" "+ args[STORE_VARS.TEMPLATE_VARS].get('path')
```

## Server Configuration

In the directory `/config`, there is a file named `config.json`. Here you can configure the server:

```json
{
    "ip": "localhost",
    "port": 5000,
    "queue_size": 10,
    "SSL": false,
    "cert_path" : "",
    "key_path" : ""
}
```

If you intend to keep the application centrally (online), it is recommended to set the value of `ip` to either `default` or the IP address of the respective server. Additionally, it is advisable to activate `SSL` and set the corresponding paths for `cert_path` and `key_path`. 

```json
    "host": [
        {
            "host": "domain1.net",
            "cert_path" : "...fullchain.pem",
            "key_path" : "...privkey.pem"
        },
        {
            "host": "domain1.net",
            "cert_path" : "...fullchain.pem",
            "key_path" : "...privkey.pem"
        }
    ]
```
`SNI support`:
You can provide the config with a host argument like this to support multible certificates
for different domains. 

### Recommended Ports

- 5000: For testing purposes
- 443: For HTTPS (SSL = true)
- 80: For HTTP (SSL = false)

## Logging

```python
log_to_file()
set_logging(LOGGING_OPTIONS.INFO, True)
set_logging(LOGGING_OPTIONS.TIME, True)
set_logging(LOGGING_OPTIONS.DEBUG, True)
set_logging(LOGGING_OPTIONS.ERROR, True)

def log(log, date, loglvl):
    if loglvl not in ['debug','info']:
        return
    print('[my-log]', log, date)


set_logging_callback(log)
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "bbwebservice",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": "Lukas",
    "author_email": "lukasogwalker@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/b3/6e/ef7330797e00c658d09a57d5ee05652e098623e87aaf9fe89dde5fa510af/bbwebservice-1.0.10.tar.gz",
    "platform": null,
    "description": "# bbwebservice\r\n\r\n`bbwebservice` is a small Python library for creating simple webservers.\r\n\r\n## Installation\r\n\r\nTo install this library, use the pip command: `pip install bbwebservice`\r\n\r\n## Usage\r\n\r\n- how to import:\r\n\r\n```python\r\nfrom bbwebservice.webserver import * \r\n```\r\n\r\n1. Register pages for HTTP `GET`:\r\n   - `@register`: When using the `@register` decorator, you must define the named parameters `route` and `type`.\r\n     - `route`: The URL which must be requested via HTTP `GET` method for the decorated function to execute. The decorated function is expected to return the respective response content.\r\n     - `type`: The `type` parameter holds the intended MIME-type of the response.\r\n\r\n```python\r\n@register(route='/', type=MIME_TYPE.HTML)\r\ndef main_page():\r\n    return load_file('/content/index.html')\r\n```\r\n\r\n2. Register pages for HTTP `POST`:\r\n   - `@post_handler`: Works similarly to [1.], with the only difference being that it is mandatory for the decorated function to take a parameter.\r\n\r\n```python\r\n@post_handler(route='/makethread', type=MIME_TYPE.HTML)\r\ndef makethread(args):\r\n    return load_file('/content/post.html')\r\n```\r\n\r\n3. Redirect:\r\n  To redirect a request, you can return a `Redirect` object that specifies the path to which the request should be redirected.\r\n\r\n```python\r\n@register(route='/foo', type=MIME_TYPE.HTML)\r\ndef redirect():\r\n    return Redirect('/')\r\n```\r\n\r\n4. PartialContent and videostreaming:\r\n   To serve partial-content for video streaming or other applications, you can return a `PartialContent` object which takes the location of the streamed file and the chunk size which determines the size of the parts that should be streamed.\r\n\r\n```python\r\n@register(route='/video.mp4', type=MIME_TYPE.MP4)\r\ndef vid(args):\r\n    return PartialContent(\"/content/v.mp4\", 80000)\r\n```\r\n\r\n5. Error handler:\r\n   With the `@error_handler`, it is possible to provide default responses for requests with the specified error code.\r\n\r\n```python\r\n@error_handler(error_code=404, type=MIME_TYPE.HTML)\r\ndef not_found():\r\n    return load_file('/content/404.html')\r\n```\r\n\r\n6. Handler args:\r\n   Setting cookies, getting query strings, or setting custom headers are possible when you give your handler function a parameter.\r\n\r\n```python\r\n@post_handler(route='/', type=MIME_TYPE.HTML)\r\ndef login(args):\r\n    set_cookie(args, 'id', \"test\")\r\n    return load_file('/content/index.html')\r\n```\r\n\r\nThe server-supplied `args` value looks something like this, and changes to the provided value will be reflected in the server answer:\r\n\r\n```py\r\n{\r\n    \"query_string\": {},\r\n    \"flags\": [],\r\n    \"template_args\": {},\r\n    \"cookies\": {},\r\n    \"address\": (\"192.168.56.1\", 64361),\r\n    \"post\": bytearray(b\"\"),\r\n    \"request_header\": {\r\n        \"Host\": [\"192.168.56.1:5000\"],\r\n        \"Connection\": [\"keep-alive\"],\r\n        \"User-agent\": [\"Mozilla/5.0 (Windows NT 10.0\", \"Win64\", \"x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36\"],\r\n        \"Accept\": [\"text/html,application/xhtml+xml,application/xml\", \"q=0.9,image/avif,image/webp,image/apng,*/*\", \"q=0.8,application/signed-exchange\", \"v=b3\", \"q=0.7\"],\r\n        \"Accept-encoding\": [\"gzip, deflate\"],\r\n        \"Accept-language\": [\"de-DE,de\", \"q=0.9,en-US\", \"q=0.8,en\", \"q=0.7\"]\r\n    },\r\n    \"response\": \"<bbwebservice.http_parser.HTTP_Response object at 0x00000151D5718E50>\"\r\n}\r\n```\r\n\r\n7. Start the server (example of fully functional server):\r\n   To start the server, invoke the `start` function.\r\n\r\n```python\r\nfrom bbwebservice.webserver import *\r\n\r\n@register(route='/', type=MIME_TYPE.HTML)\r\ndef main():\r\n    return load_file('/content/index.html')\r\n\r\nstart()\r\n```\r\n\r\n8. With URL-templating you are able to match dynamic URLs like `/test/paul/1456379827256`\r\n\r\n```py\r\n@register(route= UrlTemplate('/test/{name:str}/{id:int}'), type=MIME_TYPE.TEXT)\r\ndef test(args):\r\n    return str(args[STORE_VARS.TEMPLATE_VARS])\r\n```\r\n\r\n| Supported Types | Example             |\r\n|-----------------|---------------------|\r\n| `str`           | `{varname:str}`     |\r\n| `int`           | `{varname:int}`     |\r\n| `float`         | `{varname:float}`   |\r\n| `bool`          | `{varname:bool}`    |\r\n| `path`          | `{varname:path}`    |\r\n\r\nyou can combine the `path` type with `load_file_from_directory` like this:\r\n```py\r\n@register(route= UrlTemplate('/path/{path:path}'), type=MIME_TYPE.TEXT)\r\ndef load_from_dir(args):\r\n    return load_file_from_directory('C:/myserver/content',args[STORE_VARS.TEMPLATE_VARS].get('path'))\r\n```\r\n\r\n1. Register routes for different domains through which the server is accessed when SNI is enabled in the config file.\r\n```py\r\n@register(route=UrlTemplate('domain1.net:{path:path}'), type=MIME_TYPE.TEXT)\r\ndef main1(args):\r\n    print(\"args:\",args)\r\n    return 'domain1.net' +\" \"+ args[STORE_VARS.TEMPLATE_VARS].get('path')\r\n\r\n@register(route=UrlTemplate('domain2.net:{path:path}'), type=MIME_TYPE.TEXT)\r\ndef main2(args):\r\n    print(\"args:\",args)\r\n    return 'domain2.net' +\" \"+ args[STORE_VARS.TEMPLATE_VARS].get('path')\r\n```\r\n\r\n## Server Configuration\r\n\r\nIn the directory `/config`, there is a file named `config.json`. Here you can configure the server:\r\n\r\n```json\r\n{\r\n    \"ip\": \"localhost\",\r\n    \"port\": 5000,\r\n    \"queue_size\": 10,\r\n    \"SSL\": false,\r\n    \"cert_path\" : \"\",\r\n    \"key_path\" : \"\"\r\n}\r\n```\r\n\r\nIf you intend to keep the application centrally (online), it is recommended to set the value of `ip` to either `default` or the IP address of the respective server. Additionally, it is advisable to activate `SSL` and set the corresponding paths for `cert_path` and `key_path`. \r\n\r\n```json\r\n    \"host\": [\r\n        {\r\n            \"host\": \"domain1.net\",\r\n            \"cert_path\" : \"...fullchain.pem\",\r\n            \"key_path\" : \"...privkey.pem\"\r\n        },\r\n        {\r\n            \"host\": \"domain1.net\",\r\n            \"cert_path\" : \"...fullchain.pem\",\r\n            \"key_path\" : \"...privkey.pem\"\r\n        }\r\n    ]\r\n```\r\n`SNI support`:\r\nYou can provide the config with a host argument like this to support multible certificates\r\nfor different domains. \r\n\r\n### Recommended Ports\r\n\r\n- 5000: For testing purposes\r\n- 443: For HTTPS (SSL = true)\r\n- 80: For HTTP (SSL = false)\r\n\r\n## Logging\r\n\r\n```python\r\nlog_to_file()\r\nset_logging(LOGGING_OPTIONS.INFO, True)\r\nset_logging(LOGGING_OPTIONS.TIME, True)\r\nset_logging(LOGGING_OPTIONS.DEBUG, True)\r\nset_logging(LOGGING_OPTIONS.ERROR, True)\r\n\r\ndef log(log, date, loglvl):\r\n    if loglvl not in ['debug','info']:\r\n        return\r\n    print('[my-log]', log, date)\r\n\r\n\r\nset_logging_callback(log)\r\n```\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A bare bone webserver",
    "version": "1.0.10",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a0f36f8bd3030826a4adb8f7004f09d0baa7f868ca1f22a93d77a34b37a36cf5",
                "md5": "24f62025b8f9b3e16ae66dddcd80907f",
                "sha256": "ded09ee7dee536b06ee252b49bd681081d94fa6ed31f7228dd441b04af250e74"
            },
            "downloads": -1,
            "filename": "bbwebservice-1.0.10-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "24f62025b8f9b3e16ae66dddcd80907f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 23769,
            "upload_time": "2024-07-24T19:56:54",
            "upload_time_iso_8601": "2024-07-24T19:56:54.349911Z",
            "url": "https://files.pythonhosted.org/packages/a0/f3/6f8bd3030826a4adb8f7004f09d0baa7f868ca1f22a93d77a34b37a36cf5/bbwebservice-1.0.10-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b36eef7330797e00c658d09a57d5ee05652e098623e87aaf9fe89dde5fa510af",
                "md5": "d8f70a8f86c8db3608c54eea9dd9900e",
                "sha256": "30042bf8f982c04c0b8b83c61af0d6099620ef08e5162cf661c4793579d0c39f"
            },
            "downloads": -1,
            "filename": "bbwebservice-1.0.10.tar.gz",
            "has_sig": false,
            "md5_digest": "d8f70a8f86c8db3608c54eea9dd9900e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 23158,
            "upload_time": "2024-07-24T19:56:55",
            "upload_time_iso_8601": "2024-07-24T19:56:55.983854Z",
            "url": "https://files.pythonhosted.org/packages/b3/6e/ef7330797e00c658d09a57d5ee05652e098623e87aaf9fe89dde5fa510af/bbwebservice-1.0.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-24 19:56:55",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "bbwebservice"
}
        
Elapsed time: 1.10092s