예제 #1
0
		def read():
	
			if not len(self.egs_data_file):
				raise ValueError('egs_data_file must be set before calling this function')
			if not os.path.exists(self.egs_data_file):
				raise IOError("Unable to find DATA file\n\t%s" % (self.egs_data_file))
			
			startTime = dt.now()

			try:
				with open(self.egs_data_file) as json_data:
					self.egs_data = json.load(json_data)
			except:
				cgitb.handler()
				sys.exit()
	
			row_count = 0
			try:
				'''
					create the pickle file for next time a user requests the file
				'''
				pickle_egs_data_file = self.egs_data_file.replace('.json', '.p')
				try:
					pickle.dump([self.egs_data], open(pickle_egs_data_file, 'wb'), pickle.HIGHEST_PROTOCOL)
				finally:
					pass
	
			except:
				cgitb.handler()
				sys.exit()
		
			return row_count
예제 #2
0
def cgidebugerror():
    _wrappedstdout = sys.stdout

    sys.stdout = web._oldstdout
    cgitb.handler()

    sys.stdout = _wrappedstdout
예제 #3
0
def process():
    error = ''
    form = cgi.FieldStorage()

    if 'comment_content' in form:
        cgitb.handler()
        test1 = form['comment_content'].value
        fp = open(file_path, 'a+',encoding="UTF-8")
        fp.write("%s%s" % (test1, '\n'))
        fp.close()
        with codecs.open(file_path, 'r', encoding="UTF-8") as f, codecs.open\
        ("C:\\Users\\zach.zhang\\Desktop\\testzach\\webtest\\cgi-bin\\result666.txt", 'w', encoding="gbk") as wf:
            for line in f:
                #lines = line.strip().split('\t')
                newline = line
                wf.write(newline)
        showthank()
        return
    if 'feedback_content' in form:
        test2 = form['feedback_content'].value
        # fp = open(file_path, 'a+')
        # test2 = bytes(test2, 'utf-8')
        # fp.write(test2)
        # fp.close()
        showthank()
        return
    if 'showCM' in form:
        showComment()
        return
    if 'showFB' in form:
        showfeedback()
        return
    if 'person' in form:
        who = form['person'].value
    else:
        who = 'New User'
    
    if 'howmany' in form:
        howmany = form['howmany'].value
    else:
        if 'action' in form and \
            form['action'].value == 'edit':
            error = 'Please select number of friends.'
        else:
            howmany = 0

    if not error:
        if 'action' in form and \
            form['action'].value != "reedit":
            doResult(who,howmany)
        else:
            showForm(who,howmany)
    else:
        showError(error)

    if 'test' in form:
        fp = open(r'C:\Users\zach.zhang\Desktop\testzach\webtest\cgi-bin\file.txt','r+')
예제 #4
0
def Error(ex):
  """ex is an exception"""
  print 'Content-type: text/html\n\n'
  print '<html><body><h2>Congratulations!  You found a bug in Webnote!</h2>'
  print '<p>(or perhaps the database is down)</p>'
  print ("<p>We'll try to have webnote up and running again as soon as "
         "possible</p>")
  if SHOWDEBUG:
    import cgitb
    cgitb.handler()
  print '</body></html>'
  log(str(ex))
예제 #5
0
        def read():

            if not len(self.huc_file):
                raise ValueError(
                    'huc_file must be set before calling this function')
            if not os.path.exists(self.huc_file):
                raise IOError("Unable to find HUC file\n\t%s" %
                              (self.huc_file))

            startTime = dt.now()

            try:
                infile = open(self.huc_file, 'r')
                reader = csv.DictReader(infile)
            except:
                cgitb.handler()
                sys.exit()

            row_count = 0
            try:
                for row in reader:
                    row_count += 1
                    code = row['Code']
                    code_string = str(code)

                    # zero-pad the HUC codes
                    if len(code_string) % 2 != 0:
                        code_string = '0' + code_string

                    # remove the states off the names - except for cataloging units
                    if len(code_string) < 8:
                        name = row['Name']
                        a = re.match('(^.+)\s\(', row['Name'])
                        if a and a.group(1):
                            row['Name'] = a.group(1)

                    self.huc_data[row['Category']][code_string] = row
                '''
					create the pickle file for next time a user requests the file
				'''
                pickle_huc_file = self.huc_file.replace('.csv', '.p')
                try:
                    pickle.dump([self.huc_data], open(pickle_huc_file, 'wb'),
                                pickle.HIGHEST_PROTOCOL)
                finally:
                    pass

            except:
                cgitb.handler()
                sys.exit()

            return row_count
예제 #6
0
	def handleException(self, parents, request, exc_info0, exc_info1, exc_info2):
		"This hook gets called when an exception occures while publishing"
		print "DBG!: handleException", parents, request, exc_info0, exc_info1, exc_info2
		err_msg = str(exc_info1)
		if exc_info0 == "Redirect":
			raise
		else:
			print "Content-type: text/html\n"
			try:
				import pydoc #XXX: short term fix
				pydoc.HTMLRepr.repr_str = pydoc.HTMLRepr.repr_string
				import cgitb
				cgitb.handler()
			except ImportError:
				print string.replace(err_msg, "Zope", self.name)
예제 #7
0
def test(Mode=0):
    if Mode == 0:
        func(1, 0)
    elif Mode == 1:
        try:
            func(1, 0)
        except:
            info = sys.exc_info()
            print('4.info=', cgitb.text(info))
    elif Mode == 2:
        cgitb.handler()
        func(1, 0)
    elif Mode == 3:
        cgitb.enable(display=0, logdir='./cgi_log', context=5, format='text')
        cgitb.handler()
        func(1, 0)
예제 #8
0
def FormatException(exc_info):
    """Gets information from exception info tuple.

  Args:
    exc_info: exception info tuple (type, value, traceback)
  Returns:
    exception description in a list - wsgi application response format.
  """
    return [cgitb.handler(exc_info)]
def respond_with_reservation_confirmation(name,
                                          email,
                                          places,
                                          date,
                                          outside_fondus,
                                          outside_assiettes,
                                          outside_bolo,
                                          outside_scampis,
                                          outside_tiramisu,
                                          outside_tranches,
                                          inside_fondus,
                                          inside_assiettes,
                                          inside_bolo,
                                          inside_scampis,
                                          inside_tiramisu,
                                          inside_tranches,
                                          gdpr_accepts_use,
                                          connection,
                                          configuration,
                                          origin=None):
    try:
        new_row = save_data_sqlite3(
            name, email, places, date, outside_fondus, outside_assiettes,
            outside_bolo, outside_scampis, outside_tiramisu, outside_tranches,
            inside_fondus, inside_assiettes, inside_bolo, inside_scampis,
            inside_tiramisu, inside_tranches, gdpr_accepts_use, origin,
            connection)
        redirection_url = make_show_reservation_url(
            new_row.uuid,
            script_name=(os.environ["SCRIPT_NAME"] if origin is None else
                         os.path.dirname(os.environ["SCRIPT_NAME"])))
    except Exception:
        respond_with_reservation_failed(configuration)
        cgitb.handler()
    else:
        redirect(redirection_url)
예제 #10
0
    POPULATION_ESTIMATE = FRESH_BATCH.Run_Batch()
except:
    #print('Content-Type: text/html')
    #print('Location: http://cas-web0.biossys.oregonstate.edu/error.html')
    #print('<html>')
    #print('<head>')
    #print('<meta http-equiv="refresh" '
    #      'content="0;url=http://cas-web0.biossys.oregonstate.edu/error.html" />')
    #print('<title>You are going to be redirected</title>')
    #print('</head>')
    #print('<body>')
    #print('Wait <a href="http://cas-web0.biossys.oregonstate.edu/error.html">'
    #      'Click here if you are not redirected</a>')
    #print('</body>')
    #print('</html>')
    cgitb.handler()

SHORT_RESULTS = {
    'Tab Name': [],
    'Elevation': [],
    'Reservoir(used for elevation)': [],
    'Daphnia Density': [],
    'Light': [],
    'Daphnia Size': [],
    'Min Depth': [],
    'Max Depth': [],
    'Min Temp': [],
    'Max Temp': [],
    'Daphnia Year': [],
    'Daphnia Month': [],
    'Daphnia Site': [],
예제 #11
0
파일: index.py 프로젝트: ensoft/tiqit
def excHandler(*args):
    print "Content-Type: text/html; charset=utf-8"
    print "\r\n\r\n"
    print "<!--: spam"
    print "Status: 500"
    cgitb.handler(args)
예제 #12
0
def main():
    cgitb.enable()

    if APP_ROOT_URI is None:
        sys.stdout.write("Content-Type: text/plain; charset=UTF-8\r\n\r\n")
        print "Sovelluksen juuri-URI:tä (APP_ROOT_URI) ei ole asetettu."
        print
        print "APP_ROOT_URI määrittää, mistä rohmotin staattiset tiedostot,"
        print "kuten CSS-tyylit ja kuvat löytyvät."
        print
        print "Esim. APP_ROOT_URI='/~me/rohmotti'"
        print "  ==> tyylit: '/~me/rohmotti/styles'"
        print "  ==> kuvat: '/~me/rohmotti/images'"
        print
        print "Muokkaa asetuksia rohmotti.py:n alussa!"
        return 0

    form = cgi.FieldStorage()

    #
    # Muodosta tietokantayhteys. Aseta oletuspolku.
    #
    conn = psycopg2.connect(DSN)
    conn.cursor().execute("""SET search_path TO %s, "$user", public""" % (DBSCHEMA))
    conn.commit()

    #
    # Setup database connection for the object model
    #
    DatabaseObject.setDatabaseConnection(conn)

    #
    # PUT, DELETE -tukikikka: jos lomakkeessa on 'method_override'
    # arvolla 'PUT' tai 'DELETE' ja käytetty kyselymetodi on POST,
    # tulkitse kyselymetodiksi 'method_override':n arvo.
    #
    request_method = os.environ.get("REQUEST_METHOD")
    if request_method == "POST":
        method_override = form.getvalue("method_override")
        if method_override in ["PUT", "DELETE"]:
            request_method = method_override

    app_root_uri = APP_ROOT_URI
    script_name = os.environ.get("SCRIPT_NAME", "")
    path_info = os.environ.get("PATH_INFO", "")
    full_path = script_name + path_info
    request_uri = os.environ.get("REQUEST_URI", "")
    remote_addr = os.environ.get("REMOTE_ADDR")
    http_x_forwarded_for = os.environ.get("HTTP_X_FORWARDED_FOR")

    if http_x_forwarded_for is not None:
        effective_remote_addr = http_x_forwarded_for
    else:
        effective_remote_addr = remote_addr

    conf = {
        "request_method": request_method,
        "script_name": script_name,
        "app_root_uri": app_root_uri,
        "path_info": path_info,
        "full_path": full_path,
        "request_uri": request_uri,
        "remote_addr": remote_addr,
        "http_x_forwarded_for": http_x_forwarded_for,
        "effective_remote_addr": effective_remote_addr,
    }

    html_template_filename = get_html_template_filename()

    C = Cookie.SimpleCookie()
    C.load(os.environ.get("HTTP_COOKIE", ""))
    sessio = Sessio.new_from_cookie(C)
    conf["sessio"] = sessio

    navigation = (
        """\
        <span class="navigation">
            <ul class="navigation">
                <li class="navigation"><a href="%(script_name)s">Rohmotti</a></li>
                <li class="navigation"><a href="%(script_name)s/resepti">Reseptit</a></li>
                <li class="navigation"><a href="%(script_name)s/ruokaaine">Ruoka-aineet</a></li>
                <li class="navigation"><a href="%(script_name)s/henkilo">Henkilöt</a></li>
                <li class="navigation"><a href="%(script_name)s/haku">Haku</a></li>
                <li class="navigation"><a href="%(script_name)s/kirjautuminen">Kirjautuminen</a></li>
            </ul>
        </span>"""
        % conf
    )

    render_dict = {
        "REQUEST_URI": request_uri,
        "APP_ROOT_URI": app_root_uri,
        "FULL_PATH": full_path,
        "navigation": navigation,
    }

    mode = "development"

    module_to_load = get_handler_name()
    handler = None
    if module_to_load is not None:
        module = import_module(module_to_load)
        handler = module.Handler(form, conf)

    handler_return = None
    if handler is not None:
        try:
            handler_return = handler.handle()
        except Exception:
            if mode == "production":
                cgi.test()
            else:
                cgitb.handler()

        if handler_return is None:
            return

        render_dict.update(handler_return[1])
        sys.stdout.write("\r\n".join(handler_return[0]) + "\r\n\r\n")
    else:
        #
        # Oletusotsakkeet
        #
        sys.stdout.write("Content-Type: text/html; charset=UTF-8\r\n\r\n")

    debug = False
    try:
        debug = form.getvalue("debug")
    except Exception:
        pass

    if html_template_filename is not None:
        if debug:
            print cgi.print_environ()

    if html_template_filename is not None:
        f = open(get_html_template_filename(), "r")
        if f is None:
            print "Ei voinut avata tiedostoa!"
        html_template_string = f.read()
        s = Template(html_template_string)
        print s.safe_substitute(render_dict)
예제 #13
0
파일: nodes.py 프로젝트: xxoolm/Ryven
 def update_event(self, inp=-1):
     self.set_output_val(0, cgitb.handler(self.input(0)))
예제 #14
0
def excHandler(*args):
    print "<!--: spam"
    print "Status: 500"
    cgitb.handler(args)
예제 #15
0
 def handle_exception(self, exception, debug_mode):
     """http://d.hatena.ne.jp/griefworker/20100302/handle_exception"""
     logging.exception(exception)
     #super(BaseHandler, self).handle_exception(exception, debug_mode)
     self.response.out.write(cgitb.handler())
예제 #16
0
파일: browse.py 프로젝트: chfoo/ytdata
	#			print """<br/><br/>http://youtube.com/watch?v=%s """ % id
			else:
				print """\"%s\",""" % id
			
			n += 1
			
			if n % 128 == 0:
				sys.stdout.flush()
			
			
#		f.close()
		
		if not is_bot:
			print_pager(page, len(l) * LINES / LINES_PER_PAGE, form)		
		
			print "<code><small>"
#			print p.communicate()[1].replace("\n", "<br/>").replace(" ", "&nbsp;")
			print "</small></code>"
		
			print """</body></html>"""
		else:
			print """null])"""
		
	except:
		print "Status: 500 Internal server error"
		print "Content-Type: text/html; charset=utf-8"
		print 
		print "<html><body><big>Internal server error</big><hr/>"
		cgitb.handler()
		print "</body></html>"
  for i in data:
  
   name=i[0];
   
   name=name.upper();
   
   drop=drop+item3+i[5]+"'"+item4+name+item5;
   
  drop=drop+"</select></p>";
  
  html6='''<h2 align = "center">Select the Company to Get the Information<br><br>''';
 
  htmlformat=html+html6+drop+html4;
 
  print(htmlformat);
  
  company=form.getvalue('company');
  
  if "sub" in form:
   
   ck['company']=company;
  
   print(ck.js_output());
  
   print(html9);
     
except:

 cgitb.handler();
예제 #18
0
def runVlad(form):
    args = []

    # config file
    cfgfile = os.path.abspath(
        os.path.join(os.path.dirname(__file__), "config.cfg"))
    args.append("-g")
    args.append(cfgfile)

    # when running as CGI, clean out temp files
    args.append("--cleanTempFiles")

    # run name
    if "runname" in form:
        args.append("-R")
        args.append(form["runname"].value)

    # analysis type
    if "analysis" in form:
        args.append("-y")
        args.append(form["analysis"].value)

    # annotation set
    if "annotationset" in form:
        aset = form["annotationset"].value
        aset = aset.split(":", 1)[0]
        if aset == "__upload__":
            handleUploads(form, args)
        else:
            args.append("-a")
            args.append(aset)

    # evidence codes
    if "eCodes" in form:
        ecs = form.getlist("eCodes")
        if len(ecs) == 1:
            ecs = ecs[0].replace(",", " ").split()
        val = ",".join(ecs)
        args.append("-x")
        args.append(val)

    # query sets
    i = 0
    while True:
        qsname = 'qs' + str(i)
        qsfname = qsname + 'file'
        qssname = qsname + 'name'
        qscname = qsname + 'color'
        if qsname not in form:
            break
        qs = form[qsname]
        qsf = form[qsfname]
        if qsf.filename:
            args.append("-q")
            args.append(qsf.value.decode('utf-8'))
        elif qs.value:
            args.append("-q")
            args.append(qs.value)
        else:
            break
        #
        qsn = form[qssname].value
        if qsn:
            args.append("-n")
            args.append(qsn)
        #
        qsc = form[qscname].value
        if qsc:
            args.append("-c")
            args.append(qsc)
        i += 1

    # universe set
    if 'usfname' in form and form['usfname'].filename:
        args.append("-u")
        args.append(form['usfname'].value)
    elif 'usids' in form:
        args.append("-u")
        args.append(form['usids'].value)

    # spreadsheet output enable
    if "tExcel" in form:
        args.append("--tExcel")
    if "tHtml" in form:
        args.append("--tHtml")
    if "tText" in form:
        args.append("--tText")

    # graphic output enable
    if "gEnable" in form:
        args.append("--gEnable")
    else:
        args.append("--gDisable")

    if "gBackground" in form:
        args.append("--gBackground")
        args.append(form.getvalue("gBackground"))

    if "gNodeColor" in form:
        args.append("--gNodeColor")
        args.append(form.getvalue("gNodeColor"))

    if "gROI" in form:
        args.append("--gROI")
        args.append(form.getvalue("gROI"))

    if "gMaxImgSize" in form:
        args.append("--gMaxImgSize")
        args.append(form.getvalue("gMaxImgSize"))

    if "gLabelEnable" in form:
        args.append("--gLabelEnable")
    else:
        args.append("--gLabelDisable")

    if "gLimitBy" in form:
        limitby = form['gLimitBy'].value
        cutoff = form.getvalue("gValue")
        if limitby == "topn":
            cutoff = str(abs(int(cutoff)))
        elif limitby == "topnlocal":
            cutoff = str(-abs(int(cutoff)))
        elif limitby == "pval":
            try:
                exp = -abs(int(cutoff))
                cutoff = str(10**exp)
            except ValueError:
                cutoff = str(float(cutoff))
        args.append("--gCutoff")
        args.append(cutoff)

    if "gCull" in form:
        args.append("--gCull")

    # write to stdout
    args.append("-O")
    args.append("-")

    try:
        libvlad.VladCGI().go(args)
    except:
        cgitb.handler()