Eu implantei um FastAPI para aplicativos da web do Azure. Eu usei o seguinte yaml:
webapps-actions
name: Build and deploy Python app to Azure Web App - fast-api-port
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python version
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate
- name: Install dependencies
run: pip install -r requirements.txt
# Optional: Add step to run tests here (PyTest, Django test suites, etc.)
- name: Zip artifact for deployment
run: zip release.zip ./* -r
- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v4
with:
name: python-app
path: |
release.zip
!venv/
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT
steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: python-app
- name: Unzip artifact for deployment
run: unzip release.zip
- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_xx }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_xx }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_xx }}
- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v3
id: deploy-to-webapp
with:
app-name: 'fast-api-port'
slot-name: 'Production'
Posso ver que os arquivos agora existem no servidor:
Entretanto, quando navego até a URL do aplicativo da web, recebo o seguinte:
Como inicio o servidor uvicorn na implantação? De alguma forma, preciso do fastapi para começar.
Adicionei o seguinte na Configuração:
Código:
from fastapi import FastAPI,Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer
import uvicorn
from fastapi import FastAPI, Security
import os
from typing import Dict
from settings import Settings
from pydantic import AnyHttpUrl,BaseModel
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from fastapi_azure_auth.user import User
settings = Settings()
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""
Load OpenID config on startup.
"""
await azure_scheme.openid_config.load_config()
yield
app = FastAPI(
swagger_ui_oauth2_redirect_url='/oauth2-redirect',
swagger_ui_init_oauth={
'usePkceWithAuthorizationCodeGrant': True,
'clientId': settings.OPENAPI_CLIENT_ID,
'scopes': settings.SCOPE_NAME,
},
)
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
tenant_id=settings.TENANT_ID,
scopes=settings.SCOPES,
)
class User(BaseModel):
name: str
roles: list[str] = []
@app.get("/", dependencies=[Security(azure_scheme)])
async def root():
print("Yo bro")
return {"whoIsTheBest": "DNA Team is"}
@app.get("/test", dependencies=[Security(azure_scheme)])
async def root():
print("Yo test")
return {"whoIsTheBest": "DNA Team is!"}
@app.get("/me", dependencies=[Security(azure_scheme)])
async def me(request: Request):
print("Me")
return User(roles=request.state.user.roles,name=request.state.user.name)
if __name__ == '__main__':
uvicorn.run('main:app', reload=True)
Testei seu código e implantei com sucesso no aplicativo Web do Azure sem problemas.
Recebi o mesmo erro depois de implantar o aplicativo, então, para resolver o problema, configurei o comando de inicialização abaixo na seção de configuração do meu aplicativo Web do Azure.
requirements.txt
arquivo.requisitos.txt:
principal .py:
arquivo de fluxo de trabalho:
Implantei o aplicativo com sucesso no Azure Web App por meio de ações do GitHub.
Saída: