Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
HomeAssignment1
IntroductiontoCurrencyExchangeWebService
Consideranoverseasvacationthatyouareplanningthisyear.Itisbesttogowhenthe
exchangerateisinyourfavor.Whenyourdollarsbuymoreintheforeigncurrency,youcando
moreonyourvacation.Thisiswhyitwouldbenicetohaveafunctionthat,givenyourcurrent
amountofcashinUSdollars,tellsyouhowmuchyourmoneyisworthinanothercurrency.
However,thereisnosetmathematicalformulatocomputethisconversion.Thevalueofone
currencywithrespecttoanotherisconstantlychanging.Infact,inthetimethatittakesyouto
readthispieceoftext,theexchangeratebetweenthedollarandtheINRhasprobablychanged
severaltimes.HowonEarthdowewriteaprogramtohandlesomethinglikethat?
Onesolutionistomakeuseofa
webservice.Awebserviceisaprogramthat,whenyousendit
webrequests,automaticallygeneratesawebpagewiththeinformationthatyouaskedfor.In
ourcase,thewebservicewilltellusthecurrentexchangerateformostofthemajor
internationalcurrencies.Yourjobwillbetousestringmanipulationmethodstoreadtheweb
pageandextracttheexactinformationweneed.
Beforewegetintothedetailsoftheassignment,itwouldbegoodifyouexperimentwiththe
webservice.Forthisassignment,youwilluseasimulatedcurrencyexchangeservicethatnever
changesvalues.Thisisimportantfortestingiftheanswerisalwayschanging,itishardtotest
thatyouaregettingtherightanswers.
Tousetheservice,youemployspecialURLsthatstartwiththefollowingprefix:
http://cs1110.cs.cornell.edu/2015fa/a1server.php?
Thisprefixisfollowedbya
currencyquery.Acurrencyqueryhasthreepiecesofinformationin
thefollowingformat(withoutspaceswehaveincludedspacesheresolelyforreadability):
from=source&to=target&q=amount
wheresourceisathreelettercodefortheoriginalcurrency,
targetisathreelettercodeforthe
newcurrencyandamountisafloatvaluefortheamountofmoneyintheoriginal.Forexample,
ifyouwanttoknowthevalueof2.5dollars(USD)inIndianRupee(INR),thequeryis
from=USD&to=INR&amt=2.5
ThefullURLforthisqueryis
http://cs1110.cs.cornell.edu/2015fa/a1server.php?from=USD&to=INR&amt=2.5
Clickonthelinktoseeitinaction.
Youwillnotethatthe"webpage"inyourbrowserisjustasinglelineinthefollowingformat:
{"lhs":"2.5UnitedStatesDollars","rhs":"160.213875IndianRupees","valid":true,"error":""
}
ThisiswhatisknownasaJSONrepresentationoftheanswer.JSONisawayofencoding
complexdatasothatitcanbesentovertheInternet.Youwillusewhatyouknowabout
operationsandmethodsinstringandjsonmoduletopullouttherelevantdataoutoftheJSON
string.
Youshouldtryafewmorecurrencyqueriestofamiliarizeyourselfwiththeservice.
Note:Thecurrencyexchangetable,containingallthevalidcurrencycodes,isprovidedalong
ashtmlfile.Useawebbrowsertoviewit.
Notethatifyouenteraninvalidquery(forexample,usinganonexistentcurrencycodelike
"AAA"),youwillgetthefollowingresponseinerror:
{"lhs":"","rhs":"","valid":false,"error":"Sourcecurrencycodeisinvalid."}
Similarly,ifyouenteraquerywithtwovalidcurrencycodes,butwithaninvalidquantityvalue,
youwillgetthefollowingerror:
{"lhs":"","rhs":"","valid":false,"error":"Currencyamountisinvalid."}
Forallerrorqueries,the"lhs"and"rhs"valuesareblank,while"valid"isfalse.Thevalue"error"
isaspecificerrormessagedescribingtheproblem.Thiswillbeimportantforerrorhandlingin
thisassignment.
TasksintheAssignment
Task1
Forthistask,maintainamoduleina1.pyandimplementthefunctionsdescribedbelow.
Yourprimarygoalinthisassignmentistousethecurrencyexchangeservicetowritethe
followingfunction:
defexchange(currency_from,currency_to,amount_from):
"""Returns:amountofcurrencyreceivedinthegivenexchange.
Inthisexchange,theuserischangingamount_frommoneyin
currencycurrency_fromtothecurrencycurrency_to.Thevalue
returnedrepresentstheamountincurrencycurrency_to.
Return1forinvalidcurrencycodeorinvalidamount_fromvalue
Thevaluereturnedhastypefloat.
Parametercurrency_from:thecurrencyonhand
Precondition:currency_fromisastringforacurrencycode.
Parametercurrency_to:thecurrencytoconvertto
Precondition:currency_toisastringforacurrencycode
Parameteramount_from:amountofcurrencytoconvert
Precondition:amount_fromisafloat"""
Thisfunctionwillinvolveseveralsteps.YouwillgettheJSONstringfromthewebservice,break
upthestringtopulloutthenumericvalue(asasubstring),andthenconvertthatsubstringtoa
float.Foreachofthesesteps,youshoulddefineaseparatefunctionandmakecalltoitin
appropriatefunction(s).Thesefunctionsaredescribedbelowinthreeparts.
PartA:CurrencyQuery
Yourscriptwouldinteractwiththewebservice.Inthispart,youwillimplementasinglefunction.
defcurrency_response(currency_from,currency_to,amount_from):
"""Returns:aJSONstringthatisaresponsetoacurrencyquery.
Acurrencyqueryconvertsamount_frommoneyincurrencycurrency_from
tothecurrencycurrency_to.Theresponseshouldbeastringoftheform
'{"lhs":"<oldamt>","rhs":"<newamt>","valid":true,"error":""}'
wherethevaluesoldamountandnewamountcontainthevalueandname
fortheoriginalandnewcurrencies.Ifthequeryisinvalid,both
oldamountandnewamountwillbeempty,while"valid"willbefollowed
bythevaluefalse.
Parametercurrency_from:thecurrencyonhand
Precondition:currency_fromisastring
Parametercurrency_to:thecurrencytoconvertto
Precondition:currency_toisastring
Parameteramount_from:amountofcurrencytoconvert
Precondition:amount_fromisafloat"""
Whilethisfunctionsoundscomplicated,itisnotasbadasyouthinkitis.Youneedtousethe
urlopenfunctionfromthemoduleurllib.request.Thisfunctiontakesastringthatrepresentsa
URLandreturnsaninstanceoftheclassaddinfourlthatrepresentsthewebpageforthaturl.
Thisobjecthasthefollowingmethods:
Method
Specification
geturl()
Returns:TheURLaddressofthiswebpageasastring.
read()
Returns:Thecontentsofthiswebpageasastring.
Usingoneorbothofthesemethods(youmightnotneedthemboth)isenoughtoimplementthe
functionabove.
PartB:ProcessingJSONdata
Onceyouretrievethejsonstringforyourquery,youneedtoprocessthisstringinordertoget
theamountvalueofexchangedcurrency.Refertotheguideonusingjsonmoduletoprocess
thedataencodedinJSON:http://docs.pythonguide.org/en/latest/scenarios/json/
Notethatyoualsoneedtodealwithcaseswhentheuserqueryisinvalid(eg.Currencycodeis
invalidetc.)Toperformthiserrorcheck,youneedtoimplementafunctiondescribedbelow:
has_error(json)
Returns:TrueifthequeryhasanerrorFalseotherwise.
GivenaJSONresponsetoacurrencyquery,thisreturnstheoppositeofthevaluefollowingthe
keyword"valid".Forexample,iftheJSONis
'{"lhs":"","rhs":"","valid":false,"error":"Sourcecurrencycodeisinvalid."}'
thenthequeryisnotvalid,sothisfunctionreturnsTrue(ItdoesNOTreturnthemessage
'Sourcecurrencycodeisinvalid').
Parameterjson:ajsonstringtoparse
Precondition:jsonistheresponsetoacurrencyquery
PartC:BreakingUpStrings
AlargepartofthisassignmentisbreakingupaJSONstring.Conceptually,youwantto
separatethecurrencyamountfromthecurrencyname.Forexample,ifwearegiventhestring
"0.912968Euros"
Thenwewanttobreakitupinto"0.912968"and"Euros".
before_space(s)
Returns:Substringofsupto,butnotincluding,thefirstspace
Parameters:thestringtoslice
Precondition:shasatleastonespaceinit
after_space(s)
Returns:Substringofsafterthefirstspace
Parameters:thestringtoslice
Precondition:shasatleastonespaceinit
Task2
Onceyouimplementthefunctionalities,youmusttestthem.Implementthetestcodein
a1test.py,usingtheunittestframework.ThisexercisewouldbesimilartowhatyoudidforLab3.
Youshoulddefinetestprocedures,withatleast5testcasesforeach.Thedescriptionoftest
procedureisgivenbelow:
1. testresponse:Checkforajsonresponsetothequeryi.ewritetestcasesfor
currency_response(currency_from,currency_to,amount_from)function.
2. testquery:Checkvalidityofaqueryi.ewritetestcasesforhaserror(json)function
3. testexchange:Checkcorrectnessofexchangeratei.ewritetestcasesfor
exchange(currency_from,currency_to,amount_from)function.
YoumightfinditconvenienttouseacurrencyqueryURLtolookupthecorrectanswer,and
thenpastetheanswerintoyourtestcase.
GradingPolicy
Ingradingyourcode,wewillfocusonthefollowing:
Correctfunctionspecificationsand/orformatting
Adequatetestcasesqualityoftestcases(aretheyextensivelytestingyourapplication?)
Correctnessofthecode(doesitpassourtestcases?)
SubmissionInstructions
Makesureyoumentionthefollowingdetailsascommentsatthetopofboththemodules.
1. NameandRollnumberofboththepartners
Zipa1.pyanda1test.pyanduploadthezippedfileonthedeadlinelink.