Skip to main content

Turn Flask into a simple RPC server

Project description

Flask-RPC 📣

PyPI version License black

pip install flask-rpc

🚨 Seeking contributions to bring more RPC protocols to Flask-RPC.

Flask - Remote Procedure Call (RPC) is a simple library that allows you to expose functions in your Flask application to be called remotely. It is designed to be straightforward to use and easy to understand.

Flask-RPC currently only uses the weeRPC as its protocol, which is a micro JSON-based protocol that allows for easy communication between the client and server.

This extension is designed to stay slim and provides methods for generating requests and responses.

It does not enforce or validate the data passed in, or the data being sent back; this is left to you to implement in whatever way you feel comfortable (or not at all, if there's no need for it)

Flask-RPC does validate the version of weeRPC on an incoming request. This is to ensure that the request is structured in a way that the version of RPC you are using expects.

Other than that, you are free to use whatever data validation you feel comfortable with. Pydantic and Marshmallow are good choices.

The typical request/response cycle of weeRPC is as follows:

Request

{
  "weerpc": 1.1,
  "function": "add_numbers",
  "data": [
    1,
    2,
    3
  ]
}

Response

{
  "weerpc": 1.1,
  "ok": true,
  "message": "Function 'add_numbers' executed successfully",
  "data": 6
}

Usage

This repo contains a working example of Flask-RPC.

flask --app example run

It also includes an example of using the JS library that helps in making requests via fetch to Flask-RPC.

Simplest example

from flask import Flask

from flask_rpc.latest import RPC, RPCResponse


def add_numbers(data):
    if isinstance(data, list):
        return RPCResponse.success(
            sum(data),
            "Function 'add_numbers' executed successfully"
        )


app = Flask(__name__)
rpc = RPC(app, url_prefix="/rpc")  # or RPC(blueprint)
rpc.functions(
    add_numbers=add_numbers
)

or

...
RPC(
    app,
    url_prefix="/rpc",
    functions={
        "add_numbers": add_numbers
    }
)
...

RPC(...)

Will register a POST route with the app or blueprint that you pass in.

rpc.functions(...)

Will register the functions that you pass in to be called remotely. The argument names used will be the name of the function you will call remotely, for example:

rpc.functions(
    add_numbers=add_numbers,
    subtract=subtract_numbers
)

Calling subtract remotely will call the subtract_numbers function.

A request to the /rpc endpoint with the following JSON payload:

import requests
from flask_rpc import RPCRequest

response = requests.post(
    "http://localhost:5000/rpc",
    json=RPCRequest.build(
        function="add_numbers",
        data=[1, 2, 3]
    )
)

or, if you're using the JS library:

fetch("/rpc", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: wrpc(
        function_ = "add_numbers",
        data = [1, 2, 3]
    )
})

Will return:

{
  "wrpc": 1.0,
  "ok": true,
  "message": "Function 'add_numbers' executed successfully",
  "data": 6
}

Security

You can lock down RPC routes by using sessions and, or host checking.

Global Session Auth

This will check the Flask session for a key value pair, this will apply this check to every function registered.

from flask_rpc.latest import RPCAuthSessionKey
...
RPC(
    app,  # or blueprint
    url_prefix="/rpc",
    session_auth=RPCAuthSessionKey("logged_in", [True]),
    functions={
        "add_numbers": add_numbers
    }
)
...

or a list of RPCAuthSessionKey:

...
RPC(
    app,  # or blueprint
    url_prefix="/rpc",
    session_auth=[
        RPCAuthSessionKey("logged_in", [True]),
        RPCAuthSessionKey("user_type", ["admin"])
    ],
    functions={
        "add_numbers": add_numbers
    }
)
...

Global Host Auth

In the following example, only requests from 127.0.0.1:5000 will be accepted.

This will apply this check to all functions registered.

...
RPC(
    app,  # or blueprint
    url_prefix="/rpc",
    host_auth=["127.0.0.1:5000"],
    functions={
        "add_numbers": add_numbers
    }
)
...

Scoped Session Auth

This will check the Flask session for a key value pair, but only in the specified functions being registered.

from flask_rpc.latest import RPCAuthSessionKey
...
rpc = RPC(
    app,  # or blueprint
    url_prefix="/rpc",
)
rpc.functions(
    session_auth__=RPCAuthSessionKey("logged_in", [True]),
    add_numbers=add_numbers
)
...

Like the example above, you can also pass a list of RPCAuthSessionKey.

...
rpc.functions(
    session_auth__=[
        RPCAuthSessionKey("logged_in", [True]),
        RPCAuthSessionKey("user_type", ["admin"])
    ],
    add_numbers=add_numbers
)
...

Scoped Host Auth

Only requests from 127.0.0.1:5000 will be accepted on the functions specified.

...
rpc = RPC(
    app,  # or blueprint
    url_prefix="/rpc",
)
rpc.functions(
    host_auth=["127.0.0.1:5000"],
    add_numbers=add_numbers
)
...

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_rpc-1.6.2.tar.gz (14.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_rpc-1.6.2-py2.py3-none-any.whl (14.5 kB view details)

Uploaded Python 2Python 3

File details

Details for the file flask_rpc-1.6.2.tar.gz.

File metadata

  • Download URL: flask_rpc-1.6.2.tar.gz
  • Upload date:
  • Size: 14.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for flask_rpc-1.6.2.tar.gz
Algorithm Hash digest
SHA256 c52bf7332a55fe8d6e389cfea2fe55b30a0b593f05a5be7582fc85734ceda780
MD5 353c7c9f594e1f90a54b9fb133e8c9ea
BLAKE2b-256 d952b146b00d9b0b876846a61b18b2ca5cdd8c063fab17b01d6ca0954d46cb39

See more details on using hashes here.

File details

Details for the file flask_rpc-1.6.2-py2.py3-none-any.whl.

File metadata

  • Download URL: flask_rpc-1.6.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 14.5 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for flask_rpc-1.6.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 bd53cd28fd1a761cf11a41712b73ac25d13c18398d7e894d6c6e75509a99b542
MD5 a55b8f8099313b1ec4c28ebb8626c9e7
BLAKE2b-256 342cd18066fc55f6e1fcb05d5ad099d0e178f11e04122f57c21319fd20f8f01a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page