最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - ImportError: cannot > import name 'AccessTokenInfo' from 'azure.core.credentials&#39

programmeradmin1浏览0评论

I have a FAST API deployed to an azure function. Locally everything works as expected. However when deployed I get following error. The error allready occurs in when doing the import:

from azure.identity import DefaultAzureCredential #if i remove this line it works

2025-02-05T18:13:34.960344159Z return util.import_app(self.app_uri) 2025-02-05T18:13:34.960347459Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960350559Z File "/opt/python/3.12.2/lib/python3.12/site-packages/gunicorn/util.py", line 371, in import_app 2025-02-05T18:13:34.960353959Z mod = importlib.import_module(module) 2025-02-05T18:13:34.960357159Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960360459Z File "/opt/python/3.12.2/lib/python3.12/importlib/init.py", line 90, in import_module 2025-02-05T18:13:34.960363959Z return _bootstrap._gcd_import(name[level:], package, level) 2025-02-05T18:13:34.960367359Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960370759Z File "", line 1387, in _gcd_import 2025-02-05T18:13:34.960374859Z File "", line 1360, in _find_and_load 2025-02-05T18:13:34.960378160Z File "", line 1331, in _find_and_load_unlocked 2025-02-05T18:13:34.960381660Z
File "", line 935, in _load_unlocked 2025-02-05T18:13:34.960384960Z File "", line 995, in exec_module 2025-02-05T18:13:34.960388360Z File "", line 488, in _call_with_frames_removed 2025-02-05T18:13:34.960392960Z File "/tmp/8dd460fb826ed55/main.py", line 12, in 2025-02-05T18:13:34.960400760Z from azure.identity import DefaultAzureCredential 2025-02-05T18:13:34.960404260Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/init.py", line 10, in 2025-02-05T18:13:34.960407860Z from ._credentials import ( 2025-02-05T18:13:34.960411060Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/_credentials/init.py", line 5, in 2025-02-05T18:13:34.960414560Z from .authorization_code import AuthorizationCodeCredential 2025-02-05T18:13:34.960417860Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/_credentials/authorization_code.py", line 7, in 2025-02-05T18:13:34.960421260Z from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions 2025-02-05T18:13:34.960424860Z ImportError: cannot import name 'AccessTokenInfo' from 'azure.core.credentials' (/agents/python/azure/core/credentials.py)

Main.py:

import os
from typing import Union
from fastapi import FastAPI, Security
import uvicorn
from utils.azure.fast_api_auth import FastAPIAuth,FastAPIAuthOptions
from routers.router1 import router1_router
from enums import fast_api_metadata
from settings import settings
import logging

from azure.identity import DefaultAzureCredential

print("TEST1")

fast_api_options = FastAPIAuthOptions(
    title="DNA PORT API",
    tenant_id=settings.TENANT_ID,
    openapi_tags=fast_api_metadata,
    client_id=settings.fastapi_settings.APP_CLIENT_ID,

)

fast_api_auth = FastAPIAuth(fast_api_options)
app = fast_api_auth.get_fast_api_app()

app.include_router(
    router1_router,
    prefix="/api/router1",
    dependencies=[Security(fast_api_auth.azure_scheme)],

    tags=["vessels"]
)

@app.get("/log", dependencies=[Security(fast_api_auth.azure_scheme)])
async def root():
    return {"whoIsTheBest": "!!"}

@app.get("/", dependencies=[Security(fast_api_auth.azure_scheme)])
def read_root():
    return {"Hello": "World"}

@app.get("/settings")
def read_settings():
    return settings

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

if __name__ == '__main__':
    uvicorn.run(
        'main:app',
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )

Requirements.txt:

annotated-types==0.7.0
anyio==4.7.0
certifi==2024.8.30
cffi==1.17.1
click==8.1.7
colorama==0.4.6
cryptography==44.0.0
fastapi==0.115.6
fastapi-azure-auth==5.0.1
h11==0.14.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
pycparser==2.22
pydantic==2.10.3
pydantic-settings==2.6.1
pydantic_core==2.27.1
PyJWT==2.10.1
python-dotenv==1.0.1
sniffio==1.3.1
starlette==0.41.3
typing_extensions==4.12.2
uvicorn==0.32.1
azure-monitor-opentelemetry
databricks
databricks.sdk
databricks-sql-connector
pandas
sqlalchemy
numpy
azure-identity
opencensus-ext-azure
opentelemetry-api
opentelemetry-sdk
opentelemetry-instrumentation-fastapi

I have a FAST API deployed to an azure function. Locally everything works as expected. However when deployed I get following error. The error allready occurs in when doing the import:

from azure.identity import DefaultAzureCredential #if i remove this line it works

2025-02-05T18:13:34.960344159Z return util.import_app(self.app_uri) 2025-02-05T18:13:34.960347459Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960350559Z File "/opt/python/3.12.2/lib/python3.12/site-packages/gunicorn/util.py", line 371, in import_app 2025-02-05T18:13:34.960353959Z mod = importlib.import_module(module) 2025-02-05T18:13:34.960357159Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960360459Z File "/opt/python/3.12.2/lib/python3.12/importlib/init.py", line 90, in import_module 2025-02-05T18:13:34.960363959Z return _bootstrap._gcd_import(name[level:], package, level) 2025-02-05T18:13:34.960367359Z
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-02-05T18:13:34.960370759Z File "", line 1387, in _gcd_import 2025-02-05T18:13:34.960374859Z File "", line 1360, in _find_and_load 2025-02-05T18:13:34.960378160Z File "", line 1331, in _find_and_load_unlocked 2025-02-05T18:13:34.960381660Z
File "", line 935, in _load_unlocked 2025-02-05T18:13:34.960384960Z File "", line 995, in exec_module 2025-02-05T18:13:34.960388360Z File "", line 488, in _call_with_frames_removed 2025-02-05T18:13:34.960392960Z File "/tmp/8dd460fb826ed55/main.py", line 12, in 2025-02-05T18:13:34.960400760Z from azure.identity import DefaultAzureCredential 2025-02-05T18:13:34.960404260Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/init.py", line 10, in 2025-02-05T18:13:34.960407860Z from ._credentials import ( 2025-02-05T18:13:34.960411060Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/_credentials/init.py", line 5, in 2025-02-05T18:13:34.960414560Z from .authorization_code import AuthorizationCodeCredential 2025-02-05T18:13:34.960417860Z File "/tmp/8dd460fb826ed55/antenv/lib/python3.12/site-packages/azure/identity/_credentials/authorization_code.py", line 7, in 2025-02-05T18:13:34.960421260Z from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions 2025-02-05T18:13:34.960424860Z ImportError: cannot import name 'AccessTokenInfo' from 'azure.core.credentials' (/agents/python/azure/core/credentials.py)

Main.py:

import os
from typing import Union
from fastapi import FastAPI, Security
import uvicorn
from utils.azure.fast_api_auth import FastAPIAuth,FastAPIAuthOptions
from routers.router1 import router1_router
from enums import fast_api_metadata
from settings import settings
import logging

from azure.identity import DefaultAzureCredential

print("TEST1")

fast_api_options = FastAPIAuthOptions(
    title="DNA PORT API",
    tenant_id=settings.TENANT_ID,
    openapi_tags=fast_api_metadata,
    client_id=settings.fastapi_settings.APP_CLIENT_ID,

)

fast_api_auth = FastAPIAuth(fast_api_options)
app = fast_api_auth.get_fast_api_app()

app.include_router(
    router1_router,
    prefix="/api/router1",
    dependencies=[Security(fast_api_auth.azure_scheme)],

    tags=["vessels"]
)

@app.get("/log", dependencies=[Security(fast_api_auth.azure_scheme)])
async def root():
    return {"whoIsTheBest": "!!"}

@app.get("/", dependencies=[Security(fast_api_auth.azure_scheme)])
def read_root():
    return {"Hello": "World"}

@app.get("/settings")
def read_settings():
    return settings

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

if __name__ == '__main__':
    uvicorn.run(
        'main:app',
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )

Requirements.txt:

annotated-types==0.7.0
anyio==4.7.0
certifi==2024.8.30
cffi==1.17.1
click==8.1.7
colorama==0.4.6
cryptography==44.0.0
fastapi==0.115.6
fastapi-azure-auth==5.0.1
h11==0.14.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
pycparser==2.22
pydantic==2.10.3
pydantic-settings==2.6.1
pydantic_core==2.27.1
PyJWT==2.10.1
python-dotenv==1.0.1
sniffio==1.3.1
starlette==0.41.3
typing_extensions==4.12.2
uvicorn==0.32.1
azure-monitor-opentelemetry
databricks
databricks.sdk
databricks-sql-connector
pandas
sqlalchemy
numpy
azure-identity
opencensus-ext-azure
opentelemetry-api
opentelemetry-sdk
opentelemetry-instrumentation-fastapi
Share Improve this question asked Feb 5 at 18:22 Thomas SegatoThomas Segato 5,22316 gold badges64 silver badges128 bronze badges 2
  • Are you getting the error during deployment? – Pravallika KV Commented Feb 6 at 3:31
  • No when the web is starting. I get the error in the Log Stream and then the UI shows Application Error. – Thomas Segato Commented Feb 6 at 7:28
Add a comment  | 

1 Answer 1

Reset to default 0

I have deployed your code to Azure function App and able to get the expected response.

Pass the access token as Bearer Token in Auth while testing the function.

Folder Structure:

│my-fastapi-azure-function/
|____function_app.py
|____host.json
|____local.settings.json
├───WrapperFunction
│   │   enums.py
│   │   settings.py
│   │   __init__.py
│   │
│   ├───routers
│   │       router1.py
│   │
│   ├───utils
│   │   │   __init__.py
│   │   │
│   │   └───azure
│   │           fast_api_auth.py
│   │           __init__.py

I have used the code provided below:

init.py:

import os
from typing import Union
from fastapi import FastAPI, Security
import uvicorn
from WrapperFunction.utils.azure.fast_api_auth import FastAPIAuth, FastAPIAuthOptions
from WrapperFunction.routers.router1 import router1_router
from WrapperFunction.enums import fast_api_metadata
from WrapperFunction.settings import settings
import logging
from azure.identity import DefaultAzureCredential

print("TEST1")

fast_api_options = FastAPIAuthOptions(
    title="DNA PORT API",
    tenant_id=settings.TENANT_ID,
    openapi_tags=fast_api_metadata,
    client_id=settings.APP_CLIENT_ID,

)

fast_api_auth = FastAPIAuth(fast_api_options)
app = fast_api_auth.get_fast_api_app()

app.include_router(
    router1_router,
    prefix="/api/router1",
    dependencies=[Security(fast_api_auth.azure_scheme)],

    tags=["vessels"]
)

@app.get("/log", dependencies=[Security(fast_api_auth.azure_scheme)])
async def root():
    return {"whoIsTheBest": "!!"}

@app.get("/", dependencies=[Security(fast_api_auth.azure_scheme)])
def read_root():
    return {"Hello": "World"}

@app.get("/settings")
def read_settings():
    return settings
@app.get("/token_test")
def token_test(token: str = Security(fast_api_auth.azure_scheme)):
    return {"message": "Token is valid", "token": token}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

if __name__ == '__main__':
    uvicorn.run(
        'main:app',
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )

utils=>azure=>function_api_auth.py:

from fastapi import Security
from azure.identity import DefaultAzureCredential
from fastapi.security import OAuth2PasswordBearer

class FastAPIAuth:
    def __init__(self, options):
        self.options = options
        self.azure_scheme = OAuth2PasswordBearer(tokenUrl="token")

    def get_auth_scheme(self):
        return DefaultAzureCredential()

    def get_fast_api_app(self):
        from fastapi import FastAPI
        app = FastAPI(title=self.options.title)
        return app

class FastAPIAuthOptions:
    def __init__(self, title, tenant_id, openapi_tags, client_id):
        self.title = title
        self.tenant_id = tenant_id
        self.openapi_tags = openapi_tags
        self.client_id = client_id

routers=>router1.py:

from fastapi import APIRouter

router1_router = APIRouter()

@router1_router.get("/")
def get_vessels():
    return {"vessel": "data"}

settings.py:

import os

class FastAPISettings:

    APP_CLIENT_ID ="Client_ID",
    TENANT_ID="Tenant_ID"

fastapi_settings = FastAPISettings()
settings = fastapi_settings

enums.py:

fast_api_metadata = [
    {"name": "vessels", "description": "Vessel related operations"}
]

function_app.py:

import azure.functions as func
from WrapperFunction import app as fastapi_app

app = func.AsgiFunctionApp(app=fastapi_app, http_auth_level=func.AuthLevel.ANONYMOUS)

Able to run the function as expected:

route: https://pyfn06.azurewebsites.net/:

route: https://pyfn06.azurewebsites.net/log:

route: https://pyfn06.azurewebsites.net/api/router1

route: https://pyfn06.azurewebsites.net//items/1?q=test:

发布评论

评论列表(0)

  1. 暂无评论