Skip to content
Snippets Groups Projects
Commit e8321369 authored by System Administrator's avatar System Administrator
Browse files

week 7 lab

parent 79627d17
No related merge requests found
File added
#!/usr/bin/env python3
from myutils import db_connect
from datetime import datetime
# make bson ObjectId class available for referencing
# bson objects inside a mongo query string
from bson.objectid import ObjectId
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
# connect to database
db = db_connect()
# output some header html
print("Content-Type: text/html\n")
print("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello Caflucks</title>
</head>
<body>
<h1>Welcome to Catflucks</h1>""")
# get one random document from images collection
result = db.images.aggregate(
[{ '$sample': { 'size': 1 } }]
)
# if a result came back
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']
# 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()
print("""<p>You are viewing a random image of a cat.</p>
<img src="{}" alt="{}" width=500>
<p>This poor cat has been flucked {} times already.</p>
<a href="/cgi-bin/myserve_cat.py" title="serve cat">Serve new cat</a>
""".format( img_src, img_alt, str(num_flucks) ))
else:
print("<p>Oops. Something went wrong!</p>")
# output a form with skip/fluck buttons
print("""<form method="POST" action="/cgi-bin/myserve_cat.py">
<input type="hidden" value="{}" name="img_id">
<input name="btn_skip" type="submit" value="Skip">
<input name="btn_fluck" type="submit" value="Fluck">
</form>""".format( img_id ))
# check if either button clicked and insert a fluck in the database
if 'btn_fluck' in form:
result = db.flucks.insert( {
"image_id":ObjectId(form['img_id'].value),
"is_flucked":1,
"timestamp":datetime.now().timestamp()
} )
elif 'btn_skip' in form:
result = db.flucks.insert( {
"image_id":ObjectId(form['img_id'].value),
"is_flucked":0,
"timestamp":datetime.now().timestamp()
} )
# output some footer html
print("</body></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():
""" Provides a connection to mongoDB database
Returns:
Object: A handle to a mongoDB database
"""
# try to create instance of MongoClient object
try:
client = MongoClient('mongodb://localhost:27017/')
except:
print("Error: failed to create mongo client")
raise
# if we have a mongo client...
else:
# switch to the specified database
db = client.catflucks
# return a handle to the database
return db
File added
{ "indexes" : [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "catflucks.accounts" } ] }
\ No newline at end of file
File added
{ "indexes" : [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "catflucks.flucks" } ] }
\ No newline at end of file
File added
{ "indexes" : [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "catflucks.images" } ] }
\ No newline at end of file
File added
#!/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'
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