Skip to content

Commit

Permalink
More PEP8
Browse files Browse the repository at this point in the history
  • Loading branch information
rtbustamantec committed Sep 22, 2014
1 parent f5db430 commit f02afe5
Show file tree
Hide file tree
Showing 6 changed files with 328 additions and 312 deletions.
16 changes: 9 additions & 7 deletions ObjectWeb/__init__.py
@@ -1,22 +1,24 @@
#!/usr/bin/python
################################################################################
###############################################################################
## contact: abram@isola.mn || https://github.com/aisola/ObjectWeb
## license: LGPLv3
## summary: This document initializes the ObjectWeb Framework for use.
## maintainer: Abram C. Isola <abram@isola.mn>
## contrib: Abram C. Isola <abram@isola.mn> (all)
################################################################################
###############################################################################

################################################################################
###############################################################################
# Import
################################################################################
###############################################################################

from application import *
from webapi import *
#from forms import *

################################################################################
###############################################################################
# Meta Information
################################################################################
###############################################################################

__author__ = ["See CONTRIB"]
__version__ = "2.0 (Beta)"
__url__ = "http://gihub.com/aisola/ObjectWeb"
__url__ = "http://gihub.com/aisola/ObjectWeb"
160 changes: 82 additions & 78 deletions ObjectWeb/application.py
@@ -1,16 +1,17 @@
#!/usr/bin/python
################################################################################
## contact: abram@isola.mn || https://github.com/aisola/ObjectWeb
# #############################################################################
# # contact: abram@isola.mn || https://github.com/aisola/ObjectWeb
## license: LGPLv3
## @summary: This document creates the Application Object that is
## crucial for the Framework.
## maintainer: Abram C. Isola <abram@isola.mn>
## contrib: Abram C. Isola <abram@isola.mn> (all)
################################################################################
###############################################################################

################################################################################
###############################################################################
# Import Standard Libraries
################################################################################
###############################################################################

import os
import re
import sys
Expand All @@ -19,15 +20,16 @@
from wsgiref.simple_server import make_server
#from wsgiref.handlers import CGIHandler

################################################################################
###############################################################################
# Import ObjectWeb
################################################################################
###############################################################################

import webapi
import debug

################################################################################
###############################################################################
# ObjectWeb Documentation
################################################################################
###############################################################################
"""
ObjectWeb is a fast, minimalist, pure-Python web framework that relies on no
third party libraries. It is designed around using Python as it was originally
Expand All @@ -50,28 +52,27 @@ def GET(self):
# Create the Application Object.
app = ObjectWeb.Appliation({
"/": MainPage, # Point the / path to be handled by MainPage
}, debug=False) # Set debug to False for production.
"/": MainPage, # Point the / path to be handled by MainPage
}, debug=False) # Set debug to False for production.
ObjectWeb can be used for many things. Feel free to include other libraries like
ORMs or Templating Engines to assist you in your development.
ObjectWeb can be used for many things. Feel free to include other libraries
like ORMs or Templating Engines to assist you in your development.
"""

################################################################################

###############################################################################
# Classes
################################################################################
###############################################################################

class Application(object):
"""
This is the main interface between the webserver and the application.
"""

def __init__(self,urlmap={},debug=False):
"""
*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
"""This is the main interface between the webserver and the application."""

def __init__(self, urlmap={}, debug=False):
"""*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
Initializes the Application Object.
Initializes the Application Object.
@param urlmap: *dict* This is a normal python dict who keys are
python re strings that map to python objects that have at least a
Expand All @@ -87,14 +88,13 @@ def __init__(self,urlmap={},debug=False):
"""
self.urlmap = urlmap
self.debug = debug

def _match(self, rpath):
"""
*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
"""*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
- Called by self.handle()
Matches the request path to the object that should handle the
requst and returns the object or None if no match exists.
Matches the request path to the object that should handle the request
and returns the object or None if no match exists.
@param rpath: *str* The webserver request path.
Expand All @@ -113,8 +113,8 @@ def _match(self, rpath):

elif type(self.urlmap) == type(()) or type(self.urlmap) == type([]):
for patwhat in self.urlmap:
pat = patwhat[0]
what = patwhat[1]
pat = patwhat[0]
what = patwhat[1]
result = re.compile("^" + str(pat) + "$").match(str(rpath))

# If there is a result, then we've matched a handler.
Expand All @@ -124,14 +124,13 @@ def _match(self, rpath):

# No match, return None.
return None

def _handle(self):
"""
*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
"""*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
- Called by: wsgi()
This method calls self._match() to find the handler then calls the
correct method (GET, POST, etc.) to handle the request.
This method calls self._match() to find the handler then calls the
correct method (GET, POST, etc.) to handle the request.
@return: The processed request's status and output.
"""
Expand All @@ -147,13 +146,15 @@ def _handle(self):
# If the HandlerObj has the method function available. (upper)
if hasattr(HandlerInst, webapi.context["method"].upper()):
# Run the method, passing in the arguments. Capture the output.
method_func = getattr(HandlerInst,webapi.context["method"].upper())
method_func = getattr(HandlerInst,
webapi.context["method"].upper())
webapi.context["output"] = method_func(*args)

# If the HandlerObj has the method function available. (lower)
elif hasattr(HandlerInst, webapi.context["method"].lower()):
# Run the method, passing in the arguments. Capture the output.
method_func = getattr(HandlerInst,webapi.context["method"].lower())
method_func = getattr(HandlerInst,
webapi.context["method"].lower())
webapi.context["output"] = method_func(*args)

# Otherwise throw an HTTP 405 Method Not Allowed.
Expand All @@ -166,7 +167,9 @@ def _handle(self):
webapi.context["output"] = HandlerInst.GET()
# If not, provide one.
else:
webapi.context["output"] = "Method Not Allowed: The method used is not allowed for this resource."
webapi.context[
"output"] = "Method Not Allowed: The method used is " \
"not allowed for this resource."

# The HandlerObj is None.
else:
Expand All @@ -178,17 +181,17 @@ def _handle(self):
webapi.context["output"] = HandlerInst.GET()
# If not, provide one.
else:
webapi.context["output"] = "Not Found: The requested URL was not found."
webapi.context[
"output"] = "Not Found: The requested URL was not found."

# return the status & the output
return webapi.context["status"], webapi.context["output"]

def _load(self,env):
"""
*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*

def _load(self, env):
"""*THIS METHOD SHOULD NOT BE CALLED MANUALLY.*
- Called by: wsgi()
Loads the Application environment.
Loads the Application environment.
@param env: *dict* A regular python dict that is recieved from the
webserver and holds the environment variables.
Expand Down Expand Up @@ -219,9 +222,12 @@ def _load(self,env):
webapi.context["protocol"] = 'http'

# Set home domain, home path, and home
webapi.context["homedomain"] = webapi.context["protocol"] + '://' + env.get('HTTP_HOST', '[unknown]')
webapi.context["homepath"] = os.environ.get('REAL_SCRIPT_NAME', env.get('SCRIPT_NAME', ''))
webapi.context["home"] = webapi.context["homedomain"] + webapi.context["homepath"]
webapi.context["homedomain"] = webapi.context["protocol"] + '://' + \
env.get('HTTP_HOST', '[unknown]')
webapi.context["homepath"] = os.environ.get(
'REAL_SCRIPT_NAME', env.get('SCRIPT_NAME', ''))
webapi.context["home"] = webapi.context["homedomain"] + \
webapi.context["homepath"]
webapi.context["realhome"] = webapi.context["home"]

# Set the Requester's IP, the Method, and the path.
Expand All @@ -230,31 +236,28 @@ def _load(self,env):
webapi.context["path"] = env.get('PATH_INFO')

# To fix empty-path bug.
if webapi.context["path"] == None:
if webapi.context["path"] is None:
webapi.context["path"] = "/"

# get the requestvars if post/put
if webapi.context["method"].lower() in ['post', 'put']:
fp = env.get('wsgi.input')
webapi.context["requestvars"] = cgi.FieldStorage(fp=fp,
environ=env,
keep_blank_values=1)

fp = env.get('wsgi.input')
webapi.context["requestvars"] = cgi.FieldStorage(
fp=fp, environ=env, keep_blank_values=1)

# get the requestvars if get
if webapi.context["method"].lower() == 'get':
webapi.context["requestvars"] = cgi.FieldStorage(environ=env,
keep_blank_values=1)
webapi.context["requestvars"] = cgi.FieldStorage(
environ=env, keep_blank_values=1)


# convert all string values to unicode values and replace
# malformed data with a suitable replacement marker.
for k, v in webapi.context.iteritems():
if isinstance(v, str):
webapi.context[k] = v.decode('utf-8', 'replace')

def getwsgi(self,*middleware):
"""
Creates a WSGI function that can be passed to a webserver run run.

def getwsgi(self, *middleware):
"""Creates a WSGI function that can be passed to a webserver run run.
It will add all *middleware to the function as well.
@param *middleware: *object* Python WSGI Middleware-compliant
Expand Down Expand Up @@ -283,7 +286,7 @@ def wsgi(env, start_response):
headers = webapi.getheaders()

# Send Complete WSGI request
start_response(str(code),headers)
start_response(str(code), headers)
return [str(output)]

# Apply middleware.
Expand All @@ -298,28 +301,30 @@ def getgoogleapp(self, *middleware):
try:
# check what version of python is running
version = sys.version_info[:2]
major = version[0]
minor = version[1]
major = version[0]
minor = version[1]

if major != 2:
raise EnvironmentError("Google App Engine only supports python 2.5 and 2.7")
raise EnvironmentError(
"Google App Engine only supports python 2.5 and 2.7")

# if 2.7, return a function that can be run by gae
if minor == 7:
return wsgiapp
# if 2.5, use run_wsgi_app
elif minor == 5:
from google.appengine.ext.webapp.util import run_wsgi_app

return run_wsgi_app(wsgiapp)
else:
raise EnvironmentError("Not a supported platform, use python 2.5 or 2.7")
raise EnvironmentError(
"Not a supported platform, use python 2.5 or 2.7")
except ImportError:
return self.getcgi(*middleware)

def getcgi(self,*middleware):
"""
Creates a CGI run and producing CGI compatibility. It will add all
*middleware to the output as well.

def getcgi(self, *middleware):
"""Creates a CGI run and producing CGI compatibility. It will add all
*middleware to the output as well.
@param *middleware: *object* Python WSGI Middleware-compliant
objects that passed as *args that will be applied as middleware to
Expand All @@ -328,12 +333,11 @@ def getcgi(self,*middleware):
@return: returns CGI compliant output.
"""
return webapi.UnicodeCGIHandler().run(self.getwsgi(*middleware))

def run(self,host="localhost",port=8080,*middleware):
"""
Creates a development server binded to *host* and *port* and
producing the output. It will add all *middleware to the output as
well.

def run(self, host="localhost", port=8080, *middleware):
"""Creates a development server binded to *host* and *port* and
producing the output. It will add all *middleware to the output as
well.
@param host: *str* The host that the run should be bound to.
Expand All @@ -345,7 +349,7 @@ def run(self,host="localhost",port=8080,*middleware):
@return: None
"""
httpd_wsgi = make_server(host,port,self.getwsgi(*middleware))
httpd_wsgi = make_server(host, port, self.getwsgi(*middleware))
try:
httpd_wsgi.serve_forever()
except KeyboardInterrupt:
Expand Down

0 comments on commit f02afe5

Please sign in to comment.