What is the correct syntax for using KV in Python?

Is there a specific syntax for using KV in Python?

The following code will fail to wrangler publish

def handleRequest(request):
	PYTEST.put("test", "test")

    return __new__(Response('OK', {'status' : 200, 'headers' : { 'content-type' : 'text/plain' }}))

addEventListener('fetch', (lambda event: event.respondWith(handleRequest(event.request))))

And yes, PYTEST is added as a kv_namespace in my wrangler.toml

Here is the error:

[email protected] ~/pythontest # wrangler publish
Error compiling /root/pythontest/index.py:
Transcrypt (TM) Python to JavaScript Small Sane Subset Transpiler Version 3.7.16
Copyright (C) Geatec Engineering. License: Apache 2.0


Parsing module: /root/pythontest/index.py

Error while compiling (offending file last):
        File 'index', line 4, namely:

         [<-SYNTAX FAULT] return __new__(Response('OK', {'status' : 200, 'headers' : { 'content-type' : 'text/plain' }}))

Aborted


 ./index.py
Module build failed (from ./node_modules/transcrypt-loader/__target_es5__/index.js):
Error: Command failed: python3 -m transcrypt --nomin --map --verbose "index"
    at checkExecSyncError (child_process.js:629:11)
    at Object.execSync (child_process.js:666:13)
    at Object.main (/root/pythontest/node_modules/transcrypt-loader/__target_es5__/index.js:56:67)
Error: webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config.

for a KV namespace named KV, the following python

def handleRequest(request):
    return KV.put('blah', 'blah').then(
        lambda _: __new__(Response('Python Worker hello world!', {'headers' : { 'content-type' : 'text/plain' }})))

will compile to the following JavaScript (visible in __target__/index.js):

export var handleRequest = function (request) {
        return KV.put ('blah', 'blah').then ((function __lambda__ (_) {
                return new Response ('Python Worker hello world!', dict ({'headers': dict ({'content-type': 'text/plain'})}));
        }));
};
1 Like

The only way I’m able to generate the syntax fault you’re seeing is by adding unequal whitespace indentation before the return statement in your example.

Without static checking, Transcrypt doesn’t know anything about what methods or objects are available in the javascript api, and will happily compile almost anything you throw at it, e.g.

def handleRequest(request):
    SomeThingThatDoesntExist.blah.put("test", "test")

will result in the javascript

export var handleRequest = function (request) {
        SomeThingThatDoesntExist.blah.put ('test', 'test');

which will fail at runtime, not at compile time

2 Likes