core
This module is the foundation of Smisk and is implemented in machine native code. See C API for documentation of the C interface.
| Requires | libfcgi |
|---|
Attributes
smisk.core.__build__-
Build identifier in URN form, distinguishing each unique build. See
smisk.release.build.Changed in version 1.1.0: Prior to 1.1.0, this was an arbitrary per-build unique string. In 1.1.0 it is now a URN. smisk.core.app-
Current
Application(Noneif no application has been created). This is actually asmisk.util.objectproxy.ObjectProxy.Application.currentis the most performance-effective way to access the current application.>>> import smisk >>> smisk.app None >>> import smisk.core >>> smisk.core.Application() <smisk.core.Application object at 0x6a5c0> >>> smisk.app <smisk.core.Application object at 0x6a5c0>
New in version 1.1.0. smisk.core.requestCurrent
Request(Noneif no application is running). AnObjectProxy.New in version 1.1.0.smisk.core.responseCurrent
Response(Noneif no application is running). AnObjectProxy.New in version 1.1.0.
Functions
smisk.core.bind(path[, backlog=-1])-
Bind to a specific unix socket or host (and/or port).
Parameters path (string) — Unix domain socket, hostname, or "host:port"
backlog (int) — listen queue depth; negative = let the system decideRaises smisk.IOErrorif already bound;IOErrorif socket creation failsSee unbind(),listening() smisk.core.unbind()Unbind from a previous call to
bind(). If not bound, calling this function has no effect.New in version 1.1.0.smisk.core.listening()-
Find out if this process is bound to a socket via
bind(). Returns the bound address/path, orNoneif not bound.Raises smisk.IOErroron failureReturns Bound path/address or None smisk.core.uid(nbits[, node=None]) → string-
Generate a universally Unique Identifier. The UID is calculated as:
sha1(time.secs, time.usecs, pid, random[, node])Note This is not a UUID (RFC 4122) implementation, but uses a similar algorithm. The output format is more compact than UUID v5. Parameters nbits (int) — bits to pack per byte (4–6), or 0 for 20 raw bytes
node (string) — optional extra data for uid generationNew in version 1.1.0. smisk.core.pack(data[, nbits=5]) → string-
Pack arbitrary bytes into a printable ASCII string. nbits controls encoding density: 0=raw 20B, 4=base16 40B, 5=base32 32B, 6=base64 27B.
See uid()New in version 1.1.0. smisk.core.object_hash(object) → longCalculate a hash from any Python object.
New in version 1.1.0.
Classes
smisk.core.ApplicationAn application. Simple example:
from smisk.core import Application
class MyApp(Application):
def service(self):
self.response.write('<h1>Hello World!</h1>')
MyApp().run()
currentCurrent application instance. Class attribute. See
smisk.core.app.forksNumber of child processes to fork. Set before calling
run(). Defaults to 0.New in version 1.1.0.request_classMust be set before calling
run().response_classMust be set before calling
run().sessions_classMust be set before calling
run(). Should implement thesmisk.session.Storeinterface.requestThe
Requestobject.responseThe
Responseobject.sessionsAn object with the
smisk.session.Storeinterface.show_tracebackIf True, traceback info is included with error responses. Always logged regardless. Defaults to True. Disable in production.
application_did_stop()Called when the application stops accepting requests. Default does nothing.
application_will_start()Called just before the application starts accepting requests. Default does nothing.
error(typ, val, tb)-
Handle an error and produce an appropriate response. The built-in implementation renders XHTML with HTTP 500. You may override this to customise error responses.
Parameters typ — Exception type
val — Exception value
tb — Traceback exit()Exit application.
run()Run application.
service()Service a request. Override in subclasses.
smisk.core.RequestA HTTP request.
inputInput stream (
Stream). Provides raw access to the POST body.envHTTP transaction environment (dict).
urlReconstructed
URL.getQuery string parameters (dict).
postPOST body parameters (dict).
filesUploaded files from POST (dict).
Cookies attached to the request (dict).
sessionCurrent session. Modifications must be done before output has begun (will add a
Set-Cookie:header).session_idCurrent session id (str).
is_activeIndicates if we are in the middle of an HTTP transaction (bool).
referring_urlReferring
URL.New in version 1.1.0.method-
HTTP method ("GET", "POST", etc.).
See RFC 2616, HTTP 1.1, Method Definitions Type str New in version 1.1.1. max_multipart_sizeLimits multipart POST data parsing.
-1disables the limit;0disables automatic parsing. Default: 2 GB.New in version 1.1.2.max_formdata_sizeLimits
x-www-form-urlencodedPOST data.0disables parsing. Cannot be fully disabled (contrast withmax_multipart_size). Default: 10 MB.New in version 1.1.2.log_error(message)Log through
errorstream, including process name and id.
smisk.core.ResponseA HTTP response.
headersResponse headers (list).
outOutput stream (
Stream).has_begunTrue if
begin()has been called and output has started. Read-only (bool).__call__(*strings)Respond with a series of byte strings. Equivalent to
writelines(strings). Callsbegin()if not yet called.send_file(path)Send a file using the host server sendfile-header technique.
begin()Begin response — send headers. Automatically called by
write()andApplication.run().write(str)Write str bytes to
out. Callsbegin()if needed.writelines(lines)Write a sequence of byte strings to the output stream.
find_header(name) → intFind a header by name or prefix (case-insensitive). Returns index in
headersor-1.-
Set a cookie.
Parameters version (int) — Cookie spec version; for RFC 2109, Version=1 applies
max_age (int) — Lifetime in seconds; calculated per the HTTP/1.1 spec; 0 = discard immediately
http_only (bool) — If True, inaccessible to scripts, helping reduce XSS attacks
smisk.core.URLschemeThe URL schema, always lower case (string).
hostHostname (string).
portPort number, 0 if unknown (int).
pathPath component (string).
queryQuery string (string).
fragmentFragment identifier (string).
__init__(obj) → URLParse obj as a URL string, or shallow-copy if obj is already a
URL.to_s(scheme=True, user=True, ...) → strString representation. Pass
Falsefor any component to omit it.static encode(s) → basestringURL-encode unsafe or reserved characters for use in path, query, or fragment.
static escape(s) → basestringEscape unsafe characters for safe rendering in URL contexts.
static decode(s) → basestringRestore data previously encoded by
encode()orescape().static decompose_query(string, charset='utf-8') → dictParse a query string into a dictionary, decoding percent-encoding.
smisk.core.StreamA file-like I/O stream connected to the host server.
smisk.core.SessionStore(object)Basic session store type.
ttlSession validity duration in seconds. Defaults to 900 (int).
nameCookie name for the session id. Defaults to
"SID"(string).
smisk.core.FileSessionStore(SessionStore)File-based session store. See SessionStore.
file_prefixPrepended to each session file. Defaults to
tempfile.tempdir + "smisk-sess."gc_probabilityProbability (0–1) that sessions are garbage-collected on a read. Default 0.1 (10%).
New in version 1.1.0.read(session_id) → dataRaises
InvalidSessionErrorif session not found.write(session_id, data)Write data for session.
destroy(session_id)Delete a session.
Exceptions
exception smisk.core.ErrorBase exception for smisk.core.
exception smisk.core.IOErrorI/O error from the C core.
exception smisk.core.InvalidSessionErrorRaised when a session cannot be found.