Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Major code style fixes #21

Merged
4 commits merged into from

1 participant

This page is out of date. Refresh to see the latest.
View
93 fapws/base.py
@@ -20,8 +20,9 @@
import cStringIO as StringIO
except ImportError:
import StringIO
-import traceback, sys, string
-
+import sys
+import string
+import traceback
import time
import config
@@ -75,56 +76,63 @@
505: 'HTTP Version not supported',
507: 'Insufficient Storage',
}
+
+
def get_status(code):
return "%s %s" % (code, status_reasons[code])
-
class Environ(dict):
def __init__(self, *arg, **kw):
- self['wsgi.version'] = (1,0)
+ self['wsgi.version'] = (1, 0)
self['wsgi.errors'] = StringIO.StringIO()
self['wsgi.input'] = StringIO.StringIO()
self['wsgi.multithread'] = False
self['wsgi.multiprocess'] = True
self['wsgi.run_once'] = False
- self['fapws.params']={}
+ self['fapws.params'] = {}
#here after some entry point before the Environ update
+
def update_headers(self, data):
- dict.update(self,data)
+ dict.update(self, data)
+
def update_uri(self, data):
- dict.update(self,data)
+ dict.update(self, data)
+
def update_from_request(self, data):
dict.update(self, data)
+
class Start_response:
def __init__(self):
self.status_code = "200"
self.status_reasons = "OK"
self.response_headers = {}
self.exc_info = None
- self.cookies = None
+ self.cookies = None
# NEW -- sent records whether or not the headers have been send to the
# client
- self.sent= False
+ self.sent = False
def __call__(self, status, response_headers, exc_info=None):
- self.status_code, self.status_reasons = status.split(" ",1)
- self.status_code=str(self.status_code)
- for key,val in response_headers:
+ self.status_code, self.status_reasons = status.split(" ", 1)
+ self.status_code = str(self.status_code)
+ for key, val in response_headers:
#if type(key)!=type(""):
- key=str(key)
+ key = str(key)
#if type(val)!=type(""):
- val=str(val)
+ val = str(val)
self.response_headers[key] = val
- self.exc_info = exc_info #TODO: to implement
- def add_header(self, key,val):
- key=str(key)
- val=str(val)
- self.response_headers[key]=val
+ self.exc_info = exc_info # TODO: to implement
+
+ def add_header(self, key, val):
+ key = str(key)
+ val = str(val)
+ self.response_headers[key] = val
+
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None):
if not self.cookies:
- self.cookies=SimpleCookie()
+ self.cookies = SimpleCookie()
self.cookies[key] = value
if max_age:
self.cookies[key]['max-age'] = max_age
@@ -134,7 +142,7 @@ def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain
elif isinstance(expires, datetime.datetime):
expires = evwsgi.rfc1123_date(time.mktime(expires.timetuple()))
else:
- raise CookieError, 'expires must be a datetime object or a string'
+ raise CookieError('expires must be a datetime object or a string')
self.cookies[key]['expires'] = expires
if path:
self.cookies[key]['path'] = path
@@ -142,45 +150,44 @@ def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain
self.cookies[key]['domain'] = domain
if secure:
self.cookies[key]['secure'] = secure
+
def delete_cookie(self, key):
if self.cookies:
self.cookies[key] = ''
self.cookies[key]['max-age'] = "0"
+
def __str__(self):
res = "HTTP/1.0 %s %s\r\n" % (self.status_code, self.status_reasons)
for key, val in self.response_headers.items():
- res += '%s: %s\r\n' % (key,val)
+ res += '%s: %s\r\n' % (key, val)
if self.cookies:
- res+=str(self.cookies)+"\r\n"
+ res += str(self.cookies) + "\r\n"
res += "\r\n"
return res
-
+
+
def redirectStdErr():
"""
This methods allow use to redirect messages sent to stderr into a string
- Mandatory methods of the sys.stderr object are:
+ Mandatory methods of the sys.stderr object are:
write: to insert data
getvalue; to retreive all data
"""
- sys.stderr=StringIO.StringIO()
+ sys.stderr = StringIO.StringIO()
+
+supported_HTTP_command = ["GET", "POST", "HEAD", "OPTIONS"]
-supported_HTTP_command=["GET","POST","HEAD","OPTIONS"]
def split_len(seq, length):
- return [seq[i:i+length] for i in range(0, len(seq), length)]
-
-def parse_cookies(environ):
- #transform the cookie environment into a SimpleCokkie object
- line=environ.get('HTTP_COOKIE', None)
- if line:
- cook=SimpleCookie()
- cook.load(line)
- return cook
- else:
- return None
+ return [seq[i:i + length] for i in range(0, len(seq), length)]
-if __name__=="__main__":
- try:
- r=1/0
- except:
- print errorMsg()
+
+def parse_cookies(environ):
+ #transform the cookie environment into a SimpleCokkie object
+ line = environ.get('HTTP_COOKIE', None)
+ if line:
+ cook = SimpleCookie()
+ cook.load(line)
+ return cook
+ else:
+ return None
View
6 fapws/config.py
@@ -13,7 +13,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
SERVER_IDENT = "fapws3/0.8.1"
-send_traceback_to_browser=True
+send_traceback_to_browser = True
#in case of False for send_traceback_to_browser, send_traceback_short will be sent to the browser
-send_traceback_short="<h1>Error</h1>Please contact your administrator"
-date_format="%a, %d %b %Y %H:%M:%S GMT"
+send_traceback_short = "<h1>Error</h1>Please contact your administrator"
+date_format = "%a, %d %b %Y %H:%M:%S GMT"
View
65 fapws/contrib/cgiapp.py
@@ -12,61 +12,64 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
-import os.path
+import os
import subprocess
+
class CGIApplication:
def __init__(self, script):
- self.script=script
- self.dirname=os.path.dirname(script)
- self.cgi_environ={}
+ self.script = script
+ self.dirname = os.path.dirname(script)
+ self.cgi_environ = {}
+
def _setup_cgi_environ(self, environ):
- for key,val in environ.items():
- if type(val)==type(""):
- self.cgi_environ[key]=val
- self.cgi_environ['REQUEST_URI']=environ['fapws.uri']
-
- def _split_return(self,data):
+ for key, val in environ.items():
+ if type(val) is str:
+ self.cgi_environ[key] = val
+ self.cgi_environ['REQUEST_URI'] = environ['fapws.uri']
+
+ def _split_return(self, data):
if '\n\n' in data:
- header,content=data.split('\n\n',1)
+ header, content = data.split('\n\n', 1)
else:
- header=""
- content=data
+ header = ""
+ content = data
return header, content
+
def _split_header(self, header):
- i=0
- headers=[]
- firstline="HTTP/1.1 200 OK"
+ i = 0
+ headers = []
+ firstline = "HTTP/1.1 200 OK"
for line in header.split('\n'):
- if i==0 and ':' not in line:
- firstline=line
+ if i == 0 and ':' not in line:
+ firstline = line
if ':' in line:
- name,value=line.split(':',1)
- headers.append((name,value))
- i+=1
- status=" ".join(firstline.split()[1:])
+ name, value = line.split(':', 1)
+ headers.append((name, value))
+ i += 1
+ status = " ".join(firstline.split()[1:])
return status, headers
-
+
def __call__(self, environ, start_response):
self._setup_cgi_environ(environ)
- proc=subprocess.Popen(
- [self.script],
+ proc = subprocess.Popen(
+ [self.script],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
- env=self.cgi_environ,
+ env=self.cgi_environ,
cwd=self.dirname,
)
- input_len=environ.get('CONTENT_LENGTH', 0)
+ input_len = environ.get('CONTENT_LENGTH', 0)
if input_len:
- cgi_input=environ['wsgi.input'].read(input_len)
+ cgi_input = environ['wsgi.input'].read(input_len)
else:
- cgi_input=""
+ cgi_input = ""
#print "cgi input", cgi_input
stdout, stderr = proc.communicate(cgi_input)
if stderr:
return [stderr]
- header,content=self._split_return(stdout)
- status,headers=self._split_header(header)
+ header, content = self._split_return(stdout)
+ status, headers = self._split_header(header)
start_response(status, headers)
return [content]
View
21 fapws/contrib/django_handler.py
@@ -12,17 +12,20 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
-from django.core.handlers import wsgi
+from django.core.handlers import wsgi
import django
-djhand=wsgi.WSGIHandler()
+
+djhand = wsgi.WSGIHandler()
+
+
def handler(environ, start_response):
- res=djhand(environ, start_response)
- if django.VERSION[0]==0:
- for key,val in res.headers.items():
- start_response.response_headers[key]=val
+ res = djhand(environ, start_response)
+ if django.VERSION[0] == 0:
+ for key, val in res.headers.items():
+ start_response.response_headers[key] = val
else:
- for key,val in res._headers.values():
- start_response.response_headers[key]=val
- start_response.cookies=res.cookies
+ for key, val in res._headers.values():
+ start_response.response_headers[key] = val
+ start_response.cookies = res.cookies
return res.content
View
6 fapws/contrib/headers.py
@@ -12,12 +12,12 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
+
+
def redirect(start_response, location, permanent=None):
- header=[('location',location),
- ('Content-Type',"text/plain")]
+ header = [('location', location), ('Content-Type', "text/plain")]
if permanent:
start_response('301 Moved Permanently', header)
else:
start_response('302 Moved Temporarily', header)
return []
-
View
27 fapws/contrib/log.py
@@ -14,28 +14,29 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import time
-import os.path
+import os
import sys
+
class Log:
- def __init__(self,output=sys.stdout):
- self.output=output
+ def __init__(self, output=sys.stdout):
+ self.output = output
+
def __call__(self, f):
def func(environ, start_response):
- res=f(environ, start_response)
- tts=time.strftime("%d/%b/%Y:%H:%M:%S", time.gmtime())
- if type(res)==type([]):
- content="".join(res)
- size=len(content)
+ res = f(environ, start_response)
+ tts = time.strftime("%d/%b/%Y:%H:%M:%S", time.gmtime())
+ if type(res) is list:
+ content = "".join(res)
+ size = len(content)
elif hasattr(res, "name"):
#this is a filetype object
- size=os.path.getsize(res.name)
+ size = os.path.getsize(res.name)
else:
- size="-"
+ size = "-"
#this is provided by a proxy or direct
- remote_host=environ.get('HTTP_X_FORWARDED_FOR',environ['fapws.remote_addr'])
- self.output.write("%s %s - [%s GMT] \"%s %s %s\" %s %s \"%s\" \"%s\"\n" % (remote_host, environ['HTTP_HOST'], tts, environ['REQUEST_METHOD'], environ['fapws.uri'], environ['wsgi.url_scheme'], start_response.status_code, size, environ.get("HTTP_REFERER", "-"), environ.get('HTTP_USER_AGENT',"-")))
+ remote_host = environ.get('HTTP_X_FORWARDED_FOR', environ['fapws.remote_addr'])
+ self.output.write("%s %s - [%s GMT] \"%s %s %s\" %s %s \"%s\" \"%s\"\n" % (remote_host, environ['HTTP_HOST'], tts, environ['REQUEST_METHOD'], environ['fapws.uri'], environ['wsgi.url_scheme'], start_response.status_code, size, environ.get("HTTP_REFERER", "-"), environ.get('HTTP_USER_AGENT', "-")))
self.output.flush()
return res
return func
-
View
56 fapws/contrib/sessions.py
@@ -12,58 +12,64 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
-import datetime, time
+import binascii
+import datetime
try:
import cPickle as pickle
-except:
+except ImportError:
import pickle
import os
-import binascii
+import time
+
class Session:
- def __init__(self,sessiondb,max_age=10*86400,datetime_fmt="%Y-%m-%d %H:%M:%S"):
- self.sessiondb=sessiondb # must have a get method abd return dictionary like object with sessionid, strdata and expiration_date
- self.datetime_fmt=datetime_fmt
- self.max_age=max_age
+ def __init__(self, sessiondb, max_age=10 * 86400, datetime_fmt="%Y-%m-%d %H:%M:%S"):
+ self.sessiondb = sessiondb # must have a get method abd return dictionary like object with sessionid, strdata and expiration_date
+ self.datetime_fmt = datetime_fmt
+ self.max_age = max_age
#we should always have a sessionid and an expiration date
if not self.sessiondb.get('sessionid', None):
self.newid()
if not self.sessiondb.get('expiration_date', None):
self.update_expdate()
+
def getdata(self):
"return the python objected associated or None in case of expiration"
- exp=self.sessiondb.get('expiration_date',None)
+ exp = self.sessiondb.get('expiration_date', None)
if not exp:
return None
- if type(exp)==type(datetime.datetime(2011,1,1)):
- expdate=exp
- elif type(exp)==type("string") or type(exp)==type(u"string"):
- expdate=datetime.datetime.fromtimestamp(time.mktime(time.strptime(exp, self.datetime_fmt)))
+ if type(exp) is datetime.datetime:
+ expdate = exp
+ elif type(exp) in (str, unicode):
+ expdate = datetime.datetime.fromtimestamp(time.mktime(time.strptime(exp, self.datetime_fmt)))
else:
- raise ValueError, "expiration_Date must be a datetime object or a string (%s)" % self.datetime_fmt
- if expdate<datetime.datetime.now():
+ raise ValueError("expiration_Date must be a datetime object or a string (%s)" % self.datetime_fmt)
+ if expdate < datetime.datetime.now():
#expired
return None
else:
if self.sessiondb['strdata']:
- strdata=str(self.sessiondb['strdata'])
- data=pickle.loads(strdata)
+ strdata = str(self.sessiondb['strdata'])
+ data = pickle.loads(strdata)
return data
else:
return None
+
def setdata(self, data):
- strdata=pickle.dumps(data)
- self.sessiondb['strdata']=strdata
+ strdata = pickle.dumps(data)
+ self.sessiondb['strdata'] = strdata
+
def newid(self):
- sessid=binascii.hexlify(os.urandom(12))
- self.sessiondb['sessionid']=sessid
+ sessid = binascii.hexlify(os.urandom(12))
+ self.sessiondb['sessionid'] = sessid
+
def getid(self):
return self.sessiondb.get('sessionid')
+
def update_expdate(self):
- self.sessiondb['expiration_date']=self._getexpdate()
+ self.sessiondb['expiration_date'] = self._getexpdate()
+
def _getexpdate(self):
- now=datetime.datetime.now()
- exp=now + datetime.timedelta(seconds=self.max_age)
+ now = datetime.datetime.now()
+ exp = now + datetime.timedelta(seconds=self.max_age)
return exp.strftime(self.datetime_fmt)
-
-
View
32 fapws/contrib/views.py
@@ -13,9 +13,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import mimetypes
-import os.path
+import os
import time
+
class Staticfile:
""" Generic class that you can use to dispatch static files
You must use it like this:
@@ -23,27 +24,28 @@ class Staticfile:
evhttp.http_cb("/static/",static)
NOTE: you must be consistent between /rootpath/ and /static/ concerning the ending "/"
"""
- def __init__(self, rootpath="",maxage=None):
- self.rootpath=rootpath
- self.maxage=maxage
+ def __init__(self, rootpath="", maxage=None):
+ self.rootpath = rootpath
+ self.maxage = maxage
+
def __call__(self, environ, start_response):
- fpath=self.rootpath+environ['PATH_INFO']
+ fpath = self.rootpath + environ['PATH_INFO']
try:
- f=open(fpath, "rb")
+ f = open(fpath, "rb")
except:
print "ERROR in Staticfile: file %s not existing" % (fpath)
- start_response('404 File not found',[])
+ start_response('404 File not found', [])
return []
- fmtime=os.path.getmtime(fpath)
- if environ.get('HTTP_IF_NONE_MATCH','NONE')!=str(fmtime):
- headers=[]
+ fmtime = os.path.getmtime(fpath)
+ if environ.get('HTTP_IF_NONE_MATCH', 'NONE') != str(fmtime):
+ headers = []
if self.maxage:
- headers.append(('Cache-control', 'max-age=%s' % int(self.maxage+time.time())))
+ headers.append(('Cache-control', 'max-age=%s' % int(self.maxage + time.time())))
#print "NEW", environ['fapws.uri']
- ftype=mimetypes.guess_type(fpath)[0]
- headers.append(('Content-Type',ftype))
- headers.append(('ETag',fmtime))
- headers.append(('Content-Length',os.path.getsize(fpath)))
+ ftype = mimetypes.guess_type(fpath)[0]
+ headers.append(('Content-Type', ftype))
+ headers.append(('ETag', fmtime))
+ headers.append(('Content-Length', os.path.getsize(fpath)))
start_response('200 OK', headers)
return f
else:
View
11 fapws/contrib/zip.py
@@ -18,23 +18,24 @@
import StringIO
import gzip
+
class Gzip:
#wsgi gzip middelware
def __call__(self, f):
def func(environ, start_response):
- content=f(environ, start_response)
+ content = f(environ, start_response)
if 'gzip' in environ.get('HTTP_ACCEPT_ENCODING', ''):
- if type(content)==type([]):
- content="".join(content)
+ if type(content) is list:
+ content = "".join(content)
else:
#this is a stream
- content=content.read()
+ content = content.read()
sio = StringIO.StringIO()
comp_file = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=sio)
comp_file.write(content)
comp_file.close()
start_response.add_header('Content-Encoding', 'gzip')
- res=sio.getvalue()
+ res = sio.getvalue()
start_response.add_header('Content-Length', len(res))
return [res]
else:
Something went wrong with that request. Please try again.