Commit 4f9811d9 authored by Sorrel Harriet's avatar Sorrel Harriet
Browse files

adding code resources for lab 7

parent 31e34857
"""
Define global config variables here.
These will be accessible from other
scripts, so we only need to set them
here.
"""
# app configurables stored in a config object
config = {
"SERVER_ADDRESS": "localhost",
"PORT": 27017,
"USER": "",
"PASS": "",
"DATABASE_NAME": "catflucks",
"TEMPLATE_DIR": "templates/"
}
#!/usr/bin/env python3
from bson.objectid import ObjectId
import cgi
import cgitb
cgitb.enable()
from config import config
import utils
# connect to database
db = utils.db_connect( config )
# render header HTML
print( utils.render_template( config['TEMPLATE_DIR'] + 'header.html') )
# get the form data
form = cgi.FieldStorage()
# get one random document from images collection
result = db.images.aggregate(
[{ '$sample': { 'size': 1 } }]
)
# if a result came back, do stuff with it...
if result:
# iterate through objects in the cursor (should only be 1)
for img in result:
# pull out the img url and alt text
img_src = img['url']
img_alt = img['alt']
img_id = img['_id']
# render serve_cat template, passing it dynamic data
print( utils.render_template( config['TEMPLATE_DIR']+'serve_cat.html', data=[img_src, img_alt] ) )
# find and count flucks with matching img_id and where is_flucked is 1
num_flucks = db.flucks.find( {"image_id": ObjectId(img_id), "is_flucked":1} ).count()
# render cat_stats template, passing it dynamic data
print( utils.render_template( config['TEMPLATE_DIR']+'cat_stats.html', data=[num_flucks] ) )
# render form_fluck template, passing it dynamic data
print( utils.render_template( config['TEMPLATE_DIR']+'form_fluck.html', data=["/cgi-bin/splash.py",img_id] ) )
else:
print("<p>Oops. Something went wrong!</p>")
# render cat_stats template, passing it the dynamic data
print( utils.render_template( config['TEMPLATE_DIR']+'footer.html' ) )
#!/usr/bin/env python3
"""
This module provides a set of reuseable utility functions
This is a Google style docstring by the way.
Read more about them here:
https://www.python.org/dev/peps/pep-0257/
"""
from pymongo import MongoClient
def db_connect( config ):
""" Provides a connection to mongoDB database
Returns:
Object: A handle to a mongoDB database
"""
# try to create instance of MongoClient object
try:
client = MongoClient( config['SERVER_ADDRESS'], config['PORT'] )
except:
# raise a custom exception
raise Exception("Problem connecting to the database!")
# if we have a mongo client...
else:
# switch to the specified database
db = client[ config['DATABASE_NAME'] ]
# check a handle was returned
if db is not None:
# return a handle to the database
return db
def render_template( temp_path, data=[] ):
""" Reads in an HTML string from file
replacing any placeholders with values
supplied in data list.
Input params:
temp_path: the path to the template file
data: optional list of data values
Returns:
String: A formatted string of HTML
"""
try:
# open and read the template file
with open(temp_path, 'r') as f:
html = f.read()
except:
raise Exception("Could not open template")
else:
if data is not None:
try:
# replace placeholders with data in list
html = html.format(*data)
except:
raise Exception("Problem parsing data to template")
return html
#!/usr/bin/env python3
# above 'she-bang' line makes the script executable from command line
""" A Simple Web Server
Run with ./simpleServer.py
Make sure all cgi scripts are executable
for single script:
chmod +x simpleServer.py
or for a whole directory:
chmod -r +x cgi-bin/
"""
import http.server # import http.server module
import cgitb; cgitb.enable() # import and enable cgitb module for exception handling
PORT = 8000 # specifies the port number to accept connections on
server = http.server.HTTPServer # provides simple web server
handler = http.server.CGIHTTPRequestHandler # provides request handler
server_address = ("", PORT) # specify server directory and port number
handler.cgi_directories = ["/","/cgi-bin","/htbin"] # where CGI scripts will reside in relation to the `server' directory
print("Starting server...") # outputs a message
httpd = server(server_address, handler) # creates the server, passing it the server address and port number, as well as the CGI handler (httpd stands for HTTP Daemon)
print("serving at port", PORT) # outputs a message
httpd.serve_forever() # puts program in infinite loop so that the server can `serve_forever'
<p>This poor cat has been flucked {} times already.</p>
<form method="POST" action="{}">
<input type="hidden" value="{}" name="img_id">
<input name="btn_skip" type="submit" value="Skip">
<input name="btn_fluck" type="submit" value="Fluck">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello Caflucks</title>
</head>
<body>
<h1>Welcome to Catflucks</h1>
<p>You are viewing a random image of a cat.</p>
<img src="{}" alt="{}" width=500>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment