【问题标题】:FastApi Cookies, not creating Cookie when calling functionFastApi Cookies,调用函数时不创建Cookie
【发布时间】:2022-11-12 12:04:13
【问题描述】:

我遇到了问题,因为我必须在后端创建一个 cookie,稍后我将使用它从前端发送请求。两个应用程序都在同一个域上。 这是https://levelup.gitconnected.com/secure-frontend-authorization-67ae11953723 背后的总体思路。

前端代码 - 向后端发送获取请求 `

@app.get('/')
async def homepage(request: Request, response_class=HTMLResponse):
    keycloak_code = 'sksdkssdk'
    data = {'code': keycloak_code}
    url_post = 'http://127.0.0.1:8002/keycloak_code'
    post_token=requests.get(url=url_post, json = data ) 
      return 'Sent'


if __name__ == '__main__':
    uvicorn.run(app, host='local.me.me', port=7999,debug=True)

`

后端代码

`

@app.get("/keycloak_code")
def get_tokens(response: Response, data: dict):
    code = data['code']
    print(code)
....

    requests.get(url='http://local.me.me:8002/set') 
    return True

@app.get("/set")
async def createcookie(response: Response):
    r=response.set_cookie(key='tokic3', value='helloworld', httponly=True)
    return True


if __name__ == '__main__':
    uvicorn.run(app, host='local.me.me', port=8002, log_level="debug")

`

当我打开浏览器并访问“http://local.me.me:8002/set”时,可以看到创建了 Cookie。 但是,当我从我的前端向后端发出相同 URL 的获取请求时,它会收到我在终端中看到的请求,但不会创建 cookie,有人知道我可能做错了什么吗?

我尝试了 FASTapi 文档中的不同实现,但没有一个有类似的用例。

【问题讨论】:

    标签: python cookies fastapi cookie-httponly


    【解决方案1】:

    127.0.0.1localhost(或您的自定义 local.me.me)是两个不同的域/来源。因此,在发出请求时,您需要使用与创建 cookie 相同的域(如果 cookie 是为 local.me.me 创建的,那么您应该在请求中使用该域)。查看相关帖子here,以及herehere

    您似乎有第二个 FastAPI 应用程序(在不同的端口上侦听)充当您的前端(如您所说)。如果这就是你想要做的,你需要在 Python requests 模块中使用Session Objects,或者最好使用httpx库中的Client instance,以便在请求之间保留cookie。 httpx 的优势在于它还提供了一个异步 API,使用 httpx.AsyncClient()。您可以在this answer 以及herehere 中找到更多详细信息和示例。

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多