Exemplo n.º 1
0
def reply():

    from cgi import FieldStorage

    kwargs = FieldStorage()

    if kwargs.has_key('addr') or kwargs.has_key('elseaddr'):
        return whereyoulive_sum.reply(kwargs)
    else:
        return survey()
Exemplo n.º 2
0
    def go(self):
        "run the AdvCGI and show in the web"
        self.cookies = {}
        self.error = ''
        form = FieldStorage()

        if form.keys() == []:
            self.show_form()
            return
       
        if form.has_key('personName'):
            self.cookies['user'] = unquote(strip(form['personName'].value))
            self.user = strip(form['personName'].value)
            result = self.checkDB()
            if result > 0:   #greater than 0 mean name had exist
                self.error = 'Your name %s is exist!' % (self.user)
            if self.user == '':
                self.error = 'Your name is required. (blacnk)'
        else:
            self.cookies['user'] = ''
            self.error = 'Your name is required. (missing)'

        if form.has_key('personPassword'):
            self.passwd = strip(form['personPassword'].value)
            if self.passwd == '':
                self.error = 'Your password is required. (blank)'
        else:
            self.error = 'Your password is required. (missing)'
        if form.has_key('personPassword2'):
            self.passwd2 = strip(form['personPassword2'].value)
            if self.passwd2 == '':
                self.error = 'Your password is required to input again. (blank)'
        else:
            self.error = 'Your password is required to input again. (missing)'

        if len(self.passwd) > 0 and len(self.passwd2) > 0:
            if self.passwd != self.passwd2: 
                self.error = 'Your passwords are not the same!'

        if form.has_key('upfile'):
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
                self.fn = ''
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.do_results()
        else:
            self.show_error()
Exemplo n.º 3
0
        def go(self):
                self.error = ''

                form = FieldStorage()

                if form.keys() == []:
                    #s('calling showForm()\n')
                    self.showForm()
                    return

                if form.has_key('person'):
                        self.who = form['person'].value.strip().title()
                        if self.who == '':
                                self.error = 'Your name is required. (blank)'
                else:
                        self.error = 'Your name is required. (missing)'

                if form.has_key('cookie'):
                        self.cookies['user'] = unquote(form['cookie'].value.strip())
                else:
                        self.cookies['user'] = ''

                self.langs = []
                if form.has_key('lang'):
                        langdata = form['lang']
                        if type(langdata) == type([]):
                                for eachLang in langdata:
                                        self.langs.append(eachLang.value)
                        else:
                                self.langs.append(langdata.value)
                else:
                        self.error = 'At least one language required.'

                if form.has_key('upfile'):
                        upfile = form["upfile"]
                        self.fn = upfile.filename or ''
                        #s('filename is %s??\n' % self.fn)
                        if upfile.file:
                                self.fp = upfile.file
                        else:
                                self.fp = StringIO('(no data)')
                else:
                        self.fp = StringIO('(no file)')
                        self.fn = ''

                if not self.error:
                        #s('calling doResults()\n')
                        self.doResults()
                else:
                        #s('calling showError()\n')
                        self.showError()
Exemplo n.º 4
0
    def __init__(self, session):
        self.consumer = oauth.Consumer(key = OSMOAuth.CONSUMER_KEY, secret = OSMOAuth.SHARED_SECRET)
        self.client = oauth.Client(self.consumer)
        data = session.data
        self.data = data
        args = FieldStorage()
        if args.list != None and args.has_key('reset'):
            data['oauth_token'] = None
            data['oauth_token_secret'] = None
            
        if data.get('oauth_token') != None:
            self.is_authorized = data['oauth_authorized'] == '1'
        else:
            self.request_token()
            
        if not self.is_authorized:
            token = self.request_access_token()
            if not 'oauth_token' in token:
                self.request_token()
            else:
                data['oauth_token'] = token['oauth_token']
                data['oauth_token_secret'] = token['oauth_token_secret']
                data['oauth_authorized'] = '1'
                print session.cookie

        self.access_with()
Exemplo n.º 5
0
def main():

    args = parse_qs(environ['QUERY_STRING'])
    form = FormPost()
    if form.has_key('FLUSH'):
        flush_all()

    if 'update' in args:
        stat()
        return
    
    ats = ['items', 'bytes', 'oldest_item_age', 'hits', 'byte_hits', 'misses']
    samples = mget('sample-times', namespace=NS)
    if not samples:
        stat()
        samples = mget('sample-times', namespace=NS) or []

    s = mmget([str(i) for i in samples], namespace=NS)
    a = []
    if s:
        a = dict([(k, [int(s[d][k]) for d in s]) for k in ats]) # attr -> vals
        a = dict([(k, (max(a[k]), min(a[k]), a[k])) for k in a]) # attrs -> (max, min, vals)
        #a = dict([(k, [61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]]) for k in a]) # attrs -> norml-vals
        a = dict([(k, ([61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]], a[k][1], a[k][0])) for k in a]) # attrs -> norml-vals

    print "Content-type: text/html"
    print ""
    #l = ["rend('"+k+"', %s);"%str([int(s[d][k]) for d in s]) for k in ats]
    #l = ["rend('"+k+"', %s);"%str([int(d) for d in a[k]]) for k in a]
    print """<html><head><script type="text/javascript" src="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js"></script>
<script>
// Using: http://solutoire.com/gchart/
// x = """+repr(a)+"""
function rend(t, d, mx, mn) {
GChart.render({'renderTo': 'stats', 'size': '800x200', colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF', legend:'"""+'|'.join([k for k in a])+"""',  title: t, 'data': d});
}
function main() {
"""
    def rnd(name, data, mxmn, colors, legend):
        print "GChart.render({'size': '480x200&chg=0,20', axistype: 'x,y,r'," # colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF',"
        print "     renderTo: '"+name+"',"
        if len(data) == 2:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"|2,"+','.join([str(i) for i in mxmn[1]])+"',"
        elif len(data) == 1:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"', axistype: 'x,y',"
        print "     colors: '"+','.join(colors)+"',"
        print "     legend:'"+'|'.join([l for l in legend])+"',"
        print "     data: "+str([[int(d) for d in dd] for dd in data])
        print "});"

    #print "rend('stats', %s);"%str([[int(d) for d in a[k][0]] for k in a])
    if a:
        rnd('stats', [a['hits'][0], a['byte_hits'][0]], [a['hits'][1:3], a['byte_hits'][1:3]], ['FF0088', '0077cc'], ["Hits", "Hit Bytes"])
        rnd('stats', [a['items'][0], a['bytes'][0]], [a['items'][1:3], a['bytes'][1:3]], ['FF0088', '0077cc'], ["Items", "Bytes"])
        rnd('stats', [a['misses'][0]], [a['misses'][1:3]], ['FF0088'], ["Miss"])
        rnd('stats', [a['oldest_item_age'][0]], [[x/60 for x in a['oldest_item_age'][1:3]]], ['0077cc'], ["Max Age"])
    print """
Exemplo n.º 6
0
def GetQuery(QueryString, BlankIfMissing =0 ):
    if not InGlobals("FormFieldStorage"):
        from cgi import FieldStorage
        global FormFieldStorage
        FormFieldStorage = FieldStorage()

    if FormFieldStorage.has_key(QueryString):
        retVal = FormFieldStorage[QueryString].value
    else:
        retVal = iif(BlankIfMissing,"",None)

    return retVal
Exemplo n.º 7
0
def AdminHandler(environ, start_response):
	path = get_path_info(environ)
	
	man_regex = r'(env|Gallery|Stored|Sections)$'
	match = re.search(man_regex, path)
	#print('match: {0}'.format(match))
	if match is None:
		return not_found(environ, start_response)
	
	from cgi import FieldStorage
	form = FieldStorage(environ=environ)
	section = form.getfirst('roof', 'imsto')
	action, = match.groups()
	if (action == 'Gallery'):
		limit = 20
		start = 0
		if form.has_key("page") and form["page"].value != "":
			page = int(form["page"].value)
			if page < 1:
				page = 1
			start = limit * (page - 1)
		
		start_response('200 OK', [('Content-type', 'text/javascript')])
		
		imsto = load_imsto(section)
		gallery = imsto.browse(limit, start)
		import datetime
		dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
		if hasattr(imsto, 'close'):
			imsto.close()
		return [json.dumps(gallery, default=dthandler)]
	elif (action == 'Stored'):
		return StoredHandler(environ, start_response)
		#start_response('200 OK', [('Content-type', 'text/plain')])
		#return ['Stored']
	elif  (action == 'env'):
		return print_env(environ, start_response)
	elif action == 'Sections':
		start_response('200 OK', [('Content-type', 'text/javascript')])
		config = Config()
		return [json.dumps(config.sections())]
	
	start_response('200 OK', [('Content-type', 'text/plain')])
	return [path_info]
Exemplo n.º 8
0
def manage(environ, start_response):
	path_info = environ.get('PATH_INFO', '')
	
	man_regex = r'^/([A-Za-z]+)/(env|Gallery|Stored)'
	match = re.search(man_regex, path_info)
	#print('match: {0}'.format(match))
	if match is None:
		return not_found(environ, start_response)
	
	action = match.groups()[1]
	if (action == 'Gallery'):
		from cgi import FieldStorage
		form = FieldStorage(environ=environ)
		limit = 20
		start = 0
		if form.has_key("page") and form["page"].value != "":
			page = int(form["page"].value)
			if page < 1:
				page = 1
			start = limit * (page - 1)
		
		start_response('200 OK', [('Content-type', 'text/plain')])
		
		imsto = ImSto()
		gallery = imsto.browse(limit, start)
		import datetime
		dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
		if hasattr(imsto, 'close'):
			imsto.close()
		return [json.dumps(gallery, default=dthandler)]
	elif (action == 'Stored'):
		return stored_process(environ, start_response)
		#start_response('200 OK', [('Content-type', 'text/plain')])
		#return ['Stored']
	elif  (action == 'env'):
		from _respond import print_env
		return print_env(environ, start_response)
	
	start_response('200 OK', [('Content-type', 'text/plain')])
	return [path_info]
Exemplo n.º 9
0
def main():

    args = parse_qs(environ['QUERY_STRING'])
    form = FormPost()
    if form.has_key('FLUSH'):
        flush_all()

    if 'update' in args:
        stat()
        return

    ats = ['items', 'bytes', 'oldest_item_age', 'hits', 'byte_hits', 'misses']
    samples = mget('sample-times', namespace=NS)
    if not samples:
        stat()
        samples = mget('sample-times', namespace=NS)

    s = mmget([str(i) for i in samples], namespace=NS)
    #
    a = dict([(k, [int(s[d][k]) for d in s]) for k in ats])  # attr -> vals
    a = dict([(k, (max(a[k]), min(a[k]), a[k]))
              for k in a])  # attrs -> (max, min, vals)
    #a = dict([(k, [61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]]) for k in a]) # attrs -> norml-vals
    a = dict([
        (k,
         ([61 * (v + 1 - a[k][1]) / (a[k][0] + 1 - a[k][1])
           for v in a[k][2]], a[k][1], a[k][0])) for k in a
    ])  # attrs -> norml-vals
    print "Content-type: text/html"
    print ""
    #l = ["rend('"+k+"', %s);"%str([int(s[d][k]) for d in s]) for k in ats]
    #l = ["rend('"+k+"', %s);"%str([int(d) for d in a[k]]) for k in a]
    print """<html><head><script type="text/javascript" src="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js"></script>
<script>
// Using: http://solutoire.com/gchart/
// x = """ + repr(a) + """
function rend(t, d, mx, mn) {
GChart.render({'renderTo': 'stats', 'size': '800x200', colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF', legend:'""" + '|'.join(
        [k for k in a]) + """',  title: t, 'data': d});
}
function main() {
"""

    def rnd(name, data, mxmn, colors, legend):
        print "GChart.render({'size': '480x200&chg=0,20', axistype: 'x,y,r',"  # colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF',"
        print "     renderTo: '" + name + "',"
        if len(data) == 2:
            print "     axisrange: '1," + ','.join([
                str(i) for i in mxmn[0]
            ]) + "|2," + ','.join([str(i) for i in mxmn[1]]) + "',"
        elif len(data) == 1:
            print "     axisrange: '1," + ','.join([str(i) for i in mxmn[0]
                                                    ]) + "', axistype: 'x,y',"
        print "     colors: '" + ','.join(colors) + "',"
        print "     legend:'" + '|'.join([l for l in legend]) + "',"
        print "     data: " + str([[int(d) for d in dd] for dd in data])
        print "});"

    #print "rend('stats', %s);"%str([[int(d) for d in a[k][0]] for k in a])
    rnd('stats', [a['hits'][0], a['byte_hits'][0]],
        [a['hits'][1:3], a['byte_hits'][1:3]], ['FF0088', '0077cc'],
        ["Hits", "Hit Bytes"])
    rnd('stats', [a['items'][0], a['bytes'][0]],
        [a['items'][1:3], a['bytes'][1:3]], ['FF0088', '0077cc'],
        ["Items", "Bytes"])
    rnd('stats', [a['misses'][0]], [a['misses'][1:3]], ['FF0088'], ["Miss"])
    rnd('stats', [a['oldest_item_age'][0]],
        [[x / 60 for x in a['oldest_item_age'][1:3]]], ['0077cc'], ["Max Age"])
    print """
Exemplo n.º 10
0
# Some hosts will need to have document_root appended
# to sys.path to be able to find user modules
import sys, os
sys.path.append(os.environ['DOCUMENT_ROOT'])

from cgi import FieldStorage
from session import Session
from osmoauth import OSMOAuth

session = Session(expires=365*24*60*60, cookie_path='/')
api = OSMOAuth(session)

args = FieldStorage()

if args.list != None and args.has_key('login'):
    # Just inisialyse the session to be shure that we are autorised.
    print
    print "OK"

elif args.list != None and args.has_key('oauth_token'):
    # auth callback.
    print
    print "logged OK"

elif args.list != None and args.has_key('new'):
    # create changeset
    empty_changeset = """<?xml version="1.0" encoding="UTF-8"?>
<osm>
  <changeset>
    <tag k="created_by" v="HTML editor 0.1 ([email protected])"/>
Exemplo n.º 11
0
def wsgi_handle_request( environ, start_response ):
   '''
   handle one WSGI request
   '''
   
   global METADATA_FIELD_NAME
   global DATA_FIELD_NAME
   
   required_post_fields = [METADATA_FIELD_NAME, DATA_FIELD_NAME]
   required_delete_fields = [METADATA_FIELD_NAME]
   
   if environ['REQUEST_METHOD'] == 'GET':
      # GET request
      url_path = environ['PATH_INFO']
      outfile = StringIO()
      
      rc, msg = get( url_path, outfile )
      
      if rc == 200:
         size = outfile.len
         outfile.seek(0)
         headers = [('Content-Type', 'application/octet-stream'), ('Content-Length', str(size))]
         start_response( '200 %s' % msg, headers )
         
         return FileWrapper( outfile )
      
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg) )
      
   elif environ['REQUEST_METHOD'] == 'POST':
      # POST request.
      # get POST'ed fields
      post_fields = FieldStorage( fp=environ['wsgi.input'], environ=environ )
      
      # validate
      for f in required_post_fields:
         if f not in post_fields.keys():
            return invalid_request( start_response )
      
      metadata_field = post_fields[METADATA_FIELD_NAME].value
      infile = post_fields[DATA_FIELD_NAME].file
      
      # if no file was given, then make a stringIO wrapper around the given string
      if infile == None:
         infile = StringIO( post_fields[DATA_FIELD_NAME].value )
      
      rc, msg = post( metadata_field, infile )
      
      if rc == 200:
         return valid_request( start_response )
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg), resp="error code %s\n" % str(rc))

   elif environ['REQUEST_METHOD'] == 'DELETE':
      # DELETE request
      post_fields = FieldStorage( fp=environ['wsgi.input'], environ=environ )
      
      # validate
      if not post_fields.has_key(METADATA_FIELD_NAME):
         return invalid_request( start_response )
      
      metadata_field = post_fields[METADATA_FIELD_NAME].value
      
      rc, msg = delete( metadata_field )
      
      if rc == 200:
         return valid_request( start_response )
      
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg), resp="error code %s\n" % str(rc))
         
   else:
      # not supported
      return invalid_request( start_response, status="501 No Such Method", resp="Method not supported\n" )
Exemplo n.º 12
0
#    Creation date: 26-May-2013 22:50 (eg)
# Last file update: 27-May-2013 16:35 (eg)
#

from os import *
from cgi import FieldStorage, escape

# Le header
print("Content-type: text/html; charset=utf-8")
print("")

# Le contenu de la page
print("<html><head><title>Test formulaires CGI</title></head><body>")

form = FieldStorage()

if form.has_key("file"):
    print("Nom de fichier chez le client: <i>%s</i><br/>" % \
              (form["file"].filename))
    print("Contenu du fichier: <hr /><pre>%s<pre><hr />" % \
              (escape(form["file"].value)))
else:
    # Pas de fichier: afficher le formulaire
    print("<form method='POST' enctype='multipart/form-data'>")
    print("Nom du fichier à charger: <input type='file' name='file' /> <br />")
    print("<input type='submit' name='submit' value='Envoyer' />")
    print("</form>")


print("</body></html>")
Exemplo n.º 13
0
 def generage_qr(environ, start_response):
     if environ['REQUEST_METHOD'].lower() == "get":
         start_response('200 OK', [('Content-Type','text/html')])
         return """
             <?xml version="1.0" encoding="UTF-8"?>
             <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
             <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
             <head>
                   <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
             </head>
             <body>
             <form action='/qr/' method='post'>
                 <p><input type='text' style='width:200px;height:30px;font-size:17px;' placeholder='内容' name='url' ></p>
                 <p><input type='text' style='width:200px;height:30px;font-size:17px;' placeholder='中心图' name='tiny' ></p>
                 <p><input type='submit' value='Generate'></p>
             </form>
             </body>
             </html>
             """
     else:
         form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
         _url = form['url'].value
         _tiny = ''
         if form.has_key('tiny'):
             _tiny = form['tiny'].value or ''
         qr = qrcode.QRCode(
             version=2,
             error_correction=qrcode.ERROR_CORRECT_H,
             box_size=10,
             )
         qr.make(fit=True)
         qr.add_data(_url)
         img = qr.make_image()
         err = ""
         if _tiny.startswith('http'):
             try:
                 _buf = urllib2.urlopen(_tiny).read()
                 _t_im = Image.open(StringIO.StringIO(_buf))
                 #//_t_im.verify()
                 s = img.size
                 print _t_im, _t_im.size, s
                 t = (int(s[0] / 5), int(s[1] / 5))
                 _t_im = _t_im.resize(t)
                 img.paste(_t_im, ((s[0] - (s[0] / 5))/2, (s[1] - (s[1] / 5))/2))
             except:
                 print traceback.format_exc()
                 err = '打开远程文件出错'
                 pass
         output = StringIO.StringIO()
         img.save(output, 'PNG')
         contents = output.getvalue().encode("base64")
         output.close()
         start_response('200 OK', [('Content-Type','text/html')])
         return """
             <?xml version="1.0" encoding="UTF-8"?>
             <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
             <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
             <head>
                   <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
             </head>
             <body>
             <form action='/qr/' method='post'>
                 <p><input type='text' style='width:200px;height:30px;font-size:17px;' placeholder='内容' name='url' ></p>
                 <p><input type='text' style='width:200px;height:30px;font-size:17px;' placeholder='中心图' name='tiny' ></p>
                 <p><input type='submit' value='Generate'></p>
             </form>
             <hr>
             %s
             <hr>
             <img style="width:600px;height:600px"src='data:image/png;base64,%s' />"
             </body>
             </html>
             """ % (err, contents)