小编Eth*_*thr的帖子

如何使用 HTTP Basic Auth 作为单独的 FastAPI 服务?

我想实现什么目标?有一项负责 HTTP 基本身份验证(访问)的服务和两项服务(a、b),其中某些端点受到访问服务的保护。

为什么?在存在更多具有受保护端点的服务的情况下,每个服务中都不会重复授权功能。还要在一处进行修改,以防更改为 OAuth2(也许将来)。

我做了什么? 我按照官方网站上的指南创建了示例服务,该服务运行得很好。

当我尝试将授权移至单独的服务,然后在具有受保护端点的少数其他服务中使用它时,就会出现问题。我不知道该怎么做。你能帮我一下吗?

我尝试过不同的功能设置。没有任何帮助,到目前为止我的代码如下所示:

访问服务

import os
import secrets

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

security = HTTPBasic()


def authorize(credentials: HTTPBasicCredentials = Depends(security)):
    is_user_ok = secrets.compare_digest(credentials.username, os.getenv('LOGIN'))
    is_pass_ok = secrets.compare_digest(credentials.password, os.getenv('PASSWORD'))

    if not (is_user_ok and is_pass_ok):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Incorrect email or password.',
            headers={'WWW-Authenticate': 'Basic'},
        )


app = FastAPI(openapi_url="/api/access/openapi.json", docs_url="/api/access/docs")


@app.get('/api/access/auth', dependencies=[Depends(authorize)])
def auth():
    return {"Granted": True} …
Run Code Online (Sandbox Code Playgroud)

python authentication basic-authentication microservices fastapi

4
推荐指数
1
解决办法
2万
查看次数

为什么在自己的and函数实现中出现异常?

我正在尝试and在Haskell中编写自己的函数。看起来像:

and' :: [Bool] -> Bool
and' (x:xs) = x && and' xs
Run Code Online (Sandbox Code Playgroud)

当我使用and' [True, True, True]它给我例外:

*** Exception: 6.hs:27:1-26: Non-exhaustive patterns in function and'
Run Code Online (Sandbox Code Playgroud)

我发现添加:and' _ = True解决了我的问题,但实际上为什么我必须添加此行?如果我的思维方式正确,函数应该返回我True && True && True,当我在ghci中使用此组合时,它会返回True。你能给我解释一下吗?有没有办法查看andghci 中函数的实现?

recursion haskell boolean

3
推荐指数
1
解决办法
73
查看次数

如何使用列表中的值格式化字符串?

如何打印列表的下一个值代替%s?下面的代码显示了我希望得到的结果,但我不想手动编写每一步.

hours=["14","15","18","30"]
print (("%s:%s-%s:%s")%(hours[0],hours[1],hours[2],hours[3]))
Run Code Online (Sandbox Code Playgroud)

有没有办法做这样的事情:

print (("%s:%s-%s:%s")%hours)
Run Code Online (Sandbox Code Playgroud)

并使其工作?

python string format list python-3.x

2
推荐指数
1
解决办法
79
查看次数

是否可以将值从列表解包到切片?

我正在尝试使用列表中的值来选择单词的一部分。这是工作解决方案:

word = 'abc'*4
slice = [2,5]  #it can contain 1-3 elements

def try_catch(list, index):
    try:
        return list[index]
    except IndexError:
        return None

print(word[slice[0]:try_catch(slice,1):try_catch(slice,2)])
Run Code Online (Sandbox Code Playgroud)

但我想知道是否可以缩短它?我想到了这样的事情:

word = 'abc'*4
slice = [2,6,2]
print(word[':'.join([str(x) for x in slice])]) #missing : for one element in list
Run Code Online (Sandbox Code Playgroud)

它产生:

TypeError: string indices must be integers
Run Code Online (Sandbox Code Playgroud)

python unpack slice

1
推荐指数
1
解决办法
787
查看次数