Django REST框架创建一个简单的Api实例讲解
CreateaSimpleAPIUsingDjangoRESTFrameworkinPython
WHATISANAPI
APIstandsforapplicationprogramminginterface.APIbasicallyhelpsonewebapplicationtocommunicatewithanotherapplication.
Let'sassumeyouaredevelopinganandroidapplicationwhichhasfeaturetodetectthenameofafamouspersoninanimage.
Introducetoachievethisyouhave2options:
option1:
Option1istocollecttheimagesofallthefamouspersonalitiesaroundtheworld,buildamachinelearning/deeplearningorwhatevermodelitisanduseitinyourapplication.
option2:
Justusesomeoneelsesmodelusingapitoaddthisfeatureinyourapplication.
LargecompanieslikeGoogle,theyhavetheirownpersonalities.SoifweusetheirApi,wewouldnotknowwhatlogic/codewheyhavewrittinginsideandhowtheyhavetrainedthemodel.Youwillonlybegivenanapi(oranurl).Itworkslikeablackboxwhereyousendyourrequest(inourcaseitstheimage),andyougettheresponse(whichisthenameofthepersoninthatimage)
Hereisanexample:
PREREQUISITES
condainstalljango condainstall-cconda-forgedjangorestframework
Step1
Createthedjangoproject,openthecommandprompttherreandenterthefollowingcommand:
django-adminstartprojectSampleProject
Step2
Navigatetheprojectfolderandcreateawebappusingthecommandline.
pythonmanage.pystartappMyApp
Step3
openthesetting.pyandaddthebelowlinesintoofcodeintheINSTALLED_APPSsection:
'rest_framework', 'MyApp'
Step4
Opentheviews.pyfileinsideMyAppfolderandaddthebelowlinesofcode:
fromdjango.shortcutsimportrender fromdjango.httpimportHttp404 fromrest_framework.viewsimportAPIView fromrest_framework.decoratorsimportapi_view fromrest_framework.responseimportResponse fromrest_frameworkimportstatus fromdjango.httpimportJsonResponse fromdjango.coreimportserializers fromdjango.confimportsettings importjson #Createyourviewshere. @api_view(["POST"]) defIdealWeight(heightdata): try: height=json.loads(heightdata.body) weight=str(height*10) returnJsonResponse("Idealweightshouldbe:"+weight+"kg",safe=False) exceptValueErrorase: returnResponse(e.args[0],status.HTTP_400_BAD_REQUEST)
Step5
Openurls.pyfileandaddthebelowlinesofcode:
fromdjango.conf.urlsimporturl fromdjango.contribimportadmin fromMyAppimportviews urlpatterns=[ url(r'^admin/',admin.site.urls), url(r'^idealweight/',views.IdealWeight) ]
Step6
Wecanstarttheapiwithbelowcommandsincommandprompt:
pythonmanage.pyrunserver
Finallyopentheurl:
http://127.0.0.1:8000/idealweight/
References:
CreateaSimpleAPIUsingDjangoRESTFrameworkinPython
以上就是本次介绍的关于DjangoREST框架创建一个简单的Api实例讲解内容,感谢大家的学习和对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。