Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Major code style fixes #21

Merged
4 commits merged into from
Dec 7, 2010
Merged
Show file tree
Hide file tree
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
93 changes: 50 additions & 43 deletions fapws/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -134,53 +142,52 @@ 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
if 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
6 changes: 3 additions & 3 deletions fapws/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
65 changes: 34 additions & 31 deletions fapws/contrib/cgiapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
21 changes: 12 additions & 9 deletions fapws/contrib/django_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 3 additions & 3 deletions fapws/contrib/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []

27 changes: 14 additions & 13 deletions fapws/contrib/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Loading