响应程序Web框架的基类。

responder-base-classes的Python项目详细描述


响应程序基类:用于Responder (kennethreitz)

Build StatusimageUpdatesimageimageimage

基本思想

主要的概念是用json和Responder's class based views

为restapi提供基类。
  • 使用类似于Flask's extensions
  • 的扩展扩展扩展响应程序
  • 响应程序执行on_request方法,后跟on_{method},其中method是http动词。
    • 将语法扩展到execute_on_requestexecute_on_{method}
    • 期望您实现或重载execute_on_requestexecute_on_{method}(视情况而定)。
  • 提供了两个基类:OpenBaseViewAuthBaseView
  • OpenBaseView不需要授权,但需要检查内容类型和实现的路由
  • AuthBaseView使用基本身份验证和自定义身份验证扩展了OpenBaseView,并具有用于实现以下内容的占位符函数:
    • 一个get_user函数,用于检查后端的常规授权
    • 每个路由的特定授权的valid_credentials_for_route函数

示例用法

import responder

from responder_base_classes.open_base_service import OpenBaseView
from responder_base_classes.auth_base_service import AuthBaseView

api = responder.API()

@api.route("/OpenBaseView")
class ObjectView(OpenBaseView):
    """An endpoint for Objects"""

    @staticmethod
    async def execute_on_get(req, resp):
        resp.media = {
            "status": "success",
            "reason": "executed on_get completely",
            "object": 42,
        }
        resp.status_code = 200  # OK

    @staticmethod
    async def execute_on_head(req, resp):
        resp.status_code = 200  # OK

    @staticmethod
    async def execute_on_post(req, resp):
        resp.media = {
            "status": "success",
            "reason": "executed on_post completely",
            "object": 42,
        }
        resp.status_code = 200  # OK

    @staticmethod
        async def execute_on_request(req, resp):
            resp.headers["X-Pizza"] = "42"

@api.route("/AuthBaseView")
class AuthObjectView(AuthBaseView):
    """An endpoint for Objects
    """

    @classmethod
    def valid_credentials_for_route(cls, req, user):
        """
        Validate credentials for route
        This should be overridden for each method
        :param req: Mutable request object
        :param user: User object
        :return:
        """
        # check password
        if user is not None:
            # something along the lines of checking if session includes 'username'
            # then checking if the username has the privileges for the request dict
            return True  # this defaults to allowed if user exists
        return False

    def get_user(cls, req):
        """
        Get User Class Object, facilitates checking credentials
        :param req: Mutable request object
        :return:
        """
        # you should implement for your application, below is just for testing
        class User(object):
            def __init__(self, username, password):
                self.username = username
                self.password = password
        user = User(username="test_user", password="test_password")
        return user

    @staticmethod
    async def execute_on_post(req, resp):
        resp.media = {
            "status": "success",
            "reason": "executed on_post completely",
            "object": 42,
        }
        resp.status_code = 200  # OK

headers = {"Content-Type": "application/json"}
r = api.requests.get("/OpenBaseView", headers=headers)
print(r.json())
{'status': 'success', 'reason': 'executed on_get completely', 'object': 42}

print(r.headers[X-Pizza'])
42

# Demo of AuthBaseView
import base64@staticmethod
        async def execute_on_request(req, resp):
            resp.headers["X-Pizza"] = "42"

# credentials that match placeholder in AuthObjectView.get_user
encoded_credentials = base64.b64encode(b"test_user:test_password")
encoded_header = "Basic {}".format(encoded_credentials.decode("utf-8"))

headers = {"Content-Type": "application/json", "authorization": encoded_header}
r = api.requests.patch("/AuthBaseView", headers=headers)

print(r.json())
{'status': 'failure', 'reason': 'execute_on_patch not implemented for this URL path'}
# note, we didn't implement execute_on_patch, we implemented execute_on_post

r = api.requests.post("/AuthBaseView", headers=headers)

print(r.json())
{'status': 'success', 'reason': 'executed on_post completely', 'object': 42}

# credentials that do not match placeholder in AuthObjectView.get_user
encoded_credentials = base64.b64encode(b"non_existent_user:bad_password")
encoded_header = "Basic {}".format(encoded_credentials.decode("utf-8"))

headers = {"Content-Type": "application/json", "authorization": encoded_header}

r = api.requests.get("/AuthBaseView", headers=headers)
print(r.json())
{'status': 'failure', 'reason': 'In on_get function: exiting before running execute_on_get_request; Invalid credentials for this request, password is wrong'}

# please note that this example's get_user defines a user,
# so it is indicating that the password doesn't match the defined user
# generally, this would indicate the 'non_existent_user' doesn't exist
# in thase case, print(r.json()) would return the following:
# {'status': 'failure', 'reason': 'In on_get function: exiting before running execute_on_get_request; Invalid credentials for this request, user doesn't exist"'}

安装响应程序基类

安装最新版本:

$ pip install responder-base-classes

只支持python 3.6+as required by the Responder package

待办事项

请参阅TODO关于可能的下一个功能/更改!


贡献指南

Contributing Guide欢迎!

谢谢你,我希望你觉得我/我们的工作有用!祝您愉快:)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java SimpleFramework和工厂方法   Java适当地处理异常   java单例类不起作用   java小程序和Swing在eclipse中不显示组件   多个键上的java Redisson FastRemove不起作用   java验证请求正文不等于模式   在Java中从URL读取数据   eche RecyclerView项的java Set自定义字体   string Java如何从Date获取HH:mm:ss   当Java应用程序落后于负载均衡器时,在某些URL上强制使用SSL   使用esapi时发生java错误   java使用流根据第二个列表中的值更新一个列表中的对象   组织。openqa。硒。Java中的NoTouchElementException WebDriver?   从JSON字符串Java创建CSV文件