summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPepper <pepper@scannerjammer.com>2015-09-27 00:03:42 -0400
committerPepper <pepper@scannerjammer.com>2015-09-27 00:03:42 -0400
commit30126dfc2877a82b8af02d68ca3b155068d551dd (patch)
treea706d699cd1e1f50c2007e69d6ca9ba96819eaed
parentff31f2c4cf1792df351359f1749f63b3d0cce23b (diff)
done linting...just need to wrap up and publish
-rw-r--r--config.py7
-rw-r--r--lib/db.py68
-rw-r--r--lib/param/__init__.py76
-rw-r--r--lib/param/bool_.py2
-rw-r--r--lib/param/color.py2
-rw-r--r--lib/param/enum.py2
-rw-r--r--lib/param/float_.py2
-rw-r--r--lib/param/img_url.py179
-rw-r--r--lib/param/int_.py39
-rw-r--r--lib/param/json.py2
-rw-r--r--lib/param/param.py59
-rw-r--r--lib/param/raw.py16
-rw-r--r--lib/param/string.py32
-rw-r--r--lib/params.py3
-rwxr-xr-xlib/pb/landscape/__init__.py68
-rw-r--r--lib/server.py139
-rw-r--r--run_module_examples.py5
-rw-r--r--run_server.py3
18 files changed, 374 insertions, 330 deletions
diff --git a/config.py b/config.py
index b6f11c2..4eed880 100644
--- a/config.py
+++ b/config.py
@@ -29,3 +29,10 @@ AWS_SECRET_ACCESS_KEY = 'Dzlzh77U6n2BgQmOPldlR/dRDiO16DMUrQAXYhYc'
BUCKET_NAME = 'i.asdf.us'
SPECIAL_DOWNLOADERS = [ "ryz pepper RICHARD_GIOVANNI dmgk" ]
SPECIAL_DOWNLOADERS_MAX_SIZE = 100000
+
+
+#database
+DB_HOST = "lalalizard.com"
+DB_USER = "asdfus"
+DB_PASSWORD = "gTYgT&M6q"
+DB_NAME = "asdfus"
diff --git a/lib/db.py b/lib/db.py
index c6286ad..a236344 100644
--- a/lib/db.py
+++ b/lib/db.py
@@ -1,11 +1,9 @@
# coding: utf-8
+"""all database connections and logic goes here"""
+from config import DB_HOST, DB_USER, DB_PASSWORD, DB_NAME
import time, sys
-HOST = "lalalizard.com"
-USER = "asdfus"
-PASSWORD = "gTYgT&M6q"
-DATABASE = "asdfus"
-from sqlalchemy import Column, Integer, LargeBinary, String, create_engine, sql
+from sqlalchemy import Column, Integer, LargeBinary, String, create_engine, sql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
_NULL = sql.null()
@@ -14,6 +12,7 @@ Base = declarative_base()
metadata = Base.metadata
class ImCmd(Base):
+ """defines the table class"""
__tablename__ = 'im_cmd'
id = Column(Integer, primary_key=True)
date = Column(Integer)
@@ -28,33 +27,34 @@ class ImCmd(Base):
tag = Column(String(50))
class Db(object):
- def __init__(self):
- engine = create_engine('mysql://{}:{}@{}/{}'.format(
- USER,
- PASSWORD,
- HOST,
- DATABASE
- ))
- self.Session = sessionmaker(bind=engine)
+ """wrapper for all db methods"""
+ def __init__(self):
+ engine = create_engine('mysql://{}:{}@{}/{}'.format(
+ DB_USER,
+ DB_PASSWORD,
+ DB_HOST,
+ DB_NAME
+ ))
+ self.Session = sessionmaker(bind=engine)
- def insert_cmd ( self, **kwargs):
- try:
- session = self.Session()
- _entry_data = {
- 'date' : kwargs.get("date", int(time.time())),
- 'remote_addr' : kwargs['remote_addr'] or _NULL,
- 'name' : kwargs['username'] or _NULL,
- 'url' : kwargs['username'] or _NULL,
- 'dir' : kwargs['directory'] or _NULL,
- 'oldfile' : kwargs['oldfile'] or _NULL,
- 'newfile' : kwargs['newfile'] or _NULL,
- 'cmd' : kwargs['cmd'] or _NULL,
- 'dataobj' : kwargs['dataobj'] or _NULL,
- 'tag' : kwargs['tag'] or _NULL
- }
- session.add(ImCmd(**_entry_data))
- session.commit()
- #FIXME session.close()....
- except Exception as e:
- sys.stderr.write("Unable to commit database entry\n");
- sys.stderr.write(str(e))
+ def insert_cmd(self, **kwargs):
+ try:
+ session = self.Session()
+ _entry_data = {
+ 'date' : kwargs.get("date", int(time.time())),
+ 'remote_addr' : kwargs['remote_addr'] or _NULL,
+ 'name' : kwargs['username'] or _NULL,
+ 'url' : kwargs['username'] or _NULL,
+ 'dir' : kwargs['directory'] or _NULL,
+ 'oldfile' : kwargs['oldfile'] or _NULL,
+ 'newfile' : kwargs['newfile'] or _NULL,
+ 'cmd' : kwargs['cmd'] or _NULL,
+ 'dataobj' : kwargs['dataobj'] or _NULL,
+ 'tag' : kwargs['tag'] or _NULL
+ }
+ session.add(ImCmd(**_entry_data))
+ session.commit()
+ #FIXME session.close()....
+ except Exception as e:
+ sys.stderr.write("Unable to commit database entry\n")
+ sys.stderr.write(str(e))
diff --git a/lib/param/__init__.py b/lib/param/__init__.py
index 10ea7a6..4f3daba 100644
--- a/lib/param/__init__.py
+++ b/lib/param/__init__.py
@@ -1,65 +1,11 @@
-import time
-import sys
-
-from config import WORKING_DIR
-
-class BadParamError(Exception):
- pass
-
-
-class Param(object):
- def __init__(self, classname="", **kwargs):
- self._working_dir = WORKING_DIR
- self._now = kwargs.get("now", str(int(time.time())));
- self._classname = classname
- for key, value in kwargs.items():
- setattr(self, key, value)
-
- def __nonzero__(self):
- return True if self.value else False
-
- def __str__(self):
- return str(self.value)
-
- def __eq__(self, other):
- return self.value == other
-
- def __ne__(self, other):
- return self.value != other
-
- def set_val(self, value):
- try:
- self.value = value
- except Exception as e:
- self.err_warn("Unable to set value {}".format(value))
-
- def err_warn(self, s, error=None):
- self._error_log(s, error=error);
- raise BadParamError("%s - %s" % (self._classname, s))
-
- def __getattr__(self, key):
- try:
- return self.__getattribute__(key);
- except AttributeError:
- return None
-
- def err_fatal(self, s, error=None):
- self._log(s, error, fatal=True);
- sys.exit(1);
-
- def _error_log(self, s, error=None, fatal=False):
- message = "ERROR - BAD PARAM"
- if fatal: message += "- [FATAL] -"
- sys.stderr.write("{}:{} - {}\n".format(message, self._classname, s))
- if error:
- sys.stderr.write("PARAM ERROR: {}\n".format(str(error)))
-
-from param.int_ import Int
-from param.raw import Raw
-from param.bool_ import Bool
-from param.enum import Enum
-from param.json import Json
-from param.color import Color
-from param.float_ import Float
-from param.img_url import Img_url
-from param.string import String
+"""imports for the param package"""
+from .param import Param
+from .int_ import Int
+from .raw import Raw
+from .bool_ import Bool
+from .enum import Enum
+from .json import Json
+from .color import Color
+from .float_ import Float
+from .img_url import Img_url
+from .string import String
diff --git a/lib/param/bool_.py b/lib/param/bool_.py
index 394dea6..fb688e3 100644
--- a/lib/param/bool_.py
+++ b/lib/param/bool_.py
@@ -1,5 +1,5 @@
"""Defines the bool param type"""
-from param import Param
+from .param import Param
import re
class Bool(Param):
"""Defines the bool param type
diff --git a/lib/param/color.py b/lib/param/color.py
index 1c62955..096a1e8 100644
--- a/lib/param/color.py
+++ b/lib/param/color.py
@@ -1,5 +1,5 @@
"""Defines the color param type"""
-from param import Param
+from .param import Param
import re
class Color(Param):
"""Defines the color param type
diff --git a/lib/param/enum.py b/lib/param/enum.py
index c68adc9..d28073d 100644
--- a/lib/param/enum.py
+++ b/lib/param/enum.py
@@ -1,6 +1,6 @@
"""Defines the enum param type"""
-from param import Param
+from .param import Param
class Enum(Param):
"""Defines the enum param type
Args:
diff --git a/lib/param/float_.py b/lib/param/float_.py
index 88ed066..46b0b14 100644
--- a/lib/param/float_.py
+++ b/lib/param/float_.py
@@ -1,5 +1,5 @@
"""Defines the float param type"""
-from param import Param
+from .param import Param
class Float(Param):
"""Defines the float param type
Args:
diff --git a/lib/param/img_url.py b/lib/param/img_url.py
index 4ce7ce7..69e3d66 100644
--- a/lib/param/img_url.py
+++ b/lib/param/img_url.py
@@ -1,98 +1,111 @@
+"""Img_url param class definition lives here"""
import os
-from param import Param
-from config import *
-import urllib, urllib2
+from .param import Param
+from config import MAX_SIZE, SPECIAL_DOWNLOADERS, SPECIAL_DOWNLOADERS_MAX_SIZE,\
+ BIN_IDENTIFY
+import urllib2
from subprocess import Popen, PIPE
import sys
-Request = urllib2.Request
-urlencode = urllib.urlencode
-urlopen = urllib2.urlopen
-Request = urllib2.Request
-urlencode = urllib.urlencode
-urlopen = urllib2.urlopen
-import sys;
class Img_url(Param):
- def __init__(self, value, key="", classname=""):
- super(Img_url, self).__init__(classname=classname)
- if value:
- try:
- self.filename = self._filename_temporary(key)
+ def __init__(self, value, key="", classname=""):
+ """Defines the float param type.
+ Takes in a url, sends a get request to the url, writes the response
+ to a temporary filename, and checks the mimetype with imagemagick.
+ Img_url class is different from other params in that it has
+ the attributes:
+ url: the original url used to retrieve the image
+ filename: the filename created to store the image
+ filepath: complete path to the stored image file
+ mimetype: the mimetype of the image
+ Args:
+ value: the image url string
+ key: the intended name of the param instance
+ classname: the name of the class to which the param belongs
+ """
+ super(Img_url, self).__init__(classname=classname)
+ if value:
+ try:
+ self.filename = self._filename_temporary(key)
- self.path = os.path.join(self._working_dir, self.filename)
- self._image_download(value, self.path)
- self.mimetype = self._image_mimetype(self.path)
- self.url = value
- except Exception as e:
- self.err_warn("Unable to download image: %s" % str(value))
- self.err_warn(str(e))
+ self.path = os.path.join(self._working_dir, self.filename)
+ self._image_download(value, self.path)
+ self.mimetype = self._image_mimetype(self.path)
+ self.url = value
+ except Exception as e:
+ self.err_warn("Unable to download image: %s" % str(value))
+ self.err_warn(str(e))
- def _filename_temporary(self, s):
- return "_tmp-{}-{}_{}".format(self._classname, self._now, s)
-
- def __dict__(self):
- return {
- 'filename' : self.filename,
- 'path': self.path,
- 'url': self.url,
- 'mimetype': self.mimetype
- }
+ def _filename_temporary(self, s):
+ return "_tmp-{}-{}_{}".format(self._classname, self._now, s)
- def __getitem__(self, item):
- return self.__dict__().__getitem__(item)
+ def __dict__(self):
+ return {
+ 'filename' : self.filename,
+ 'path': self.path,
+ 'url': self.url,
+ 'mimetype': self.mimetype
+ }
- def __str__(self):
- return str(self.__dict__())
+ def __getitem__(self, item):
+ return self.__dict__().__getitem__(item)
- def __nonzero__(self):
- return True if self.path and self.mimetype else False
+ def __str__(self):
+ return str(self.__dict__())
- def _image_download(self, url, path):
- max_size = MAX_SIZE
- if self.username in SPECIAL_DOWNLOADERS:
- max_size = SPECIAL_DOWNLOADERS_MAX_SIZE
- try:
- self._download(url, path, max_size=max_size)
- except Exception as e:
- self.err_warn("Download failed");
+ def __nonzero__(self):
+ return True if self.path and self.mimetype else False
- def _browser_request (self, url, data=None):
- headers = {
- 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
- 'Accept': '*/*',
- }
- try:
- req = Request(url, data, headers)
- response = urlopen(req)
- except IOError as e:
- if hasattr(e, 'code'):
- sys.stderr.write( 'browser request error: %s - ERROR %s' % (url, e.code) )
- raise IOError
- return response
+ def _image_download(self, url, path):
+ """downloads the image to the path specified in the local
+ filesystem"""
+ max_size = MAX_SIZE
+ if self.username in SPECIAL_DOWNLOADERS:
+ max_size = SPECIAL_DOWNLOADERS_MAX_SIZE
+ try:
+ self._download(url, path, max_size=max_size)
+ except Exception as e:
+ self.err_warn("Download failed")
- def _download(self, url, destination, max_size=MAX_SIZE):
- response = self._browser_request(url, None)
+ def _browser_request(self, url, data=None):
+ """sends a get request to the url using browser User-Agent headers"""
+ headers = {
+ 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
+ 'Accept': '*/*',
+ }
+ try:
+ req = urllib2.Request(url, data, headers)
+ response = urllib2.urlopen(req)
+ except IOError as e:
+ if hasattr(e, 'code'):
+ sys.stderr.write('browser request error: %s - ERROR %s' % (url, e.code))
+ raise IOError
+ return response
- rawimg = response.read()
- if len(rawimg) == 0:
- self.err_warn("got zero-length file")
- if len(rawimg) > max_size:
- self.err_warn("file too big: max size {} KB / {} is {} KB".format(
- str(MAX_SIZE/1024),
- destination,
- str(len(rawimg)/1024)
- )
- )
- f = open(destination, "w")
- f.write(rawimg)
- f.close()
+ def _download(self, url, destination, max_size=MAX_SIZE):
+ """generic download method, checks the size of the filedata"""
+ response = self._browser_request(url, None)
- def _image_mimetype(self, f):
- try:
- mimetype = Popen(
- [BIN_IDENTIFY, f], stdout=PIPE
- ).communicate()[0].split(" ")[1].lower()
- return mimetype
- except Exception as e:
- sys.stderr.write("couldn't determine mimetype\n")
- raise e;
+ rawimg = response.read()
+ if len(rawimg) == 0:
+ self.err_warn("got zero-length file")
+ if len(rawimg) > max_size:
+ self.err_warn("file too big: max size {} KB / {} is {} KB".format(
+ str(MAX_SIZE/1024),
+ destination,
+ str(len(rawimg)/1024)
+ ))
+ f = open(destination, "w")
+ f.write(rawimg)
+ f.close()
+
+ def _image_mimetype(self, f):
+ """retrieves the image mimetype from the file header using imagemagick"""
+ try:
+ mimetype = Popen(
+ [BIN_IDENTIFY, f], stdout=PIPE
+ ).communicate()[0].split(" ")[1].lower()
+ return mimetype
+ except Exception as e:
+ sys.stderr.write("couldn't determine mimetype\n")
+ raise e
diff --git a/lib/param/int_.py b/lib/param/int_.py
index b33c6b5..9d48518 100644
--- a/lib/param/int_.py
+++ b/lib/param/int_.py
@@ -1,18 +1,25 @@
-from param import Param
+"""Int class definition lives here"""
+from .param import Param
class Int(Param):
- def __init__(self, value, classname=""):
- super(Int, self).__init__(classname=classname)
- try:
- if value:
- self.value = int(value)
- else:
- self.value = 0
- except Exception as e:
- self.err_warn("Not an int: %s" % str(value))
- self.err_warn(str(e))
- def __int__(self):
- return int(self.value)
-
- def __float__(self):
- return float(self.value)
+ def __init__(self, value, classname=""):
+ """Defines the float param type
+ Args:
+ value: the value of the Int
+ classname: the name of the class to which the param belongs
+ """
+ super(Int, self).__init__(classname=classname)
+ try:
+ if value:
+ self.value = int(value)
+ else:
+ self.value = 0
+ except Exception as e:
+ self.err_warn("Not an int: %s" % str(value))
+ self.err_warn(str(e))
+
+ def __int__(self):
+ return int(self.value)
+
+ def __float__(self):
+ return float(self.value)
diff --git a/lib/param/json.py b/lib/param/json.py
index 08db3e9..4fa4933 100644
--- a/lib/param/json.py
+++ b/lib/param/json.py
@@ -1,5 +1,5 @@
"""Defines the json param type"""
-from param import Param
+from .param import Param
import simplejson as json
class Json(Param):
diff --git a/lib/param/param.py b/lib/param/param.py
new file mode 100644
index 0000000..d1e1446
--- /dev/null
+++ b/lib/param/param.py
@@ -0,0 +1,59 @@
+"""param base class lives here, used for inheritance only"""
+import time
+import sys
+
+from config import WORKING_DIR
+
+class BadParamError(Exception):
+ pass
+
+
+class Param(object):
+ """Defines the param base class, this class is used for inheritance only"""
+ def __init__(self, classname="", **kwargs):
+ self.value = None
+ self._working_dir = WORKING_DIR
+ self._now = kwargs.get("now", str(int(time.time())))
+ self._classname = classname
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ def __nonzero__(self):
+ return True if self.value else False
+
+ def __str__(self):
+ return str(self.value)
+
+ def __eq__(self, other):
+ return self.value == other
+
+ def __ne__(self, other):
+ return self.value != other
+
+ def set_val(self, value):
+ try:
+ self.value = value
+ except Exception as e:
+ self.err_warn("Unable to set value {}".format(value))
+
+ def err_warn(self, s, error=None):
+ self._error_log(s, error=error)
+ raise BadParamError("%s - %s" % (self._classname, s))
+
+ def __getattr__(self, key):
+ try:
+ return self.__getattribute__(key)
+ except AttributeError:
+ return None
+
+ def err_fatal(self, s, error=None):
+ self._log(s, error, fatal=True)
+ sys.exit(1)
+
+ def _error_log(self, s, error=None, fatal=False):
+ message = "ERROR - BAD PARAM"
+ if fatal: message += "- [FATAL] -"
+ sys.stderr.write("{}:{} - {}\n".format(message, self._classname, s))
+ if error:
+ sys.stderr.write("PARAM ERROR: {}\n".format(str(error)))
+
diff --git a/lib/param/raw.py b/lib/param/raw.py
index 3d2f93f..72d6e0d 100644
--- a/lib/param/raw.py
+++ b/lib/param/raw.py
@@ -1,6 +1,14 @@
-from param import Param
+"""Defines the raw param type"""
+from .param import Param
class Raw(Param):
- def __init__(self, value, classname=""):
- super(Raw, self).__init__(classname=classname)
- self.value = value or None
+ """Defines the raw param type.
+ Basically, this is a catchall class, any input can go here,
+ so it needs to be used carefully (for security reasons).
+ Args:
+ value: can be any value
+ classname: name of the class to which the param instance belongs
+ """
+ def __init__(self, value, classname=""):
+ super(Raw, self).__init__(classname=classname)
+ self.value = value or None
diff --git a/lib/param/string.py b/lib/param/string.py
index bd3d6d8..14e8e87 100644
--- a/lib/param/string.py
+++ b/lib/param/string.py
@@ -1,15 +1,21 @@
-from param import Param
+"""String class definition lives here"""
+from .param import Param
import re
-import sys
class String(Param):
- def __init__(self, value, classname=""):
- super(String, self).__init__(classname=classname)
- if value:
- try:
- self.value = self.sanitize(value)
- except Exception as e:
- self.err_warn("Unable to sanitize: %s\nreason:%s" % (str(value), str(e)))
- else:
- self.value = ""
- def sanitize (self, s):
- return re.sub(r'\W+', '', s)
+ """String param class definition
+ Args:
+ value: a string
+ classname: name of the class to which the param instance will belong
+ """
+ def __init__(self, value, classname=""):
+ super(String, self).__init__(classname=classname)
+ if value:
+ try:
+ self.value = self.sanitize(value)
+ except Exception as e:
+ self.err_warn("Unable to sanitize: %s\nreason:%s" % (str(value), str(e)))
+ else:
+ self.value = ""
+ def sanitize(self, s):
+ """Removes non-word characters from the string for security reasons"""
+ return re.sub(r'\W+', '', s)
diff --git a/lib/params.py b/lib/params.py
index 33a467e..2f3bf31 100644
--- a/lib/params.py
+++ b/lib/params.py
@@ -1,6 +1,7 @@
"""Params class and methods stored here"""
import sys
-from param import Bool, Color, Enum, Float, Img_url, Json, Raw, String
+from param import Bool, Color, Enum, Float, Int,\
+ Img_url, Json, Raw, String
class BadParamError(Exception):
pass
diff --git a/lib/pb/landscape/__init__.py b/lib/pb/landscape/__init__.py
index 54f9806..df8d143 100755
--- a/lib/pb/landscape/__init__.py
+++ b/lib/pb/landscape/__init__.py
@@ -5,46 +5,46 @@ import urlparse, re
class PbLandscape(Pb):
example_params = {
- 'imgdata' : open('lib/pb/landscape/_base64img', 'rb').read(),
- 'texture' : 'http://someurl.biz/someimg.jpg',
- 'heightmap' : 'http://someurl.biz/someimg.jpg',
- 'name' : 'donkey'
+ 'imgdata' : open('lib/pb/landscape/_base64img', 'rb').read(),
+ 'texture' : 'http://someurl.biz/someimg.jpg',
+ 'heightmap' : 'http://someurl.biz/someimg.jpg',
+ 'name' : 'donkey'
}
def __init__(self, **kwargs):
- super(PbLandscape,self).__init__(**kwargs);
- _definitions = {
- 'heightmap': {'type': 'string'} ,
- 'imgdata': {'type': 'raw' } ,
- 'texture': {'type': 'string' } ,
- 'username': {'type': 'string'} ,
- }
- self.params.definitions_import(_definitions, kwargs, classname=self.__class__.__name__);
- _namepart = re.sub(r'https?:?/?/?', '', str(self.params.texture))
- self.filename, self.filepath = self._filename_filepath_create(url=_namepart, extension="png")
-
- self._db_url_param = str(self.params.texture)
+ super(PbLandscape, self).__init__(**kwargs)
+ _definitions = {
+ 'heightmap': {'type': 'string'},
+ 'imgdata': {'type': 'raw'},
+ 'texture': {'type': 'string'},
+ 'username': {'type': 'string'},
+ }
+ self.params.definitions_import(_definitions, kwargs, classname=self.__class__.__name__)
+ _namepart = re.sub(r'https?:?/?/?', '', str(self.params.texture))
+ self.filename, self.filepath = self._filename_filepath_create(url=_namepart, extension="png")
+
+ self._db_url_param = str(self.params.texture)
def _saveImgData(self):
- try:
- up = urlparse.urlparse(str(self.params.imgdata))
- head, data = up.path.split(',', 1)
- bits = head.split(';')
- mime_type = bits[0] if bits[0] else 'text/plain'
- charset, b64 = 'ASCII', False
- for bit in bits[1]:
- if bit.startswith('charset='):
- charset = bit[8:]
- elif bit == 'base64':
- b64 = True
+ try:
+ up = urlparse.urlparse(str(self.params.imgdata))
+ head, data = up.path.split(',', 1)
+ bits = head.split(';')
+ #mime_type = bits[0] if bits[0] else 'text/plain'
+ #charset, b64 = 'ASCII', False
+ #for bit in bits[1]:
+ # if bit.startswith('charset='):
+ # charset = bit[8:]
+ # elif bit == 'base64':
+ # b64 = True
- # Do something smart with charset and b64 instead of assuming
- plaindata = base64.b64decode(data)
+ # Do something smart with charset and b64 instead of assuming
+ plaindata = base64.b64decode(data)
- with open(self.filepath, 'wb') as f:
- f.write(plaindata)
- except Exception as e:
- self.err_warn(str(e));
+ with open(self.filepath, 'wb') as f:
+ f.write(plaindata)
+ except Exception as e:
+ self.err_warn(str(e))
def create(self, breakmode=""):
- self._saveImgData();
+ self._saveImgData()
super(PbLandscape, self).create()
diff --git a/lib/server.py b/lib/server.py
index 8506c7a..3a91632 100644
--- a/lib/server.py
+++ b/lib/server.py
@@ -1,5 +1,6 @@
+"""All webserver logic lives here, including routes"""
from flask import Flask
-from flask import abort, redirect, url_for, request, jsonify
+from flask import request, jsonify
import sys, os
import cherrypy
@@ -8,9 +9,9 @@ from paste.translogger import TransLogger
sys.path.append("./lib")
from pb import *
from config import SERVER_HOST, SERVER_PORT
-#http://flask.pocoo.org/docs/0.10/deploying/fastcgi/ this should be the one
class InvalidUsage(Exception):
+ """error class for InvalidUsage"""
status_code = 400
def __init__(self, message, status_code=None, payload=None):
@@ -26,83 +27,77 @@ class InvalidUsage(Exception):
return rv
class Server(object):
- def __init__(self):
- self.app = Flask(__name__)
- self._wsgi_server = None
- @self.app.route('/test', methods=['GET'])
- def test():
- return "HELLO WORLD!"
- @self.app.route('/im/api/<pb_classname>', methods=['POST'])
- def pb(pb_classname):
- return self._response_post(pb_classname, request.form.to_dict())
+ """Main server class"""
+ def __init__(self):
+ self.app = Flask(__name__)
+ self._wsgi_server = None
+ @self.app.route('/test', methods=['GET'])
+ def test():
+ return "HELLO WORLD!"
+ @self.app.route('/im/api/<pb_classname>', methods=['POST'])
+ def pb(pb_classname):
+ return self._response_post(pb_classname, request.form.to_dict())
- @self.app.errorhandler(InvalidUsage)
- def handle_invalid_usage(error):
- response = jsonify(error.to_dict())
- response.status_code = error.status_code
- return response
+ @self.app.errorhandler(InvalidUsage)
+ def handle_invalid_usage(error):
+ response = jsonify(error.to_dict())
+ response.status_code = error.status_code
+ return response
- self._classname_aliases = {
- 'generate' : 'PbGenerate',
- 'imgrid' : 'PbGrid',
- 'imbreak' : 'PbBreaker',
- 'impattern' : 'PbPattern',
- 'imgradient' : 'PbGradient',
- 'landscape' : 'PbLandscape',
- }
+ self._classname_aliases = {
+ 'generate' : 'PbGenerate',
+ 'imgrid' : 'PbGrid',
+ 'imbreak' : 'PbBreaker',
+ 'impattern' : 'PbPattern',
+ 'imgradient' : 'PbGradient',
+ 'landscape' : 'PbLandscape',
+ }
- def _find_class_by_name(self, pb_classname):
- pb_classname = self._classname_aliases.get(pb_classname, None) or pb_classname
- try:
- return filter(lambda c: c.__name__ == pb_classname, Pb.__subclasses__())[0]
- except IndexError:
- raise InvalidUsage('No such api', status_code=410)
+ def _find_class_by_name(self, pb_classname):
+ pb_classname = self._classname_aliases.get(pb_classname, None) or pb_classname
+ try:
+ return filter(lambda c: c.__name__ == pb_classname, Pb.__subclasses__())[0]
+ except IndexError:
+ raise InvalidUsage('No such api', status_code=410)
- def _response_post(self, pb_classname, request_form):
- pb_class = self._find_class_by_name(pb_classname)
- classnames = map(lambda c: c.__name__, Pb.__subclasses__())
- try:
- pb = pb_class(**request_form)
- pb.create();
- pb.file_s3move()
- pb.db_send();
- return jsonify(pb.file_dict());
+ def _response_post(self, pb_classname, request_form):
+ pb_class = self._find_class_by_name(pb_classname)
+ classnames = map(lambda c: c.__name__, Pb.__subclasses__())
+ try:
+ pb = pb_class(**request_form)
+ pb.create()
+ pb.file_s3move()
+ pb.db_send()
+ return jsonify(pb.file_dict())
- #FIXME handle BadParamsError and PbError separately
- except Exception as e:
- sys.stderr.write("%s failure" % pb_class.__name__)
- sys.stderr.write("params:\n")
- sys.stderr.write(str(e))
- for i in request_form.keys():
- sys.stderr.write("{}:{}\n".format(i, request_form[i]))
- raise;
- return jsonify({ 'error' : 'Request could not be processed' })
+ #FIXME handle BadParamsError and PbError separately
+ except Exception as e:
+ sys.stderr.write("%s failure" % pb_class.__name__)
+ sys.stderr.write("params:\n")
+ sys.stderr.write(str(e))
+ for i in request_form.keys():
+ sys.stderr.write("{}:{}\n".format(i, request_form[i]))
+ raise
+ return jsonify({'error' : 'Request could not be processed'})
- def run(self, host=SERVER_HOST, port=SERVER_PORT):
- self.app.run(host=host, port=port)
+ def run(self, host=SERVER_HOST, port=SERVER_PORT):
+ self.app.run(host=host, port=port)
+ def run_wsgi(self, server_port=SERVER_PORT, host=SERVER_HOST):
+ #http://fgimian.github.io/blog/2012/12/08/setting-up-a-rock-solid-python-development-web-server/
+ # Enable WSGI access logging via Paste
+ app_logged = TransLogger(self.app)
-#http://fgimian.github.io/blog/2012/12/08/setting-up-a-rock-solid-python-development-web-server/
- def run_wsgi(self, server_port=SERVER_PORT, host=SERVER_HOST):
- # Enable WSGI access logging via Paste
- app_logged = TransLogger(self.app)
+ # Mount the WSGI callable object (app) on the root directory
+ cherrypy.tree.graft(app_logged, '/')
- # Mount the WSGI callable object (app) on the root directory
- cherrypy.tree.graft(app_logged, '/')
+ # Set the configuration of the web server
+ cherrypy.config.update({
+ 'engine.autoreload_on': True,
+ 'log.screen': True,
+ 'server.socket_port': server_port,
+ 'server.socket_host': host
+ })
+ cherrypy.engine.start()
+ cherrypy.engine.block()
- # Set the configuration of the web server
- cherrypy.config.update({
- 'engine.autoreload_on': True,
- 'log.screen': True,
- 'server.socket_port': server_port,
- 'server.socket_host': host
- })
- cherrypy.engine.start()
- cherrypy.engine.block()
-
-
- def stop(self):
- if self._wsgi_server:
- return
- else:
- return
diff --git a/run_module_examples.py b/run_module_examples.py
index 32a920f..7803fc0 100644
--- a/run_module_examples.py
+++ b/run_module_examples.py
@@ -1,9 +1,10 @@
+#!/usr/bin/python2.7
+"""calls the example_run method on all modules"""
import sys
sys.path.append('./lib')
from pb import *
for cls in Pb.__subclasses__():
- print cls.__name__
- if cls.__name__ == 'PbGenerate':
+ print cls.__name__
instance = cls.example_run()
instance.file_s3move()
print instance.file_dict()
diff --git a/run_server.py b/run_server.py
index 9d80e6c..5cff199 100644
--- a/run_server.py
+++ b/run_server.py
@@ -1,9 +1,10 @@
#!/usr/bin/python2
+"""used to run the webserver"""
import sys
sys.path.append("./lib")
from server import Server
server = Server()
if __name__ == "__main__":
- server.run_wsgi()
+ server.run_wsgi()