cjohnson318
cjohnson318

Reputation: 3253

How to return JSON in Flask server built with Haxe

I'm trying to build a Flask server using Haxe, and I'm stumped on how to return a JSON. I got an example up and running using this gist that has Main.index() return a String, but when I try to return a String from haxe.Json.stringify() I get an error when I try to run the output Python.

import haxe.Constraints.Function;

@:pythonImport("flask", "Flask")
extern class Flask {
    function new(module:String);
    function route<T:Function>(path:String):T->T;
    function run():Void;
}

class Main {
    static function main() {
        var app = new Flask(untyped __name__);
        app.route("/")(index);
        app.run();
    }

    static function index() {
        return haxe.Json.stringify({msg:"hello"});
    }
}

Python error:

$ python main.py
  File "main.py", line 69
    return haxe_format_JsonPrinter.print(_hx_AnonObject({'msg': "hello"}),None,None)
                                       ^
SyntaxError: invalid syntax

Upvotes: 3

Views: 195

Answers (1)

Jason O&#39;Neil
Jason O&#39;Neil

Reputation: 6008

It doesn't seem to be well documented but Haxe's python target only supports Python 3. See https://github.com/HaxeFoundation/haxe/issues/4195

In this case, "print" was a keyword in Python 2, and the Haxe generated code is trying to generate a function named "print", hence the error.

Try:

python3 main.py

to have it run correctly.

Upvotes: 2

Related Questions