Movatterモバイル変換


[0]ホーム

URL:


Ana içeriğe geç
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

Response class

You can declare a parameter in apath operation function or dependency to be of typeResponse and then you can set data for the response like headers or cookies.

You can also use it directly to create an instance of it and return it from yourpath operations.

Read more about it in theFastAPI docs about returning a custom Response

You can import it directly fromfastapi:

fromfastapiimportResponse

fastapi.Response

Response(content=None,status_code=200,headers=None,media_type=None,background=None,)
Source code instarlette/responses.py
3435363738394041424344454647
def__init__(self,content:Any=None,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:self.status_code=status_codeifmedia_typeisnotNone:self.media_type=media_typeself.background=backgroundself.body=self.render(content)self.init_headers(headers)

media_typeclass-attributeinstance-attribute

media_type=None

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

backgroundinstance-attribute

background=background

bodyinstance-attribute

body=render(content)

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

[8]ページ先頭

©2009-2026 Movatter.jp