Skip to main content

A bare bone webserver

Project description

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:
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.
@register(route='/', type=MIME_TYPE.HTML)
def main_page():
    return load_file('/content/index.html')
  1. 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.
@post_handler(route='/makethread', type=MIME_TYPE.HTML)
def makethread(args):
    return load_file('/content/post.html')
  1. Redirect: To redirect a request, you can return a Redirect object that specifies the path to which the request should be redirected.
@register(route='/foo', type=MIME_TYPE.HTML)
def redirect():
    return Redirect('/')
  1. 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.
@register(route='/video.mp4', type=MIME_TYPE.MP4)
def vid(args):
    return PartialContent("/content/v.mp4", 80000)
  1. Error handler: With the @error_handler, it is possible to provide default responses for requests with the specified error code.
@error_handler(error_code=404, type=MIME_TYPE.HTML)
def not_found():
    return load_file('/content/404.html')
  1. Handler args: Setting cookies, getting query strings, or setting custom headers are possible when you give your handler function a parameter.
@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:

{
    "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>"
}
  1. Start the server (example of fully functional server): To start the server, invoke the start function.
from bbwebservice.webserver import *

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

start()
  1. With URL-templating you are able to match dynamic URLs like /test/paul/1456379827256
@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:

@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.
@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:

{
    "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.

    "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

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)

Project details


Download files

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

Source Distribution

bbwebservice-1.0.10.tar.gz (23.2 kB view details)

Uploaded Source

Built Distribution

bbwebservice-1.0.10-py3-none-any.whl (23.8 kB view details)

Uploaded Python 3

File details

Details for the file bbwebservice-1.0.10.tar.gz.

File metadata

  • Download URL: bbwebservice-1.0.10.tar.gz
  • Upload date:
  • Size: 23.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.1

File hashes

Hashes for bbwebservice-1.0.10.tar.gz
Algorithm Hash digest
SHA256 30042bf8f982c04c0b8b83c61af0d6099620ef08e5162cf661c4793579d0c39f
MD5 d8f70a8f86c8db3608c54eea9dd9900e
BLAKE2b-256 b36eef7330797e00c658d09a57d5ee05652e098623e87aaf9fe89dde5fa510af

See more details on using hashes here.

File details

Details for the file bbwebservice-1.0.10-py3-none-any.whl.

File metadata

File hashes

Hashes for bbwebservice-1.0.10-py3-none-any.whl
Algorithm Hash digest
SHA256 ded09ee7dee536b06ee252b49bd681081d94fa6ed31f7228dd441b04af250e74
MD5 24f62025b8f9b3e16ae66dddcd80907f
BLAKE2b-256 a0f36f8bd3030826a4adb8f7004f09d0baa7f868ca1f22a93d77a34b37a36cf5

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page