Sunteți pe pagina 1din 29

Experiment No.

Simple Web Services

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

Anaconda [Spyder (Python 3.7)]

Procedures

1. Install Anaconda [Spyder (Python 3.7)]


2. Install Tornado Web Framework by Anaconda prompt (Anaconda3) and type pip install tornado.

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

from tornado.options import define, options


define("port", default= 8000, help="run on the given port", type=int

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

Import various Tornado libraries

tornado.httpserver - very basic keep-alive connections handler


tornado.Ioloop – main event loop for non-blocking sockets
tornado.options - a command line parsing module that lets modules define their own options
tornado.web - provides a simple web framework with asynchronous features that allow it to scale to
large numbers of open connections

from tornado.options import define, options


define("port", default= 8000, help="run on the given port", type=int)

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")

Tornado request handler class

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)])

Create an instance of Tornado’s Application class.

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()

Application object to Tornado’s HTTPServer object

http_server.listen(options.port) - listens to the port specified on the command line


tornado.ioloop.IOLoop.instance().start() - ready to accept HTTP requests.

4. Run the program F5 and go to any browser and type http://localhost:8000/.

Try to change the port “default” in any number respective to http://localhost.

What did you notice?

Data

Question

1. How the word “Hello Tornado” display in web page?


Task

Make a sample Resume that display including your Personal Information and Educational
Attainment in http://localhost:8000/.

Observation

Conclusion
Experiment No.2

Forms and Templates

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

Anaconda [Spyder (Python 3.7)]

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

from tornado.options import define, options


define("port", default=8000, help="run on the given port", type=int)

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

Tornado request handler class

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

device = self.get_argument('device',' ')


get_argument - which we use here to get an argument ‘device’,’ ’ from the query string

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)

The if-elif-else statement is used to conditionally execute a statement or a block of statements.


Conditions can be true or false, execute one thing when the condition is true, something else when
the condition is false.
2. Create three HTML files search.html, error.html and Resistor.html using Anaconda [Spyder
(Python 3.7)] and save in a folder templates.

search.html

<!DOCTYPE html>
<html>
<head><title>Electronic Components </title></head>
<body>
<h1>Electronic Components</h1>
<form method="post" action="/components">

<p><b>Enter device:</b> resistor<br>


note: use lower case:
<input type="text" name="device"></p>

<input type="submit" value= "SEARCH">


</form>
</body>
</html>

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>

<p>A <b>resistor</b> is a passive two-


terminal electrical component that implements electrical resistance as a circuit element.
In electronic circuits, resistors are used to reduce current flow, adjust signal levels, to divide voltages
, bias active elements, and terminate transmission lines, among other uses. </p>

</body>
</html>

HTML Tags Description

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

<form method="post" action="/components">


Contents will be sent to "/components" in a POST request when the user clicks the "SEARCH" button.

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

Anaconda [Spyder (Python 3.7)]

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

from tornado.options import define, options


define("port", default=8000, help="run on the given port", type=int)

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

Anaconda [Spyder (Python 3.7)]

MongoDB Compass Community

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

from tornado.options import define, options


define("port", default=8000, help="run on the given port", type=int)

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"),
)

conn = pymongo.MongoClient("localhost", 27017)


self.db = conn["RTU"]
db = conn["RTU"]
db.students.insert_one({"Student_number": "2014-
105113", "Fullname":"Macunay, Domingo C. Jr."})

tornado.web.Application.__init__(self, handlers, debug=True, **settings)

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"),
)

tornado.web.Application - A collection of request handlers that make up a web application. Instances


of this class are callable and can be passed directly to HTTPServer to serve the application
__init__- This method initialize the values of instance members for the new object

conn = pymongo.MongoClient("localhost", 27017)


pymongo.MongoClient - create a connection to a MongoDB database using “localhost” as hostname
and default port 27017

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>

<input type="submit" class="button button.large button-primary" value= "Search">


</form>
{% block content %}
{% end %}
</body>
</html>

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

1. How MongoDB stores data using Python?

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

Database: Save and Search

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

Anaconda [Spyder (Python 3.7)]

MongoDB Compass Community

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

from tornado.options import define, options


define("port", default=8000, help="run on the given port", type=int)

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"),
)

conn = pymongo.MongoClient("localhost", 27017)


self.db = conn["RTU"]

tornado.web.Application.__init__(self, handlers, debug=True, **settings)


class StudentHandler(tornado.web.RequestHandler):
def get(self):
self.render('student.html')

class SaveHandler(tornado.web.RequestHandler):
def post(self):

number=self.get_argument('number',"")
fullname=self.get_argument('fullname',"")

if number and fullname:


coll = self.application.db.students
coll.insert_one({"Student_number":number,"Fullname":fullname})
self.render('save.html')

elif number ==" " and fullname ==" ":


self.render('student.html')

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>

<input type="submit" class="button button.large button-primary" value= "Save">


</form>
</body>
</html>

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>

<input type="submit" class="button button.large button-primary" value= "Search">


</form>
{% block save %}
{% end %}
</body>
</html>
success.html

{% 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

Database: Sample Account (Create and Access existing account)

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

Anaconda [Spyder (Python 3.7)]

MongoDB Compass Community

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.

login.html success.html show your first name

error.html display error when the data is not found

4. Run the program F5 and go to any web browser and type http://localhost:8000/.

Observation

Conclusion

S-ar putea să vă placă și