HCI Web Applications 4 - Using Flask
Uploaded by adrianwang2003 · 28 May 2024
Preview
Text from the first pagesWeb Applications Name: __________________________ ( ) Class:_________ Date: _________ Lesson 4: Using Flask Instructional Objectives: By the end of this task, you should be able to: ● Use theflask.Flask()constructor to create a Flaskapplication ● Usetheflask.Flask.route()decoratortoassociatefunctionswitheithera static path or a path containing one or more variable sections ● Useflask.Flask.run()to start a Flask application ● Useflask.render_template()to simplify sending oflong HTML responses ● Useflask.redirect()tosendaHTTP302(Found)statuscodeandhave the browser request a different address ● Use theflask.request.formdictionary to retrievedecoded form data ● Usethe Jinja2templatelanguageandflask.url_for()to dynamically generate links and URLs in HTML responses Part 1: Dynamic Web Pages AlthoughwecanusethewebtosimplyrequestforandretrievestaticHTMLandCSSdocuments,the webbecomesmuchmoreusefulif thewebservercancustomiseitsresponsetoeachHTTPrequest.Forexample,thefollowingprogramuseswhatwehavelearntsofaraboutsockets,HTTP, HTMLandCSStogenerateaweb page with random colours and text every time it is requested. Program 1:p01_server_without_flask.py 1234567 import randomimport socket # HTTP uses \r\n to end lines instead of \n.EOL = b'\r\n' # List of possible colours. CPDD Computer Education Unit Version: Nov 20181
Web Applications 891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 COLOURS = ['red', 'orange', 'blue', 'purple','#C0C000', # dark yellow'#00C000' # dark green] # List of possible messages.MESSAGES = ['Hello, World!', 'Computing is Fun', 'Alamak!'] # Start listening for web browser requests on port 8000.listen_socket = socket.socket()listen_socket.bind(('127.0.0.1', 8000))listen_socket.listen() def handle_request(new_socket):# Keep loading request until end of first line (\r\n).request = b''while EOL not in request:received = new_socket.recv(1024)if received == b'':new_socket.close()returnrequest += received # Extract first line and split it into three.# Requested path is always the second part.index = request.index(EOL)first_line = request[:index].decode()path = first_line.split()[1] # Start response with standard HTTP status line.response = b'HTTP/1.1 200 OK' + EOL # Generate CSS document for response if path is '/css'.# Otherwise, generate HTML document for response.if path == '/css':# Generate CSS document.border_colour = random.choice(COLOURS)text_colour = random.choice(COLOURS)body = 'p {{ border: 5px solid {0}; color: {1};'body += 'font-size: 72px; padding: 20px; }}'body = body.format(border_colour, text_colour)body = body.encode() # Append HTTP header fields to response.response += b'Content-Type: text/css' + EOLresponse += b'Content-Length: 'response += str(len(body)).encode() + EOL CPDD Computer Education Unit Version: Nov 20182
Web Applications 5758596061626364656667686970717273747576777879808182838485 else:# Generate HTML document.msg = random.choice(MESSAGES)body = '<!DOCTYPE html>\n<html>'body += '<head><title>{0}</title>'body += '<link rel="stylesheet" href="/css"></head>'body += '<body><p>{0}</p></body></html>'body = body.format(msg).encode() # Append HTTP header fields to response.response += b'Content-Type: text/html' + EOLresponse += b'Content-Length: 'response += str(len(body)).encode() + EOL # Append empty line to response.response += EOL # Append document as message body.response += body # Send the response and close the socket.new_socket.sendall(response)new_socket.close() while True:new_socket, addr = listen_socket.accept() handle_request(new_socket) Runtheprograminthebackground,thenviewhttp://127.0.0.1:8000/inawebbrowser. Reloadthebrowsera fewtimestoseethewebpage’s textandcolourschange each time: How does the program work? 1. Lines 17 to 20 start the server by listening on port 8000. CPDD Computer Education Unit Version: Nov 20183
Web Applications 2. Whena webbrowservisitshttp://127.0.0.1:8000/, it sendsa HTTPrequestviathenewsocketthatisreturnedbyaccept()online83.Thenewsocket is then passed to thehandle_request()functionon line 23. 3. Lines24 to 37 readtheHTTPrequestuntila lineendingis detected.However, ifrecv()everreturnsanemptybytesobject,theconnectionhasbeenclosedso the programstopsprocessingthe requestimmediately.Otherwise, it extracts thepathcomponent from thefirst line of the request. 4. Line 40 starts a new HTTP response with only a status line. 5. Ifpathmatches'/css'exactly, lines45to 51generatea CSSdocumentusingrandomcoloursandstoreit inbody. Lines53to56thengeneratetherequired HTTP header fields and append them to the response. 6. Otherwise,lines58to64generatea HTMLdocumentcontaininga randomphraseandstoretheHTMLdocumentinbody. Lines66to69thengeneratethe required HTTP header fields and append them to the response. 7. RegardlessofwhetheraCSSorHTMLdocumentwasgenerated,lines71to78endtheheaderfieldswithanemptyline,appendthegenerateddocumentto the response and send the completed response back to the web browser. 8. Finally, line79closesthesocketsotheservercanhandlethenextHTTPrequest and so on until Ctrl-C is pressed. Writingdynamicwebpagesinthiswaycanbecomplexandtedious.Inparticular,p01_server_without_flask.pyrequirestheprogrammerto parseor constructHTTPrequest/statuslinesandheaderfieldsto followtheHTTPstandard.It alsorequirestheprogrammerto assemblelongpiecesof HTMLandCSScodefromPython strings. Insteadof havingtheprogrammerspendtimeonthesetediousanderror-pronetasks,it is usuallybetterto usea frameworkinstead.A frameworkistypicallyamoduleor librarywithready-madegenericsolutionsthata programmercanselectivelyoverridetocustomisecertainbehaviours.Thisletstheprogrammergetmoredoneinlesstimeastheframeworkalreadyprovidesaworkingsolutionthattheprogrammer only needs to configure or customise for his or her needs. 1 The following program runs a web server athttp://127.0.0.1:5000/thatsimply repeats the first line of each HTTP request back to the browser. import socket EOL = b'\r\n' listen_socket = socket.socket()listen_socket.bind(('127.0.0.1', 5000)) CPDD Computer Education Unit Version: Nov 20184
Web Applications listen_socket.listen() def handle_request(new_socket):request = b''while EOL not in request:received = new_socket.recv(1024)if received == b'':returnrequest += receivedindex = request.index(EOL)first_line = request[:index] response = b'HTTP/1.1 200 OK' + EOLresponse += b'Content-Type: text/plain' + EOLresponse += b'Content-Length: 'response += str(len(first_line)).encode() + EOLresponse += EOLresponse += first_line new_socket.sendall(response)new_socket.close() while True:new_socket, addr = listen_socket.accept() handle_request(new_socket) Run the program and visit each of the URLs below to tabulate the output thatis displayed in the browser. An example has been completed for you. No. URL Output e.g. http://127.0.0.1:5000/helloGET /hello HTTP/1.1 1 http://127.0.0.1:5000/ 2 http://127.0.0.1:5000/100/200 3 http://127.0.0.1:5000/200/300/ 4 http://127.0.0.1:5000//300//400// 5 http://127.0.0.1:5000/?key=value CPDD Computer Education Unit Version: Nov 20185
Web Applications 6 http://127.0.0.1:5000/#fragment 7 http://127.0.0.1:5000/?key#hash Part 2: The Flask Framework Tocreatedynamicwebsites,wecanuseawebapplicationframeworknamedFlask.Unliketheotherlibrariesandmodulesthatwehaveusedsofar, FlaskisnotbuiltintoPythonandtypicallyneedstobeinstalledseparately. However, itshouldalreadybeinstalled for you in the computers at your school. To check if Flask is installed, run the following line of Python (bold text only): >>>import flask Ifyougetanerroronyourhomecomputer, youmayneedtoinstallFlaskbystartingCommand Prompt or PowerShell as an administrator and running (bold text only): PS C:\Users\user>pip3 install flask Toruntheabovecommandsuccessfully, youmusthaveInternetaccessandPythonmustbeincludedinyourPATH,whichisthelistofdirectoriesthatCommandPromptorPowerShellautomaticallysearchesthroughwhenlookingforacommand.SearchtheInternetoraskyourteacherforhelpif youareunabletoinstallFla
Content continues in the PDF. Download PDF
Related notes
- NYJC 2026 Prelim P2Exam Papers · 2026
- NYJC 2026 Prelim P1Exam Papers · 2026
- DHS 2026 Y6 H2 Computing Prelim Paper 2_finalExam Papers · 2026
- ACJC 2026 JC2 Computing Prelim Paper 2 (Practical)Exam Papers · 2026
- 2026_NJC Prelim_Computing_P2.pdfExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P2_finalExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_markschemeExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_finalExam Papers · 2026
- 2026 ACJC Prelim Computing Paper 2Exam Papers · 2026
- 2024 ACJC Computing PromoExam Papers · 2024
- 2023 ACJC Promo QPExam Papers · 2023
- 2022 ACJC Computing Promo Paper 2Exam Papers · 2022
- See all H2 Computing notes

