Created
April 23, 2021 06:47
-
-
Save thomaxxl/f8cff63a80979b4a4da70fd835ec2b99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
SAFRS example calling a postgres TVF. | |
Suppose the database has this function defined: | |
--- | |
CREATE FUNCTION public.f_2(v1 integer, OUT v2 integer, OUT v3 integer) RETURNS record | |
LANGUAGE plpgsql | |
AS $$ | |
BEGIN | |
v2 := v1; | |
v3 := v1 + 1; | |
END | |
$$; | |
--- | |
In psql this returns: | |
test=# SELECT * FROM f_2(1) AS t1; | |
v2 | v3 | |
----+---- | |
1 | 2 | |
(1 row) | |
We expose this function through /MyService/f2_rpc | |
Then call invoke the function with | |
$ curl -X POST "http://localhost:5000/MyService/f2_rpc" -H "accept: application/vnd.api+json" -H "Content-Type: application/json" -d "{ \"arg\": 0}" | |
{ | |
"result": [ | |
0, | |
1 | |
] | |
} | |
""" | |
import sys | |
from flask import Flask | |
from flask_sqlalchemy import SQLAlchemy | |
from safrs import SAFRSAPI, jsonapi_rpc | |
from safrs import JABase, DB | |
db = SQLAlchemy() | |
class MyService(JABase): | |
""" | |
description: Example class without SQLa Model | |
""" | |
@staticmethod | |
@jsonapi_rpc(http_methods=["POST"], valid_jsonapi=False) | |
def f2_rpc(arg): | |
""" | |
description: rpc example | |
args: | |
arg : 0 | |
""" | |
sql_query = db.text("SELECT * FROM f_2(:arg)") | |
query_result = db.engine.execute(sql_query, arg=arg) | |
result = query_result.fetchall() | |
return {"result" : list(result[0])} | |
HOST = sys.argv[1] if len(sys.argv) > 1 else "0.0.0.0" | |
PORT = 5000 | |
app = Flask("SAFRS Demo Application") | |
app.config.update(SQLALCHEMY_DATABASE_URI="postgresql://test:test@localhost/test", DEBUG=True) | |
if __name__ == "__main__": | |
db.init_app(app) | |
db.app = app | |
API_PREFIX = "" | |
with app.app_context(): | |
api = SAFRSAPI(app, host="{}".format(HOST), port=PORT, prefix=API_PREFIX) | |
# Expose the database objects as REST API endpoints | |
api.expose_object(MyService) | |
# Register the API at /api/docs | |
print("Starting API: http://{}:{}{}".format(HOST, PORT, API_PREFIX)) | |
app.run(host=HOST, port=PORT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment