Skip to content
This repository was archived by the owner on Dec 10, 2018. It is now read-only.

Small changes(Comments, argparse, and port) #47

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 34 additions & 37 deletions sleepymongoose/httpd.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import os.path, socket
import urlparse
import cgi
import getopt
import argparse
import sys

try:
Expand Down Expand Up @@ -78,21 +78,28 @@ class MongoHTTPRequest(BaseHTTPRequestHandler):
def _parse_call(self, uri):
"""
this turns a uri like: /foo/bar/_query into properties: using the db
foo, the collection bar, executing a query.
foo, the collection bar, executing a query. The last uri segment must start with '_'

returns the database, collection, and action
"""
parts = uri.split('/')

# operations always start with _
# here the returned values follow the format of (database, collection, action/func_name)
if parts[-1][0] != '_':
# if the last segment of the uri doesn't end with an underscore return None for all
return (None, None, None)

if len(parts) == 1:
# if only one folder down ex: http://localhost:port/_hello then the database is admin and the action is the last segment;
# in our example _hello
return ("admin", None, parts[0])
elif len(parts) == 2:
# if url is like http:localhost:port/_greetings/_goodbye, the database is _greetings and the action is _goodbye
return (parts[0], None, parts[1])
else:
# if the uri is longer than two levels deep and the last segment ends with an '_' the database is the first segment,
# the collection is the second segment up to the but not including the last one joined by periods,
# and the action is the last segment
# example: http://localhost:27080/foo/bar/bazz/sazz/_hello returns ('foo', 'bar.bazz.sazz', '_hello')
return (parts[0], ".".join(parts[1:-1]), parts[-1])


Expand Down Expand Up @@ -237,7 +244,7 @@ def serve_forever(port):

MongoHandler.mh = MongoHandler(MongoHTTPRequest.mongos)

print "listening for connections on http://localhost:27080\n"
print "listening for connections on http://localhost:%s\n" % (port)
try:
server.serve_forever()
except KeyboardInterrupt:
Expand All @@ -252,38 +259,28 @@ def setup(self):
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)


def usage():
print "python httpd.py [-x] [-d docroot/dir] [-s certificate.pem] [-m list,of,mongods]"
print "\t-x|--xorigin\tAllow cross-origin http requests"
print "\t-d|--docroot\tlocation from which to load files"
print "\t-s|--secure\tlocation of .pem file if ssl is desired"
print "\t-m|--mongos\tcomma-separated list of mongo servers to connect to"


def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "xd:s:m:", ["xorigin", "docroot=",
"secure=", "mongos="])

for o, a in opts:
if o == "-d" or o == "--docroot":
if not a.endswith('/'):
a = a+'/'
MongoHTTPRequest.docroot = a
if o == "-s" or o == "--secure":
MongoServer.pem = a
if o == "-m" or o == "--mongos":
MongoHTTPRequest.mongos = a.split(',')
if o == "-x" or o == "--xorigin":
MongoHTTPRequest.response_headers.append(("Access-Control-Allow-Origin","*"))

except getopt.GetoptError:
print "error parsing cmd line args."
usage()
sys.exit(2)

MongoHTTPRequest.serve_forever(27080)
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--docroot',help="allows you to specify the location of your files. Defaults to the sleepy.mongoose directory")
parser.add_argument('-s', '--secure', help="location of .pem file if ssl is desired")
parser.add_argument('-m', '--mongos', help="comma-separated list of mongo servers to connect to")
parser.add_argument('-x', '--xorigin', help="allow cross-origin http requests")
parser.add_argument('-p', '--port', help="port where the interface will be served on", type=int)
args = parser.parse_args()
if args.docroot:
if not args.docroot.endswith('/'):
args.docroot = args.docroot + '/'
MongoHTTPRequest.docroot = args.docroot

if args.secure:
MongoServer.pem = args.secure

if args.mongos:
MongoHTTPRequests.mongos = args.mongos.split(',')

if args.xorigin:
MongoHTTPRequest.response_headers.append(("Access-Control-Allow-Origin","*"))
MongoHTTPRequest.serve_forever(args.port or 27080)
if __name__ == "__main__":
main()