Birmingham-mumbai


app.add_middleware(CORSMiddleware, max_age=3600



tải về 6.62 Mb.
Chế độ xem pdf
trang268/275
Chuyển đổi dữ liệu09.10.2023
Kích6.62 Mb.
#55278
1   ...   264   265   266   267   268   269   270   271   ...   275
Sherwin John Tragura - Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure-Packt Publishing - ebooks Account

app.add_middleware(CORSMiddleware, max_age=3600,
allow_origins=origins, allow_credentials=True,
allow_methods= ["POST", "GET", "DELETE", 
"PATCH", "PUT"], allow_headers=[
"Access-Control-Allow-Origin", 
"Access-Control-Allow-Credentials", 
"Access-Control-Allow-Headers",
"Access-Control-Max-Age"
])
This time, we used FastAPI’s 
add_middleware()
function to add CORS support to our application. 
Aside from 
allow_origins
, we also need to add into 
CORSMiddleware
the 
allow_credentials
parameter, which adds 
Access-Control-Allow-Credentials: true
to the response header 
for the browser to recognize the domain origin matches and send an 
Authorization
cookie to 
allow the request. Also, we must include the 
allow_headers
parameter, which registers a list of 
acceptable header keys during browser interaction. Aside from 
Accept

Accept-Language

Content-Language
, and 
Content-Type
, which are included by default, we need to register 
Access-Control-Allow-Origin

Access-Control-Allow-Credentials

Access-
Control-Allow-Headers
, and 
Access-Control-Max-Age
explicitly instead of using the 


Customizing APIRoute and Request
297
asterisk (
*
). The 
allow_headers
parameter must also be part of the middleware to specify other 
HTTP methods that need to be supported by the browser. And lastly, the 
max_age
parameter must 
also be in the configuration because we need to tell the browser the amount of time it will cache all 
the resources loaded into the browser.
If the application needs additional CORS support features, customizing the 
CORSMiddleware
to 
extend some built-in utilities and features to manage CORS is a better solution. 
By the way, it is not only the middleware that we can subclass and use to create custom implementations 
of but also the 
Request
data and API routes. 

tải về 6.62 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   264   265   266   267   268   269   270   271   ...   275




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương