Skip to main content

SMDB Web Server

An easy to use, not secured web server, because I don't like the other options, and I like to create my own solutions most of the time.

Table of content

Section Name
Usage
Get handler
Put Handler
Post Handler
Data

Usage

To start using this HTTP Server, import the HTMLServer class, and initialize it.

from smdb_web_server import HTMLServer, UrlData
server = HTMLServer("127.0.0.1", 8080, title="Example server")

If the plaintext or JSON responses will use any specific encodings you can set the response_charset property when creating the HTMLServer. The default value is 'UTF-8'.

IP restrictions can be enforced by a function passed in to address_filter. For example, a local IP restriction could look like the following:

from smdb_web_server import HTMLServer, UrlData

def restrict_ip_to_lan(ip: str) -> bool:
    return '.'.join(ip.split('.')[:-1]) == '192.168.0'

server = HTMLServer("127.0.0.1", 8080, title="Example server", address_filter=restrict_ip_to_lan)

disable_cache can be set to true to prevent the user's browser from caching the data sent.

An smdb_logger can be used, if desired, but not necessary.

To add a new url path, use the add_url_rule command.

def index_handler(url_data: UrlData) -> str:
    ...

server.add_url_rule("/", index_handler)

This method will be called with a GET request by default. This can be set as an optional parameter called protocol. For now, only GET and PUT are supported.

Url handlers can be assigned with a decorator as well:

@server.as_url_rule("/help")
def help_handler(url_data: UrlData) -> str:
    ...

To start the server, use either the serve_forever or the serve_forever_threaded function. The first will be a blocking call, the second will create a new thread.

server.serve_forever_threaded(template_dictionary, static_dictionary)

Both handlers can fail with KnownError exception, which will result in a user controlled return code and reason.

To disable caching for one page, set the "disable_cache" flag to true when creating the handler:

@server.as_url_rule("/help", disable_cache=True)
def help_handler(url_data: UrlData) -> str:
    ...

This will send the no_cache flag in the header of the message. To do this with the whole application, set the same flag to true, when instantiating the server.

GET handler

This handler can return any string, but it's useful, if it returns an HTML file as string. This can be a hardcoded HTML code, or a static or dynamic file. For rendering HTML template files, the server has a helper function called render_template_file. This can render an HTML file from a pre setup dictionary.

def index_handler(url_data: UrlData) -> str:
    example_list = ["value1", "value2|False", "value3|True"]
    return server.render_template("index", page_title="Example Title", example_selector=example_list, button_1="Button 1 name", button_2="Button 2 name")

If you need to just create a list to update an already rendered HTML page's selector, you can use it the following way:

def update(url_data: UrlData) -> str:
    return server.render_template_list("example_selector", ["value1|True", "value2|False", "value3|False"])

server.add_url_rule("/update", update)

This will result in the following list, if we use the option tag as shown in the template_dictionary in the data paragraph:

<option disabled></option>
<option value="value1" selected>value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>

This list will be sent as a plaintext response.

Put Handler

This handler can return a simple string. The incoming data will be a bytearray of the body of the request.

from smdb_web_server import Protocol

def put_handler(url_data: UrlData) -> str:
    # Do stuff here.
    # Either return with string, or fail with KnownError
    ...

server.add_url_rule("/put", put_handler, Protocol.Put)

Post Handler

This handler can return a simple string. The incoming data will be a bytearray of the body of the request.

rom smdb_web_server import Protocol

def post_handler(url_data: UrlData) -> str:
    # Do stuff here.
    # Either return with string, or fail with KnownError
    ...

server.add_url_rule("/post", post_handler, Protocol.Post)

Data

Template dictionary

  • Keys: The "file name" without extension
  • Value: The file's content, or a path in the following format: "PATH|{Relative path to file}"

This dictionary will be used to generate HTML response from the template. These templates can have replaceable values with the following format.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ page_title }}</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <div class="container">
        <h2>Example Header</h2>
        <div class="grid-container">
                <label for="ExampleSelector">Example Selector:</label>
                <select id="ExampleSelector" class="fixed-width">
                    {{[ example_selector ]}}
                </select>
            <div class="button-group">
                <button id="ExampleButton1">{{ button_1 }}</button>
                <button id="ExampleButton2">{{ button_2 }}</button>
            </div>
        </div>
    </div>
    <script src="/static/script.js"></script>
</body>
</html>

In this page the {{ page_title }}, the {{ button_1 }} and the {{ button_2 }} will be replaced with one value, and the {{[ ExampleSelector ]}} will be generated using a list.

This dictionary should contain a key-value pair with the value being a repeatable value to fill the {{[ ExampleSelector ]}} place.

selector_values = """<option value="{{VALUE}}"{{SELECTED}}>{{VALUE}}</option>"""

Here, the {{VALUE}} will be replaced by the list's content, and the {{SELECTED}} will be replaced by either the value selected or with an empty string, if the list's value is formatted in the following manner: {value}|True. If the value following the | character is not "True", it will be treated as if it was not present.

You can return a list by calling the render_template_list function by itself, or by rendering a full HTML page by calling render_template, with a list as an argument.

Static dictionary

  • Keys: The "file name" without extension
  • Value: Either the file's content, or a path in the following format: "PATH|{Relative path to file}"

Static files will be sent automatically, if the correct URL is called. In the Template Dictionary example, the JavaScript and the CSS files are loaded from the path /static/{file_name}. This will result in the {file_name} file being served from the dictionary.

KnownError

This error is used to send a user controlled response code to the requester. This exception can be used the following way:

from smdb_web_server import KnownError
def fail(_):
    raise KnownError("Reason", 405)

Protocol

This is a simple enum class to use with add_url_rule to determine the protocol to be used

Values: Get, Put, Post

UrlData

This dataclass contains the following fields, either filled or containing None:

  • fragment: String object (Data following the # in the URL)
  • query: Dictionary with string keys and values (Data following the ? in the URL). The key will be the part following the ? or & characters, and the value will be the part after the = sign. If there is no value, None will be used as a value in the dictionary.
  • data: Bytes object (Payload of the request, if available)
  • source: String object (source adders of the request)
  • headers: Dictionary with string keys and values (The request's headers)

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smdb_web_server-2.0.1.tar.gz (15.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smdb_web_server-2.0.1-py3-none-any.whl (15.5 kB view details)

Uploaded Python 3

File details

Details for the file smdb_web_server-2.0.1.tar.gz.

File metadata

  • Download URL: smdb_web_server-2.0.1.tar.gz
  • Upload date:
  • Size: 15.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.7

File hashes

Hashes for smdb_web_server-2.0.1.tar.gz
Algorithm Hash digest
SHA256 faaacf17b6fb8f6ea0d6106c50170b3a906ec30df6c5eeba57eaf1858d95a065
MD5 0e12429549a44a64fbdce8323ec4a15a
BLAKE2b-256 cde9755ba44853e504099e1bb8380a2e6dc0b94b4ea89479810abbfa48788f41

See more details on using hashes here.

File details

Details for the file smdb_web_server-2.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for smdb_web_server-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 088212e324292df99a3e3a53531ae279e0409e8516e4ca92a5f971fec99576a0
MD5 0074917a9ba0d2d96fc0e0a36934e335
BLAKE2b-256 4f37e40cdc6a64b7a5e74affe222d18e86c28c7c284da6d43d90b51cfed74574

See more details on using hashes here.

Release history Release notifications | RSS feed

2.0.2

2 files

This release

2.0.1 This release

2 files

2.0.0

2 files

1.1.4

2 files

1.1.3

2 files

1.1.2

2 files

1.1.1

2 files

1.1.0

2 files

1.0.2

2 files

1.0.1

2 files

1.0.0

2 files

0.6.5

2 files

0.6.4

2 files

0.6.3

2 files

0.6.2

2 files

0.6.1

2 files

0.6.0

2 files

0.5.6

2 files

0.5.5

2 files

0.5.4

2 files

0.5.3

2 files

0.5.2

2 files

0.5.1

2 files

0.5.0

2 files

0.4.3

2 files

0.4.2

2 files

0.4.1

2 files

0.4.0

2 files

0.3.6

2 files

0.3.5

2 files

0.3.4

2 files

0.3.3

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.0

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page