首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个Starlette代码只适用于GET,我需要POST

这个Starlette代码只适用于GET,我需要POST
EN

Stack Overflow用户
提问于 2022-08-11 03:27:13
回答 1查看 88关注 0票数 0

我能够从一个示例Starlette示例中构建一段代码,获取基本的Auth用户名和密码,读取头部,并获取json主体。但是只有当我使用"GET“而不是post的时候,它才会这么做,而且我还无法想出如何将已接受的方法更改为POST。(我试图托管的应用程序只使用POST。让POST方法工作是一件简单的事情,还是一次重写?

代码语言:javascript
复制
    from starlette.applications import Starlette
    from starlette.authentication import requires
    from starlette.authentication import (
        AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
    )
    from starlette.middleware import Middleware
    from starlette.middleware.authentication import AuthenticationMiddleware
    from starlette.responses import (PlainTextResponse, JSONResponse)
    from starlette.routing import Route
    import base64
    import binascii
    
    class BasicAuthBackend(AuthenticationBackend):
        async def authenticate(self, conn):
            if "Authorization" not in conn.headers:
                return
    
            auth = conn.headers["Authorization"]
            try:
                scheme, credentials = auth.split()
                if scheme.lower() != 'basic':
                    return
                decoded = base64.b64decode(credentials).decode("ascii")
            except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
                raise AuthenticationError('Invalid basic auth credentials')
            username, _, password = decoded.partition(":")
            global my_user
            global my_pass
            my_user = username
            my_pass = password
            # TODO: You'd want to verify the username and password here.
            return AuthCredentials(["authenticated"]), SimpleUser(username)
    
    
    async def homepage(request):
        if request.user.is_authenticated:
            body = await request.json()
            return JSONResponse({"user": my_user, "password": my_pass, "header": request.headers['client_id']}, body )
             
        return PlainTextResponse('Hello, you')
    
    routes = [
        Route("/testpath", endpoint=homepage)
    ]

middleware = [
    Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())
]

app = Starlette(debug=True, routes=routes, middleware=middleware)
EN

回答 1

Stack Overflow用户

发布于 2022-09-01 02:21:00

您需要注意的是,您的路由接受POST方法。

代码语言:javascript
复制
async def homepage(request):
    if request.user.is_authenticated:
        body = await request.json()
        return JSONResponse({"user": my_user, "password": my_pass, "header": request.headers['client_id']})

    return PlainTextResponse('Hello, you')


routes = [
    Route("/testpath", endpoint=homepage, methods=["POST"])
]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73314925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档