Question? Leave a message!




Introduction to CGI Programming

Introduction to CGI Programming
Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb MCS275Lecture 21 ProgrammingToolsandFileManagement Jan Verschelde,27February2017 ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 1/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 2/ 33the Web Server Apache theA in LAMP Thecombinationofwebserver, scripting language,anddatabaseis often referred to as the LAMP system. LAMPstandsfor L is Linux, theoperatingsystem; A is Apache,the webserver; M is MySQL,the database; P is Python,the scripting language. Observethat all four are opensource software. Apachemakes acute punon “a patchywebserver”, but its nameis in honoroftheNative American Apachetribe. Its web site is athttp://www.apache.org. ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 3/ 33Running Apache onaMacOSX Apacheis platform independent. We will demonstrateona MacOS X. 1 Apacheis alreadyinstalledon MacOSX, launchSafari withhttp://localhost/to verify. 2 Toenablewebsharing,selectSharingfrom the System Preferences. 3 Insteadofpublichtml,theSitesdirectory is whereMac usersstore their webpages. 4 Insteadof/var/www/cgibin,CGIscripts are in /Library/WebServer/CGIExecutables. CGI = CommonGatewayInterface, is set of protocolsthrough whichapplicationsinteract with webservers. Usinglocalhostwe remain working offline. ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 4/ 33more instructions are needed since Yosemite Tocheck the version ofApache: httpd v Server version: Apache/2.4.23 (Unix) Server built: Aug 8 2016 16:31:34 TolaunchApache,typesudo /usr/sbin/apachectl graceful in a Terminalwindow. Pointing the browsertolocalhost(or 127.0.0.1)showsIt works. Tocheck the configurationof Apache,type apachectl configtest at the commandprompt. ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 5/ 33serving web pages from user directories Toserve webpagesfrom user directories,in the file /etc/apache2/extra/httpduserdir.conf uncommentthe linethat contains Include /private/etc/apache2/users/ .conf In/etc/apache2/httpd.confuncommentthe lines LoadModule userdirmodule libexec/apache2/moduserdir.so User home directories Include /private/etc/apache2/extra/httpduserdir.conf andalso theline LoadModule cgimodule libexec/apache2/modcgi.so ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 6/ 33configuration of users In the folder/etc/apache2/users, ifuseris your user name,in the fileuser.conf, thenaddthe line Require all granted inside the block Directory "/Users/user/Sites/" Options Indexes MultiViews AllowOverride None Require all granted /Directory ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 7/ 33Running the Web Server Apache on Windows... Apacheis platform independent. Ona Windows2000Dell LatitudeLaptop: 1 Downloadbinariesof Apachewebserverfrom http://www.apache.org. 2 Loginas Administratorandinstall Apachebinary. 3 Connecttohttp://127.0.0.1:8080/ 4 html files areinc:/Program Files/Apache " + "Software Foundation/Apache2.2/htdocs" 5 scripts are in"c:/Program Files/Apache " + "Software Foundation/Apache2.2/cgibin" Important: localhost=127.0.0.1:8080. ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 8/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27 February2017 9/ 33Python Works – our first CGI script ThePythonscriptpythonworks.py: /usr/bin/python """ Place this in /Library/WebServer/CGIExecutables. """ print("ContentType: text/plain\n\n") print("Python works") Thefirst lineis the locationofthe Pythoninterpreter. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 10/ 33dynamic web pages /usr/bin/python """ Displays the current time in a browser window. """ import time print("ContentType: text/plain\n") print(time.ctime(time.time())) Thetime getsupdatedeverytime the pagerefreshes. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 11/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 12/ 33Dynamic Web Pages HTTP:GETandPOSTmethods HTTP(HyperText Transfer Protocol) determinesrequestresponse communication betweenwebbrowserandwebserver. Methodsof HTTP: GET methodis a requestfor a static resource, such asan HTMLpage. Just typing theURL of therequestedwebpageinvokes theGETmethod. POST methodis a requestfor a dynamicresource,with input parametersofthe requestcontainedwithinthe bodyof therequest. TheGETandPOSTmethodsare most commonlyused. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 13/ 33Elements of HTML HyperTextMarkup Language Commonlyusedelementsin HTMLdocuments: HTML HTMLmarks start of HTMLdocument, and/HTMLmarks the end. HEAD specifies headerinformationof adocument. TITLE specifies title of thedocument. BODY containsthebodytext of thedocument. FONT usedto alterfont size andcolorof text. H1 to displayheadingsoftype 1, otherheadingelementsareH2andH3. P definesa paragraph. OL orderedlist, unorderedlist isUL. LI list elementin orderedor unorderedlist. LearnHTMLby lookingat source ofwebpages. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 14/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 15/ 33Accepting Data from Users Toaccept data from users, threeelementsare generallyused: FORM containsall thecode relatedto a form. Its purposeisto accept userinputin a systematic and structured manner. INPUT specifies thecode usedto create the form controls that accept user input. SELECT usedto display lists in aform. Designingandcreating interactive webpages is similar to GUI design. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 16/ 33theFORM element A form is a collection oftext boxes, radiobuttons, check boxes,andbuttons. Twoattributes of a form: METHOD isGETorPOST. ACTION is typically used to specify the codethatwill process the theinputdata. Syntax: FORM METHOD="GETorPOST" ACTION="filename" codeoftheform /FORM ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 17/ 33theINPUT element TheINPUTelementis specified inside aFORMelement. TheINPUTelementsconsists of controls, such as text boxes, buttons, radiobuttons,andcheck boxes. Eachof these controls canhave attributes: TYPE specifies type ofcontrol to accept userinput. NAME specifies nameof a control, for identification. VALUE holdsvalue enteredby user, or default. Five typesofcontrol: (1) submit button; (2) text boxes; (3) radio buttons; (4) check boxes; (5) comboboxes. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 18/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 19/ 33ClientSide / ServerSide scripting We distinguish between ClientSideScripting: processed bybrowser advantage: savestime of the server ServerSideScripting: processed byserver neededfor synchronization, modificationof data server time is then the time Pythonis a powerfulserverside scripting language. Thecgimodulehasto beimported, in orderto communicatethe datafrom client. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 20/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 21/ 33Prompting for a Number 1 Thedisplayedwebpageusesaformelement. 2 Theformcontainstwoinputelements 3 After the user hitssubmit,a Pythonscript will run. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 22/ 33the User enters a Number Observethe URL:it containsthedata. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 23/ 33the User enters Nothing Theuser receivesan errormessage. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 24/ 33Form and Input Elements HTML HEAD TITLE MCS 275 Lec 21: give a number /TITLE /HEAD BODY FORM action="http://localhost/cgibin/givenumber.py" give a number: INPUT type="text" name="number" size ="8" INPUT type="submit" /FORM /BODY /HTML ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 25/ 33theactionofpython /usr/bin/python """ Accepts a number from a form. """ import cgi form = cgi.FieldStorage() print("ContentType: text/plain\n") try: n = form’number’.value print("your number is"+n) except KeyError: print("please enter a number") ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 26/ 33Introduction to CGI Programming 1 PythonScripts in Browsers ApacheandLAMP dynamicwebpages 2 InternetBasics HTTP:GETandPOSTmethods FORMto accept userdata serverside scripting 3 Interactive Web Pages acceptinguser input greatestcommondivisor on theweb ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 27/ 33GCD on the Web web computingofthe greatestcommon divisor Thehtml codeextendsnaturally. Whentheusersubmitsthenumbers,theirgreatestcommondivisor will becomputedanddisplayed. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 28/ 33Output of Web GCD Eucliddoesweb computing Which computerdoesthe computation ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 29/ 33The HTML Code HTML HEAD TITLE MCS 275 Lec 21: web gcd /TITLE /HEAD BODY FORM action="http://localhost/cgibin/webgcd.py" P give first number: input type="text" name="A" size ="40" /P Pgive second number: input type="text" name="B" size ="40" /P P input type="submit" /P /FORM /BODY /HTML ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 30/ 33The Python Script /usr/bin/python """ Script to compute the greatest common divisor of two numbers entered via a form. """ import cgi form = cgi.FieldStorage() print("ContentType: text/plain\n") try: x = form’A’.value print("your first number is " + x) except KeyError: print("please enter a first number") try: y = form’B’.value print("your second number is " + y) except KeyError: print("please enter a second number") ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 31/ 33The Python Script continued def gcd(alpha, beta): """ Returns the greatest common divisor of the numbers alpha and beta. """ rest = alpha beta if rest == 0: return beta else: return gcd(beta, rest) ix = int(x) iy = int(y) print("gcd(d,d) = d" (ix, iy, gcd(ix, iy))) ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 32/ 33Summary + Assignments Exercises: 1 Makeyour ownwebpage,usingpeople.uic.edu. 2 Verifyif Apacheis installedon yourcomputer. Install Apacheif necessary. 3 Designa webinterface to convert poundsinto kilograms and kilogramsinto pounds. 4 Take the scriptfacnum.pyofLecture 1 andwrite a webinterface for it. ProgrammingTools (MCS 275) introductionto CGI L21 27February2017 33/ 33
Website URL
Comment