这个Starlette代码可以工作,但只适用于GET,我需要POST



我能够从一个示例Starlette中构建一段代码,该代码获取Basic Auth用户名和密码,读取一个标头,并获取json主体。但只有当我使用";获取";而不是post,而且我还没能弄清楚如何将接受的方法更改为post。(我试图托管的应用程序只使用POST。让POST方法工作是一件简单的事情,还是一次重写?

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)

您需要提到您的路由接受POST方法。

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"])
]

相关内容

  • 没有找到相关文章

最新更新