Python

This page contains a reference of all exported Kore functions to Python.

Kore must be compiled with PYTHON=1 for this to work. Python 3.6 or higher should be used.


Pulling in Python files

You can import Python files into your Kore application using the python_import configuration option:

python_import ./src/hello.py

Intro

Before you write any Python code you must import the kore module:

import kore

Note that the Python code is expected to run inside of the Kore worker process, the kore module being imported is not available outside of this worker process.

Shortcuts

Kore

Constants

The kore module exports some constants that can be used by the Python code.

  • LOG_INFO
  • LOG_NOTICE
  • RESULT_OK
  • RESULT_RETRY
  • RESULT_ERROR
  • MODULE_LOAD
  • MODULE_UNLOAD
  • CONN_PROTO_HTTP
  • CONN_PROTO_UNKNOWN
  • CONN_PROTO_WEBSOCKET
  • CONN_STATE_ESTABLISHED

Functions


log

Synopsis

kore.log(priority, string)

Description

Logs the given string to syslog.

Parameter Description
priority Log level priority (kore.LOG_ constants).
string The string to be sent to syslog.

Returns

Nothing

Example

kore.log(kore.LOG_INFO, 'this is a log string from a worker process')

fatal

Synopsis

kore.fatal(reason)

Description

Terminates the worker process with the given reason as the error message.

Parameter Description
reason String containing the reason why the worker is terminating.

Returns

Nothing

Example

kore.fatal('worker going dead')

websocket_broadcast

Synopsis

kore.websocket_broadcast(src, op, data, scope)

Description

Broadcasts a websocket message to all other connected websocket clients.

Parameter Description
src The source kore.connection object.
op The websocket op type.
data The data to be broadcasted.
scope Whether or not this is broadcasted to all workers or just this one.

Returns

Nothing

Example

def onmessage(c, op, data):
    kore.websocket_broadcast(c, op, data, kore.WEBSOCKET_BROADCAST_GLOBAL)

register_database

Synopsis

kore.register_database(name, connstring)

Description

Associates a pgsql connection string with a shortname for a database that can be used later in pgsql.

Parameter Description
name The friendly name for the database.
connstring The pgsql connection string.

Returns

Nothing

Example

kore.register_database("db", "host=/tmp dbname=hello")

HTTP

Like the C API Kore will pass an http_request data structure to your Python page handler. This data structure is of type kore.http_request.

Constants

  • HTTP_METHOD_GET
  • HTTP_METHOD_PUT
  • HTTP_METHOD_HEAD
  • HTTP_METHOD_POST
  • HTTP_METHOD_DELETE
  • HTTP_METHOD_OPTIONS
  • HTTP_METHOD_PATCH

Getters

  • host - The domain as a unicode string.
  • agent - The user agent as a unicode string.
  • path - The requested path as a unicode string.
  • body - The entire incoming HTTP body as a PyBuffer.
  • method - The requested method as a PyLong. (kore.HTTP_METHOD_GET, etc).
  • body_path - The path to the HTTP body on disk (if enabled).
  • connection - The underlying client connection as a kore.connection object.

Functions


pgsql

Synopsis

result = await req.pgsql(db, query)

Description

Performs an asynchronous PostgreSQL query.

Parameter Description
db A previously configured database name.
query The query to be performed.

Returns

The result of the query as a dictionary.

Example

async def myquery(req):
    result = await req.pgsql("db", "SELECT * FROM pg_delay(10)")
    req.response(200, json.dumps(result).encode("utf-8"))

cookie

Synopsis

cookie = req.cookie(name)

Description

Returns the cookie value for a given name.

Parameter Description
name The name of the cookie to lookup.

Returns

Returns the value of the cookie as a unicode string or None if not found.

Example

def handler(req):
    cookie = req.cookie("my_session")
    if cookie != None:
        # use cookie value to do things.

response

Synopsis

req.response(status, body)

Description

Creates an HTTP response for the given HTTP request.

Parameter Description
status The HTTP status code to include in the response.
body The HTTP body to be included in the response, this must be a binary buffer.

Returns

Nothing

Example

def handler(req):
    req.response(200, b'ok')

argument

Synopsis

value = req.argument(name)

Description

Looks up an HTTP parameter that was previously validated via a Kore params block in the configuration.

Parameter Description
name The name of the parameter to lookup.

Returns

The parameter as a unicode string or None if it was not found.

Example

def handler(req):
    id = req.argument("id")
    if id != None:
        # got an id from somewhere

body_read

Synopsis

length, chunk = req.body_read(length)

Description

Reads up to length bytes from the HTTP body and returns the actual bytes read and data in a tuple.

A returned length of 0 bytes indicates the end of the HTTP body.

Parameter Description
length The number of bytes to read.

Returns

The length and data read.

Example

def handler(req):
    if req.method == kore.HTTP_METHOD_POST:
        try
            length, body = req.body_read(1024)
            # do stuff with the body.
        except:
            kore.log(kore.LOG_INFO, "some error occurred")
            req.response(500, b'')

file_lookup

Synopsis

file = req.file_lookup(name)

Description

Lookup an uploaded file (via multipart/form-data).

Parameter Description
name The name of the file that was uploaded.

Returns

A kore.http_file object that can be used to read data from.

Example

def handler(req):
    if req.method == kore.HTTP_METHOD_POST:
        req.populate_multi()
        try
            file = req.file_lookup("myfile")
            length, data = file.read(1024)
            # do stuff with the data .
        except:
            kore.log(kore.LOG_INFO, "some error occurred")
            req.response(500, b'')

populate_get

Synopsis

req.populate_get()

Description

Instructs Kore to go ahead and parse the incoming querystring and validate parameters according to the configured params {} blocks in the configuration.

Returns

Nothing


populate_post

Synopsis

req.populate_post()

Description

Instructs Kore to go ahead and parse the incoming POST data which is of content-type application/x-www-form-urlencoded and validate parameters according to the configured params {} blocks in the configuration.

Returns

Nothing


populate_multipart

Synopsis

req.populate_multipart()

Description

Instructs Kore to go ahead and parse the incoming body as content-type multipart/form-data and validate parameters according to the configured params {} blocks in the configuration.

Returns

Nothing


populate_cookies

Synopsis

req.populate_cookies()

Description

Instructs Kore to go ahead and parse the incoming cookie header (if any).

Returns

Nothing


request_header

Synopsis

value = req.request_header(name)

Description

Finds the incoming request header by name and returns it.

Parameter Description
name The name of the header to lookup.

Returns

The value of the header as a unicode string or None if the header was not present.

Example

def myhandler(req):
    xrequest = req.request_header("x-request")
    if xrequest != None:
        req.response_header("x-response", xrequest)

    req.response(200, b'hello world)

response_header

Synopsis

req.response_header(name, value)

Description

Adds the given header to the response that will be sent by req.response().

Parameter Description
name The name of the header that will be added.
value The value of the header that will be added.

Returns

Nothing

Example

def myhandler(req):
    xrequest = req.request_header("x-request")
    if xrequest != None:
        req.response_header("x-response", xrequest)

    req.response(200, b'hello world)

websocket_handshake

Synopsis

req.websocket_handshake(onconnect, onmsg, ondisconnect)

Description

Adds the given header to the response that will be sent by req.response().

Parameter Description
onconnect The name of the function to be called when a new websocket client is connected.
onmsg The name of the function to be called when a websocket message arrives.
ondisconnect The name of the function to be called when a new websocket client is removed.

Returns

Nothing

Example

def onconnect(c):
    kore.log(kore.LOG_INFO, "%s: connected" % c)

def onmessage(c, op, data):
    # data from c arrived
    # op is the websocket op, WEBSOCKET_OP_TEXT, WEBSOCKET_OP_BINARY
    # data is the data that arrived

def ondisconnect(c):
    kore.log(kore.LOG_INFO, "%s: disconnected" % c)

def ws_connect(req):
    req.websocket_handshake("onconnect", "onmsg", "ondisconnect")

results matching ""

    No results matching ""