插件的安装:
pip install Flask-JSONRPC
from flask import Flask
from flask_jsonrpc import JSONRPC
app = Flask("application")
jsonrpc = JSONRPC(app, "/api", enable_web_browsable_api=True)
@jsonrpc.method("App.index")
def index() -> str:
return "Welcome to Flask JSON-RPC"
if __name__ == '__main__':
app.run()
以上为app.py文件中的所有代码.
$ curl -i -X POST \
-H "Content-Type: application/json; indent=4" \
-d '{
"jsonrpc": "2.0",
"method": "App.index",
"params": {},
"id": "1"
}' http://localhost:5000/api
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 77
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Fri, 14 Dec 2012 19:26:56 GMT
{
"jsonrpc": "2.0",
"id": "1",
"result": "Welcome to Flask JSON-RPC"
}
@jsonrpc.method('entity')
def index(product_name:list) -> str:
print(product_name)
return "Welcome to Flask JSON-RPC"
以下的视图函数返回的是列表数据
@jsonrpc.method('entity')
def index(product_name:list) -> list:
print(product_name)
return ["Welcome to Flask JSON-RPC"]
注意点: 1. 在定义有参数的视图函数的时候, 参数的类型必须确定即指定参数类型.
2. 返回值的类型也需要进行指定, 如果返回字符串则指定str, 如果返回列表则指定list.