local na rede Internet:Home - Django REST frameworkcontente
Home-DjangoRESTframeworkvar_gaq=_gaq||[];_gaq.push(['_setAccount','UA--2']);_gaq.push(['_trackPeview']);(function(){varga=document.createElement('script');ga.type='text/jascript';ga.async=true;ga.src=(':'==document.location.protocol?'ssl':'httpwww')+'.google-analytics.com/ga.js';vars=document.getElementsByTName('script')[0];s.parentNode.insertBefore(ga,s);})();#sidebarIncludeimg{margin-bottom:10px;}#sidebarIncludea.promo{color:black;}@media(max-width:767px){div.promo{display:none;}}GitHubNextPreviousSearchDjangoRESTframeworkHomeTutorialQuickstart1-Serialization2-Requestsandresponses3-Classbasedviews4-Authenticationandpermissions5-RelationshipsandhyperlinkedAPIs6-ViewsetsandroutersAPIGuideRequestsResponsesViewsGenericviewsViewsetsRoutersParsersRenderersSerializersSerializerfieldsSerializerrelationsValidatorsAuthenticationPermissionsCachingThrottlingFilteringPinationVersioningContentnegotiationMetadataSchemasFormatsuffixesReturningURLsExceptionsStatuscodesTestingSettingsTopicsDocumentingyourAPIInternationalizationAJAX,CSRF&CORSHTML&FormsBrowserEnhancementsTheBrowsableAPIREST,Hypermedia&HATEOASCommunityTutorialsandResourcesThirdPartyPackesContributingtoRESTframeworkProjectmanementReleaseNotes3.15Announcement3.14Announcement3.13Announcement3.12Announcement3.11Announcement3.10Announcement3.9Announcement3.8Announcement3.7Announcement3.6Announcement3.5Announcement3.4Announcement3.3Announcement3.2Announcement3.1Announcement3.0AnnouncementKickstarterAnnouncementMozillaGrantFundingJobs×DocumentationsearchCloseDjangoRESTframeworkFundingRequirementsInstallationExampleQuickstartDevelopmentSupportSecurityLicense.promolia{float:left;width:130px;height:20px;text-align:center;margin:10px30px;padding:150px000;background-position:050%;background-size:130pxauto;background-repeat:no-repeat;font-size:120%;color:black;}.promoli{list-style:none;}DjangoRESTFrameworkDjangoRESTframeworkisapowerfulandflexibletoolkitforbuildingWebAPIs.SomereasonsyoumightwanttouseRESTframework:TheWebbrowsableAPIisahugeusabilitywinforyourdevelopers.AuthenticationpoliciesincludingpackesforOAuth1aandOAuth2.SerializationthatsupportsbothORMandnon-ORMdatasources.Customizableallthewaydown-justuseregularfunction-basedviewsifyoudon'tneedthemorepowerfulfeatures.Extensivedocumentation,andgreatcommunitysupport.UsedandtrustedbyinternationallyrecognisedcompaniesincludingMozilla,RedHat,Heroku,andEventbrite.FundingRESTframeworkisacollaborativelyfundedproject.IfyouuseRESTframeworkcommerciallywestronglyencoureyoutoinvestinitscontinueddevelopmentbysigningupforapaidplan.Everysinglesign-uphelpsusmakeRESTframeworklong-termfinanciallysustainable.SentryStreamSpacinovRetoolbit.ioPostHogCryptAPIFEZTOSvixZuploManythankstoallourwonderfulsponsors,andinparticulartoourpremiumbackers,Sentry,Stream,Spacinov,Retool,bit.io,PostHog,CryptAPI,FEZTO,Svix,,andZuplo.RequirementsRESTframeworkrequiresthefollowing:Django(4.2,5.0)Python(3.8,3.9,3.10,3.11,3.12)WehighlyrecommendandonlyofficiallysupportthelatestpatchreleaseofeachPythonandDjangoseries.Thefollowingpackesareoptional:PyYAML,uritemplate(5.1+,3.0.0+)-Schemagenerationsupport.MarkdHome - Django REST frameworkown(3.3.0+)-MarkdownsupportforthebrowsableAPI.Pygments(2.7.0+)-AddsyntaxhighlightingtoMarkdownprocessing.django-filter(1.0.1+)-Filteringsupport.django-guardian(1.1.1+)-Objectlevelpermissionssupport.InstallationInstallusingpip,includinganyoptionalpackesyouwant...pipinstalldjangorestframeworkpipinstallmarkdown#MarkdownsupportforthebrowsableAPI.pipinstalldjango-filter#Filteringsupport...orclonetheprojectfromgithub.gitclonegithub.com/encode/django-rest-frameworkAdd'rest_framework'toyourINSTALLED_APPSsetting.INSTALLED_APPS=[...'rest_framework',]Ifyou'reintendingtousethebrowsableAPIyou'llprobablyalsowanttoaddRESTframework'sloginandlogoutviews.Addthefollowingtoyourrooturls.pyfile.urlpatterns=[...path('api-auth/',include('rest_framework.urls'))]NotethattheURLpathcanbewhateveryouwant.ExampleLet'stakealookataquickexampleofusingRESTframeworktobuildasimplemodel-backedAPI.We'llcreatearead-writeAPIforaccessinginformationontheusersofourproject.AnyglobalsettingsforaRESTframeworkAPIarekeptinasingleconfigurationdictionarynamedREST_FRAMEWORK.Startoffbyaddingthefollowingtoyoursettings.pymodule:REST_FRAMEWORK={#UseDjango'sstandard`django.contrib.auth`permissions,#orallowread-onlyaccessforunauthenticatedusers.'DEFAULT_PERMISSIHome - Django REST frameworkON_CLASSES':['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly']}Don'tforgettomakesureyou'vealsoaddedrest_frameworktoyourINSTALLED_APPS.We'rereadytocreateourAPInow.Here'sourproject'srooturls.pymodule:fromdjango.urlsimportpath,includefromdjango.contrib.auth.modelsimportUserfromrest_frameworkimportrouters,serializers,viewsets#SerializersdefinetheAPIrepresentation.classUserSerializer(serializers.HyperlinkedModelSerializer):classMeta:model=Userfields=['url','username','email','is_staff']#ViewSetsdefinetheviewbehior.classUserViewSet(viewsets.ModelViewSet):queryset=User.objects.all()serializer_class=UserSerializer#RoutersprovideaneasywayofautomaticallydeterminingtheURLconf.router=routers.DefaultRouter()router.register(r'users',UserViewSet)#WireupourAPIusingautomaticURLrouting.#Additionally,weincludeloginURLsforthebrowsableAPI.urlpatterns=[path('',include(router.urls)),path('api-auth/',include('rest_framework.urls',namespace='rest_framework'))]YoucannowopentheAPIinyourbrowserathttp127.0.0.1:8000/,andviewyournew'users'API.Ifyouusethelogincontrolinthetoprightcorneryou'llalsobeabletoadd,createanddeleteusersfromthesystem.QuickstartCan'twaittogetstarted?Thequickstartguideisthefastestwaytogetupandrunning,andbuildingAPIswithRESTframework.DevelopmentSeetheContributionguidelinesforinformationonhowtoclonetherepository,runthetestsuiteandhelpmaintainthecodebaseofRESTFramework.SupportForsupportpleaseseetheRESTframeworkdiscussiongroup,trythe#restframeworkchannelonirc.libera.chat,orraiseaquestiononStackOverflow,makingsuretoincludethe'django-rest-framework't.Forprioritysupportpleasesignupforaprofessionalorpremiumsponsorshipplan.SecuritySecurityissuesarehandledunderthesupervisionoftheDjangosecurityteam.Pleasereportsecurityissuesbyemailingsecurity@djangoproject.com.Theprojectmaintainerswillthenworkwithyoutoresolveanyissueswhererequired,priortoanypublicdisclosure.License©2011-present,EncodeOSSLtd.Allrightsreserved.Redistributionanduseinsourceandbinaryforms,withorwithoutmodification,arepermittedprovidedthatthefollowingconditionsaremet:Redistributionsofsourcecodemustretaintheabovenotice,thislistofconditionsandthefollowingdisclaimer.Redistributionsinbinaryformmustreproducetheabovenotice,thislistofconditionsandthefollowingdisclaimerinthedocumentationand/orothermaterialsprovidedwiththedistribution.Neitherthenameoftheholdernorthenamesofitscontributorsmaybeusedtoendorseorpromoteproductsderivedfromthissoftwarewithoutspecificpriorwrittenpermission.THISSOFTWAREISPROVIDEDBYTHEHHome - Django REST frameworkOLDERSANDCONTRIBUTORS"ASIS"ANDANYEXPRESSORIMPLIEDWARRANTIES,INCLUDING,BUTNOTLIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESSFORAPARTICULARPURPOSEAREDISCLAIMED.INNOEVENTSHALLTHEHOLDERORCONTRIBUTORSBELIABLEFORANYDIRECT,INDIRECT,INCIDENTAL,SPECIAL,EXEMPLARY,ORCONSEQUENTIALDAMES(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENTOFSUBSTITUTEGOODSORSERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION)HOWEVERCAUSEDANDONANYTHEORYOFLIABILITY,WHETHERINCONTRACT,STRICTLIABILITY,ORTORT(INCLUDINGNEGLIGENCEOROTHERWISE)ARISINGINANYWAYOUTOFTHEUSEOFTHISSOFTWARE,EVENIFADVISEDOFTHEPOSSIBILITYOFSUCHDAME.DocumentationbuiltwithMkDocs.varshiftWindow=function(){scrollBy(0,-50)};if(location.hash)shiftWindow();window.addEventListener("hashchange",shiftWindow);$('.dropdown-menu').on('clicktouchstart',function(event){event.stopPropation();});//Dynamicallyforcesiden/dropdowntonohigherthanbrowserwindow$('.side-n,.dropdown-menu').css('max-height',window.innerHeight-130);$(function(){$(window).resize(function(){$('.side-n,.dropdown-menu').css('max-height',window.innerHeight-130);});});