Documente Academic
Documente Profesional
Documente Cultură
Objective
To write “handlers” that respond to HTTP requests that matches particular criteria and go over
the basics of writing a simple web service with Tornado using Python and Anaconda [Spyder
(Python 3.7)]
Material
Procedures
3. Open Anaconda [Spyder (Python 3.7)] and type this source code and save as hello.py.
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, Tornado")
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/", MainHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Syntax Description
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
port - will listen on for HTTP requests, If the user doesn’t specify a value, it defaults to 8000
help parameter – the program will print out all of the option you’ve defined, along with the text you
specified with the help parameter in the call define.
type parameter – to do basic type checking on the parameter, throwing an error if a value of an
inappropriate type is given, allows the user to use an integer port argument, which can access in the
body of the program as option.port
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, Tornado")
get method – this handler will respond only to HTTP GET request, GET is used to request data from a
specified resource.
self.write - another method of the RequestHandler class, which takes a string as a parameter and writes
that string into the HTTP response.
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/", MainHandler)])
list of tuples – with each tuple containing a regular expression to match as its first member the root
resource (“/”) and a RequestHandler class as its second member
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Data
Question
Make a sample Resume that display including your Personal Information and Educational
Attainment in http://localhost:8000/.
Observation
Conclusion
Experiment No.2
Objective
To take a look at some of the more powerful features that you’re likely to use when building
web applications.
To allow you to use nearly any template language supported by Python, it contains a
lightweight, fast, and flexible templating language within the tornado module.
Material
Procedures
1. Open Anaconda [Spyder (Python 3.7)] and type this source code and save as electronics.py.
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import os.path
class SearchHandler(tornado.web.RequestHandler):
def get(self):
self.render('search.html')
class DeviceHandler(tornado.web.RequestHandler):
def post(self):
device = self.get_argument('device',' ')
if device == "resistor":
self.render('Resistor.html')
else:
self.render('error.html', components=device)
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', SearchHandler), (r'/components', DeviceHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates")
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Syntax Description
import os.path
os.path - the path module suitable for the operating system Python is running on
self.render('search.html')
.render – this code will cause Tornado to find a file called “search.html” in the templates directory, read
its contents, and send it to the browser
def post(self):
post method - is used to send data to a server to create/update a resource, one of the most common
HTTP methods
template_path=os.path.join(os.path.dirname(__file__), "templates")
template_path parameter - tells Tornado where to look for template files
if device == "resistor":
self.render('Resistor.html')
else:
self.render('error.html', components=device)
search.html
<!DOCTYPE html>
<html>
<head><title>Electronic Components </title></head>
<body>
<h1>Electronic Components</h1>
<form method="post" action="/components">
error.html
<!DOCTYPE html>
<html >
<head>
<title>Error</title>
<style type='text/css'>
p1.upper {
text-transform: uppercase;
}
</style>
</head>
<body>
<h1>ERROR</h1>
<p>We're sorry we could not fulfill your request for
<p1 class='upper example'><b>{{components}}</b> </p1>
</p>
</body>
</html>
Resistor.html
<!DOCTYPE html>
<html>
<head><title>Electronic Components </title></head>
<body>
<h1>Resistor</h1>
</body>
</html>
Tags Description
<!DOCTYPE html> Defines the document type
<b> Defines bold text
<br> Defines a single line break
<body> Defines the document's body
<form> Defines an HTML form for user input
<h1> to <h6> Defines HTML headings
<head> Defines information about the document
<html> Defines the root of an HTML document
<input> Defines an input control
<title> Defines a title for the document
<p> Defines a paragraph
<style> Defines style information for a document
self.render('error.html', components=device)
<b>{{components}}</b>
The words enclosed in double curly brackets are placeholders, which we want to replace with real
values components when the template is rendered. We can specify what values will be interpolated in
the HTML in their place by passing keyword arguments to the render function, with the keywords
corresponding to names of the placeholders.
3. Run the program F5 and go to any browser and type http://localhost:8000/.
Data
Try to make a condition that allow the “Resistor” and “RESISTOR” valid as the enter device and
remove the “note:use lower case”.
Question
1. Why localhost:8000 change into localhost:8000/components when you clicked search button?
Task
Add another device such as diode, capacitor and transistor in Enter device that allows UPPERCASE,
lowercase and Capitalize of word and make your own definition.
Observation
Conclusion
Experiment No. 3
Extending Templates
Objective
To make use of repurposable content like headers, footers, and layout grids by extending
Tornado templates using Anaconda [Spyder (Python 3.7)]
Material
Procedures
1. Open Anaconda [Spyder (Python 3.7)] and type this source code and save as guessword.py.
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
class JumbleHandler(tornado.web.RequestHandler):
def get(self):
self.render('jumble.html'
class CorrectHandler(tornado.web.RequestHandler):
def post(self):
word1 = self.get_argument('word1',' ')
if word1 == "resistor":
self.render('correct.html')
else:
self.render ('incorrect.html')
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', JumbleHandler), (r'/correct', CorrectHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates")
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
2. Create three HTML files jumble.html, correct.html and incorrect.html using Anaconda [Spyder
(Python 3.7)] and save in a folder templates.
jumble.html
<!DOCTYPE html>
<html>
<head><title>Guess Word</title></head>
<body>
<h1>Guess Word</h1>
<form method="post" action="/correct">
<p><b>"SERTORIS"</b></p>
<p>NOTE: Use lowercase to type the correct answer.</p>
<p>Guess word: <input type="text" name="word1"> </p>
<input type="submit" class="button button.large button-primary" value= "Check">
</form>
{% block word1 %}
{% end %}
</body>
</html>
correct.html
{% extends "jumble.html" %}
{% block word1 %}
<script>alert('You are Correct')</script>
{% end %}
incorrect.html
{% extends "jumble.html" %}
{% block word1 %}
<script>alert('Try Again, Incorrect')</script>
{% end %}
Syntax Description
{% extends "jumble.html" %}
Extend an existing template "jumble.html"
{% block word1 %}
{% end %}
A block statement encapsulates some element of a template that you might want to change when you
extend it
3. Run the program F5 and go to any web browser and type http://localhost:8000/.
Data
Question
1. What do you think are the advantages of extending templates in web development?
Task
Make your own dictionary that extends the definition in your main html.
Observation
Conclusion
Experiment No. 4
Database
Objective
To use MongoDB as the database, and pymongo as the Python driver to connect to MongoDB.
Material
Procedures
1. Install MongoDB Compass Community and install pymongo by Anaconda prompt (Anaconda3)
and type pip install pymongo.
2. Open MongoDB Compass Community and set Hostname = localhost, port =27017, Favorite
Name = database and click Create Favorite and CONNECT.
3. Open Anaconda [Spyder (Python 3.7)] and type this source code and save as rtustudentfiles.py.
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pymongo
import os.path
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r"/", StudentHandler),(r"/student", SuccessHandler)]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
)
class StudentHandler(tornado.web.RequestHandler):
def get(self):
self.render('student.html')
class SuccessHandler(tornado.web.RequestHandler):
def post(self):
number=self.get_argument('number',"")
if number=="2014-105113":
coll = self.application.db.students
stud_num= coll.find_one({"Student_number":"2014-105113"})
name= stud_num["Fullname"]
self.render('success.html',name1=name)
else:
self.render('error.html',errornum=number)
if __name__ == '__main__':
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Syntax Description
import pymongo
pymongo - tools for interacting with MongoDB database from Python
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r"/", StudentHandler),(r"/student", SuccessHandler)]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
)
self.db = conn["RTU"]
db = conn["RTU"]
.db - create database name “RTU”
db.students.insert_one({"Student_number": "2014-
105113", "Fullname":"Macunay, Domingo C. Jr."})
db.students.insert_one({"Student_number": "2015-100965", "Fullname":"Ursua, Arvie Kate C."})
insert_one – method to insert a record, or document as it is called in MongoDB, into a collection
“students”
coll = self.application.db.students
db.students - create a collection in MongoDB name students
stud_num= coll.find_one({"Student_number":"2014-105113"})
find_one - methods to find data in a collection
4. Create three HTML files student.html, success.html and error.html using Anaconda [Spyder
(Python 3.7)] and save in a folder templates.
student.html
<!DOCTYPE html>
<html>
<head><title>RTU Student Files</title></head>
<body>
<h1>RTU Student Files</h1>
<form method="post" action="/student">
<p><b>Student number:</b> <input type="text" name="number"> </p>
success.html
{% extends "student.html" %}
{% block content %}
<h1>{{name1}}</h1>
{% end %}
error.html
{% extends "student.html" %}
{% block content %}
<style type='text/css'>
p1.upper {
text-transform: uppercase;
}
</style>
<p>Sorry but we are not able to provide this at the moment.
<p1 class='upper example'><b>ERROR "{{errornum}}"</b> </p1>
</p>
{% end %}
5. Run the program F5 and go to any web browser and type http://localhost:8000/.
Data
Try to add your student number and name. It should be stored in MongoDB and searchable.
Questions
Task
Make a sample dictionary consist of 5 words that can search the definition and stored the data in
MongoDB.
Observation
Conclusion
Experiment No. 5
Objective
To use MongoDB as the database, and pymongo as the Python driver to connect to MongoDB.
To make it possible to create, save and search information by making HTTP requests to the web
service.
Material
Procedures
1. Open Anaconda [Spyder (Python 3.7)] and type this source code and save as saveandsearch.py.
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pymongo
import os.path
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r"/", StudentHandler),(r"/save", SaveHandler),(r"/search", SearchHandler)]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
)
class SaveHandler(tornado.web.RequestHandler):
def post(self):
number=self.get_argument('number',"")
fullname=self.get_argument('fullname',"")
else:
self.render('student.html')
class SearchHandler(tornado.web.RequestHandler):
def post(self):
snum=self.get_argument('snum',"")
coll = self.application.db.students
stud_num=coll.find_one({"Student_number":snum})
if stud_num:
coll = self.application.db.students
stud_num=coll.find_one({"Student_number":snum})
full=stud_num["Fullname"]
self.render('success.html', full1=full)
else:
self.render('error.html', errornum=snum)
if __name__ == '__main__':
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
2. Create four HTML files student.html, save.html, success.html and error.html using Anaconda
[Spyder (Python 3.7)] and save in a folder templates.
student.html
<!DOCTYPE html>
<html>
<head><title>RTU Student Files</title></head>
<body>
<h1>RTU Student Files</h1>
<form method="post" action="/save">
<p><b>Student number:</b> <input type="text" name="number"> </p>
<p><b>Fullname:</b> <input type="text" name="fullname"> </p>
save.html
<!DOCTYPE html>
<html>
<head><title>RTU Student Files</title></head>
<body>
<h1>Successfully Save</h1>
<form method="post" action="/search">
<p><b>Student number:</b> <input type="text" name="snum"> </p>
{% extends "save.html" %}
{% block save %}
<h1>{{full1}}</h1>
{% end %}
error.html
{% extends "save.html" %}
{% block save %}
<style type='text/css'>
p1.upper {
text-transform: uppercase;
}
</style>
<p>
<p1 class='upper example'><b>NOT FOUND! ERROR "{{errornum}}"</b><br> <br></p1>
<p2>Save your details here</p2>
<a href ="http://localhost:8000/">http://localhost:8000/</a>
</p>
{% end %}
3. Run the program F5 and go to any web browser and type http://localhost:8000/.
Data
Check the MongoDB. Are the student number and full name stored in MongoDB?
Instead of searching the student number try to change the code that will search a full name and it
should display the student number.
Task
Make a sample dictionary that can add a word and definition and can search the meaning of the
word added.
Observation
Conclusion
Experiment No. 6
Objective
To use MongoDB as the database, and pymongo as the Python driver to connect to MongoDB.
To make it possible to create and access existing account save in MongoDB by making HTTP
requests to the web service.
Material
Procedures
1. Open MongoDB Compass Community and set Hostname = localhost, port =27017, Favorite
Name = database and click Create Favorite and CONNECT.
2. Open Anaconda [Spyder (Python 3.7)] and make your own source code and save as
createandaccess.py.
3. Create four HTML files create.html, signup.html, login.html, success.html and error.html using
Anaconda [Spyder (Python 3.7)] and save in a folder templates.
create.html
This html shows when you clicked Sign up button.
signup.html
When you clicked Create button the data should store in MongoDB and will go to loginh.html.
This html shows when you clicked Log in button.
4. Run the program F5 and go to any web browser and type http://localhost:8000/.
Observation
Conclusion