Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Middleware

There are several middlewares available provided by Starlette directly.

Read more about them in theFastAPI docs for Middleware.

fastapi.middleware.cors.CORSMiddleware

CORSMiddleware(app,allow_origins=(),allow_methods=("GET",),allow_headers=(),allow_credentials=False,allow_origin_regex=None,allow_private_network=False,expose_headers=(),max_age=600,)
Source code instarlette/middleware/cors.py
161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
def__init__(self,app:ASGIApp,allow_origins:Sequence[str]=(),allow_methods:Sequence[str]=("GET",),allow_headers:Sequence[str]=(),allow_credentials:bool=False,allow_origin_regex:str|None=None,allow_private_network:bool=False,expose_headers:Sequence[str]=(),max_age:int=600,)->None:if"*"inallow_methods:allow_methods=ALL_METHODScompiled_allow_origin_regex=Noneifallow_origin_regexisnotNone:compiled_allow_origin_regex=re.compile(allow_origin_regex)allow_all_origins="*"inallow_originsallow_all_headers="*"inallow_headerspreflight_explicit_allow_origin=notallow_all_originsorallow_credentialssimple_headers:dict[str,str]={}ifallow_all_origins:simple_headers["Access-Control-Allow-Origin"]="*"ifallow_credentials:simple_headers["Access-Control-Allow-Credentials"]="true"ifexpose_headers:simple_headers["Access-Control-Expose-Headers"]=", ".join(expose_headers)preflight_headers:dict[str,str]={}ifpreflight_explicit_allow_origin:# The origin value will be set in preflight_response() if it is allowed.preflight_headers["Vary"]="Origin"else:preflight_headers["Access-Control-Allow-Origin"]="*"preflight_headers.update({"Access-Control-Allow-Methods":", ".join(allow_methods),"Access-Control-Max-Age":str(max_age),})allow_headers=sorted(SAFELISTED_HEADERS|set(allow_headers))ifallow_headersandnotallow_all_headers:preflight_headers["Access-Control-Allow-Headers"]=", ".join(allow_headers)ifallow_credentials:preflight_headers["Access-Control-Allow-Credentials"]="true"self.app=appself.allow_origins=allow_originsself.allow_methods=allow_methodsself.allow_headers=[h.lower()forhinallow_headers]self.allow_all_origins=allow_all_originsself.allow_all_headers=allow_all_headersself.preflight_explicit_allow_origin=preflight_explicit_allow_originself.allow_origin_regex=compiled_allow_origin_regexself.allow_private_network=allow_private_networkself.simple_headers=simple_headersself.preflight_headers=preflight_headers

appinstance-attribute

app=app

allow_originsinstance-attribute

allow_origins=allow_origins

allow_methodsinstance-attribute

allow_methods=allow_methods

allow_headersinstance-attribute

allow_headers=[(lower())forhinallow_headers]

allow_all_originsinstance-attribute

allow_all_origins=allow_all_origins

allow_all_headersinstance-attribute

allow_all_headers=allow_all_headers

preflight_explicit_allow_origininstance-attribute

preflight_explicit_allow_origin=(preflight_explicit_allow_origin)

allow_origin_regexinstance-attribute

allow_origin_regex=compiled_allow_origin_regex

allow_private_networkinstance-attribute

allow_private_network=allow_private_network

simple_headersinstance-attribute

simple_headers=simple_headers

preflight_headersinstance-attribute

preflight_headers=preflight_headers

is_allowed_origin

is_allowed_origin(origin)
Source code instarlette/middleware/cors.py
 97 98 99100101102103104
defis_allowed_origin(self,origin:str)->bool:ifself.allow_all_origins:returnTrueifself.allow_origin_regexisnotNoneandself.allow_origin_regex.fullmatch(origin):returnTruereturnorigininself.allow_origins

preflight_response

preflight_response(request_headers)
Source code instarlette/middleware/cors.py
106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
defpreflight_response(self,request_headers:Headers)->Response:requested_origin=request_headers["origin"]requested_method=request_headers["access-control-request-method"]requested_headers=request_headers.get("access-control-request-headers")requested_private_network=request_headers.get("access-control-request-private-network")headers=dict(self.preflight_headers)failures:list[str]=[]ifself.is_allowed_origin(origin=requested_origin):ifself.preflight_explicit_allow_origin:# The "else" case is already accounted for in self.preflight_headers# and the value would be "*".headers["Access-Control-Allow-Origin"]=requested_originelse:failures.append("origin")ifrequested_methodnotinself.allow_methods:failures.append("method")# If we allow all headers, then we have to mirror back any requested# headers in the response.ifself.allow_all_headersandrequested_headersisnotNone:headers["Access-Control-Allow-Headers"]=requested_headerselifrequested_headersisnotNone:forheaderin[h.lower()forhinrequested_headers.split(",")]:ifheader.strip()notinself.allow_headers:failures.append("headers")breakifrequested_private_networkisnotNone:ifself.allow_private_network:headers["Access-Control-Allow-Private-Network"]="true"else:failures.append("private-network")# We don't strictly need to use 400 responses here, since its up to# the browser to enforce the CORS policy, but its more informative# if we do.iffailures:failure_text="Disallowed CORS "+", ".join(failures)returnPlainTextResponse(failure_text,status_code=400,headers=headers)returnPlainTextResponse("OK",status_code=200,headers=headers)

simple_responseasync

simple_response(scope,receive,send,request_headers)
Source code instarlette/middleware/cors.py
151152153
asyncdefsimple_response(self,scope:Scope,receive:Receive,send:Send,request_headers:Headers)->None:send=functools.partial(self.send,send=send,request_headers=request_headers)awaitself.app(scope,receive,send)

sendasync

send(message,send,request_headers)
Source code instarlette/middleware/cors.py
155156157158159160161162163164165166167168169170171172173174175176
asyncdefsend(self,message:Message,send:Send,request_headers:Headers)->None:ifmessage["type"]!="http.response.start":awaitsend(message)returnmessage.setdefault("headers",[])headers=MutableHeaders(scope=message)headers.update(self.simple_headers)origin=request_headers["Origin"]has_cookie="cookie"inrequest_headers# If request includes any cookie headers, then we must respond# with the specific origin instead of '*'.ifself.allow_all_originsandhas_cookie:self.allow_explicit_origin(headers,origin)# If we only allow specific origins, then we have to mirror back# the Origin header in the response.elifnotself.allow_all_originsandself.is_allowed_origin(origin=origin):self.allow_explicit_origin(headers,origin)awaitsend(message)

allow_explicit_originstaticmethod

allow_explicit_origin(headers,origin)
Source code instarlette/middleware/cors.py
178179180181
@staticmethoddefallow_explicit_origin(headers:MutableHeaders,origin:str)->None:headers["Access-Control-Allow-Origin"]=originheaders.add_vary_header("Origin")

It can be imported fromfastapi:

fromfastapi.middleware.corsimportCORSMiddleware

fastapi.middleware.gzip.GZipMiddleware

GZipMiddleware(app,minimum_size=500,compresslevel=9)
Source code instarlette/middleware/gzip.py
12131415
def__init__(self,app:ASGIApp,minimum_size:int=500,compresslevel:int=9)->None:self.app=appself.minimum_size=minimum_sizeself.compresslevel=compresslevel

appinstance-attribute

app=app

minimum_sizeinstance-attribute

minimum_size=minimum_size

compresslevelinstance-attribute

compresslevel=compresslevel

It can be imported fromfastapi:

fromfastapi.middleware.gzipimportGZipMiddleware

fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware

HTTPSRedirectMiddleware(app)
Source code instarlette/middleware/httpsredirect.py
78
def__init__(self,app:ASGIApp)->None:self.app=app

appinstance-attribute

app=app

It can be imported fromfastapi:

fromfastapi.middleware.httpsredirectimportHTTPSRedirectMiddleware

fastapi.middleware.trustedhost.TrustedHostMiddleware

TrustedHostMiddleware(app,allowed_hosts=None,www_redirect=True)
Source code instarlette/middleware/trustedhost.py
1314151617181920212223242526272829
def__init__(self,app:ASGIApp,allowed_hosts:Sequence[str]|None=None,www_redirect:bool=True,)->None:ifallowed_hostsisNone:allowed_hosts=["*"]forpatterninallowed_hosts:assert"*"notinpattern[1:],ENFORCE_DOMAIN_WILDCARDifpattern.startswith("*")andpattern!="*":assertpattern.startswith("*."),ENFORCE_DOMAIN_WILDCARDself.app=appself.allowed_hosts=list(allowed_hosts)self.allow_any="*"inallowed_hostsself.www_redirect=www_redirect

appinstance-attribute

app=app

allowed_hostsinstance-attribute

allowed_hosts=list(allowed_hosts)

allow_anyinstance-attribute

allow_any='*'inallowed_hosts

www_redirectinstance-attribute

www_redirect=www_redirect

It can be imported fromfastapi:

fromfastapi.middleware.trustedhostimportTrustedHostMiddleware

[8]ページ先頭

©2009-2026 Movatter.jp