Example #1
0
def main():
    """ Go main Go """
    check_load()
    form = cgi.FieldStorage()
    try:
        tzinfo = pytz.timezone(form.getfirst("tz", "Etc/UTC"))
    except pytz.exceptions.UnknownTimeZoneError as exp:
        sys.stdout.write("Content-type: text/plain\n\n")
        sys.stdout.write("Invalid Timezone (tz) provided")
        sys.stderr.write("asos.py invalid tz: %s\n" % (exp, ))
        sys.exit()
    pgconn = get_dbconn('asos')
    acursor = pgconn.cursor('mystream',
                            cursor_factory=psycopg2.extras.DictCursor)

    # Save direct to disk or view in browser
    direct = True if form.getfirst('direct', 'no') == 'yes' else False
    report_type = form.getlist('report_type')
    stations = get_stations(form)
    if direct:
        sys.stdout.write('Content-type: application/octet-stream\n')
        fn = "%s.txt" % (stations[0],)
        if len(stations) > 1:
            fn = "asos.txt"
        sys.stdout.write('Content-Disposition: attachment; filename=%s\n\n' % (
                         fn,))
    else:
        sys.stdout.write("Content-type: text/plain \n\n")

    dbstations = stations
    if len(dbstations) == 1:
        dbstations.append('XYZXYZ')

    dataVars = form.getlist("data")
    sts, ets = get_time_bounds(form, tzinfo)

    delim = form.getfirst("format", "onlycomma")

    if "all" in dataVars:
        queryCols = ("tmpf, dwpf, relh, drct, sknt, p01i, alti, mslp, "
                     "vsby, gust, skyc1, skyc2, skyc3, skyc4, skyl1, "
                     "skyl2, skyl3, skyl4, presentwx, metar")
        outCols = ['tmpf', 'dwpf', 'relh', 'drct', 'sknt', 'p01i', 'alti',
                   'mslp', 'vsby', 'gust', 'skyc1', 'skyc2', 'skyc3',
                   'skyc4', 'skyl1', 'skyl2', 'skyl3', 'skyl4',
                   'presentwx', 'metar']
    else:
        for _colname in ['station', 'valid']:
            if _colname in dataVars:
                dataVars.remove(_colname)
        dataVars = tuple(dataVars)
        outCols = dataVars
        dataVars = str(dataVars)[1:-2]
        queryCols = re.sub("'", " ", dataVars)

    if delim in ["tdf", "onlytdf"]:
        rD = "\t"
        queryCols = re.sub(",", "\t", queryCols)
    else:
        rD = ","

    gtxt = {}
    gisextra = False
    if form.getfirst("latlon", "no") == "yes":
        gisextra = True
        mesosite = get_dbconn('mesosite')
        mcursor = mesosite.cursor()
        mcursor.execute("""SELECT id, ST_x(geom) as lon, ST_y(geom) as lat
             from stations WHERE id in %s
             and (network ~* 'AWOS' or network ~* 'ASOS')
        """, (tuple(dbstations),))
        for row in mcursor:
            gtxt[row[0]] = "%.4f%s%.4f%s" % (row[1], rD, row[2], rD)

    rlimiter = ""
    if len(report_type) == 1:
        rlimiter = " and report_type = %s" % (int(report_type[0]),)
    elif len(report_type) > 1:
        rlimiter = (" and report_type in %s"
                    ) % (tuple([int(a) for a in report_type]), )
    acursor.execute("""SELECT * from alldata
      WHERE valid >= %s and valid < %s and station in %s """+rlimiter+"""
      ORDER by valid ASC""", (sts, ets, tuple(dbstations)))

    if delim not in ['onlytdf', 'onlycomma']:
        sys.stdout.write("#DEBUG: Format Typ    -> %s\n" % (delim,))
        sys.stdout.write("#DEBUG: Time Period   -> %s %s\n" % (sts, ets))
        sys.stdout.write("#DEBUG: Time Zone     -> %s\n" % (tzinfo,))
        sys.stdout.write(("#DEBUG: Data Contact   -> daryl herzmann "
                          "[email protected] 515-294-5978\n"))
        sys.stdout.write("#DEBUG: Entries Found -> %s\n" % (acursor.rowcount,))
    sys.stdout.write("station"+rD+"valid"+rD)
    if gisextra:
        sys.stdout.write("lon"+rD+"lat"+rD)
    sys.stdout.write(queryCols+"\n")

    for row in acursor:
        sys.stdout.write(row["station"] + rD)
        sys.stdout.write(
            (row["valid"].astimezone(tzinfo)).strftime("%Y-%m-%d %H:%M") + rD)
        if gisextra:
            sys.stdout.write(gtxt.get(row['station'], "M%sM%s" % (rD, rD)))
        r = []
        for data1 in outCols:
            if data1 == 'relh':
                if row['tmpf'] is not None and row['dwpf'] is not None:
                    tmpf = temperature(row['tmpf'], 'F')
                    dwpf = temperature(row['dwpf'], 'F')
                    val = meteorology.relh(tmpf, dwpf)
                    r.append("%.2f" % (val.value("%"),))
                else:
                    r.append("M")
            elif data1 == 'sped':
                if row['sknt'] >= 0:
                    r.append("%.1f" % (speed(row['sknt'],
                                             'KT').value('MPH'), ))
                else:
                    r.append("M")
            elif data1 == 'gust_mph':
                if row['gust'] >= 0:
                    r.append("%.1f" % (speed(row['gust'],
                                             'KT').value('MPH'), ))
                else:
                    r.append("M")
            elif data1 == 'p01m':
                if row['p01i'] >= 0:
                    r.append("%.2f" % (row['p01i'] * 25.4, ))
                else:
                    r.append("M")
            elif data1 == 'tmpc':
                if row['tmpf'] is not None:
                    val = temperature(row['tmpf'], 'F').value('C')
                    r.append("%.2f" % (val, ))
                else:
                    r.append("M")
            elif data1 == 'dwpc':
                if row['dwpf'] is not None:
                    val = temperature(row['dwpf'], 'F').value('C')
                    r.append("%.2f" % (val, ))
                else:
                    r.append("M")
            elif data1 == 'presentwx':
                if row['presentwx'] is not None:
                    r.append("%s" % (row['presentwx'].replace(",", " "), ))
                else:
                    r.append("M")
            elif data1 in ["metar", "skyc1", "skyc2", "skyc3", "skyc4"]:
                if row[data1] is None:
                    r.append("M")
                else:
                    r.append("%s" % (row[data1].replace(",", " "), ))
            elif (row.get(data1) is None or row[data1] <= -99.0 or
                  row[data1] == "M"):
                r.append("M")
            else:
                r.append("%2.2f" % (row[data1], ))
        sys.stdout.write("%s\n" % (rD.join(r),))
Example #2
0
#!/usr/bin/python3

import cgi
import subprocess

print("content-type: text/html")
print()

mydata = cgi.FieldStorage()
volume = mydata.getvalue("vol_name")

output = subprocess.getoutput("sudo docker volume inspect " + volume)
print(output)
Example #3
0
#!/usr/bin/python36

import subprocess as sp
import os
import cgi

print("content-type: text/html")
print()

print("""
<form action='http://192.168.43.171/cgi-bin/service.py'/>
Enter the service name:
<input name='name'/>
</br>
<input type='submit'/>
</br>
""")

data = cgi.FieldStorage()  #alotts mydata variable to the cgi variable
name = data.getvalue("name")

k = sp.getstatusoutput(
    "sudo ansible-playbook playbooks/service.yml --extra-vars 'x={}'".format(
        name))
print(k)
if (k[0] == 0):
    print("<h1>{} Service has been Started successfully</h1>".format(name))
else:
    print("<h1>Unable to start the {} Service.</h1>".format(name))
Example #4
0
#!/usr/local/bin/python3
#  ^^^ this is bad practice, DON'T do as I did!
import cgi
import cgitb  # debugging
from assets import *

print("Content-Type: text/html;charset=utf-8")
print()

cgitb.enable()  # enable debugging
loggedIn = False

# header
showHeader()

# content
startTag("div", id="container")  # start container
dispHTML("h3", contents="Login")
loginForm = cgi.FieldStorage()
startTag("form", id="login-form", method="POST",
         action="main.py")  # login form
dispHTML("p", contents="Password:"******"input", type="password", name="password")
dispHTML("button", contents="submit")
endTag("form")  #  end login form
endTag("div")  # end container

# footer
showFooter()
Example #5
0
 def __init__(self):
     self.form = cgi.FieldStorage()
     self.session = cksession.CookieSession()
     self.check_mode()
Example #6
0
import os, sys, cgi
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'bin')))
import api_local

config = api_local.get_config()
export_dir = config['local']['export_dir']
report_dir = config['local']['report_dir']


if __name__ == '__main__':

    search = cgi.FieldStorage().getvalue('search')
    search_strings = search.split(',')

    users = api_local.read_csv(export_dir + 'users.csv', 'login_id')
    user_index = api_local.build_index(users,key='canvas_user_id')

    lastaccess = api_local.read_csv(report_dir + 'last_user_access_csv.csv', 'user id')
    lastaccess_index = api_local.build_index(lastaccess,key='user id')

    output = []
    canvas_ids = []


    # Build array of canvas_user_ids with corresponding login_ids matching a search string
    for search_string in search_strings:
        for canvas_user_id in user_index:
            login_id = user_index[canvas_user_id]['login_id']
            if search_string.lower() in login_id:
                canvas_ids.append(canvas_user_id)
    def Dispatch(self,
                 request,
                 outfile,
                 base_env_dict=None):
      """Handle post dispatch.

      This dispatcher will handle all uploaded files in the POST request, store
      the results in the blob-storage, close the upload session and transform
      the original request in to one where the uploaded files have external
      bodies.

      Returns:
        New AppServerRequest indicating request forward to upload success
        handler.
      """

      if base_env_dict['REQUEST_METHOD'] != 'POST':
        outfile.write('Status: 400\n\n')
        return


      upload_key = re.match(UPLOAD_URL_PATTERN, request.relative_url).group(1)
      try:
        upload_session = datastore.Get(upload_key)
      except datastore_errors.EntityNotFoundError:
        upload_session = None

      if upload_session:
        success_path = upload_session['success_path']

        upload_form = cgi.FieldStorage(fp=request.infile,
                                       headers=request.headers,
                                       environ=base_env_dict)

        try:


          mime_message_string = self.__cgi_handler.GenerateMIMEMessageString(
              upload_form)
          datastore.Delete(upload_session)
          self.current_session = upload_session


          header_end = mime_message_string.find('\n\n') + 1
          content_start = header_end + 1
          header_text = mime_message_string[:header_end].replace('\n', '\r\n')
          content_text = mime_message_string[content_start:].replace('\n',
                                                                     '\r\n')


          complete_headers = ('%s'
                              'Content-Length: %d\r\n'
                              '\r\n') % (header_text, len(content_text))

          return dev_appserver.AppServerRequest(
              success_path,
              None,
              mimetools.Message(cStringIO.StringIO(complete_headers)),
              cStringIO.StringIO(content_text),
              force_admin=True)
        except dev_appserver_upload.InvalidMIMETypeFormatError:
          outfile.write('Status: 400\n\n')
      else:
        logging.error('Could not find session for %s', upload_key)
        outfile.write('Status: 404\n\n')
Example #8
0
def app(environ, respond):
    _meta = pathlib.Path(os.environ.get('MINISS_META') or default_meta)
    _forbidden = os.environ.get('MINISS_FORBIDDEN', '').split()
    username = os.environ.get('MINISS_USERNAME', '')
    password = os.environ.get('MINISS_PASSWORD', '')
    if not _meta.is_absolute():
        meta = workspace / _meta
    meta.mkdir(parents=True, exist_ok=True)
    forbidden = set([meta])
    for path in _forbidden:
        p = pathlib.Path(path)
        if not p.is_absolute():
            p = workspace / p
        forbidden.add(p)
    without_leading_slash = environ['PATH_INFO'][1:]
    path = workspace / without_leading_slash
    if path in forbidden:
        _respond(respond, 403)
        return []
    meta /= without_leading_slash
    method = environ['REQUEST_METHOD']
    if method == 'DELETE':
        if not path.is_file():
            _respond(respond, 404)
            return []
        if username or password:
            try:
                _assert_owner(environ, username, password)
            except Exception:
                _respond(respond, 401, [('WWW-Authenticate', 'Basic')])
                return []
        meta.unlink()
        path.unlink()
        _respond(respond, 200, [('Content-Type', 'text/plain')])
        return []
    elif method in ('GET', 'HEAD'):
        if not path.exists():
            _respond(respond, 404)
            return []
        if path.is_dir():
            if username or password:
                try:
                    _assert_owner(environ, username, password)
                except Exception:
                    _respond(respond, 401, [('WWW-Authenticate', 'Basic')])
                    return []
            index = path / 'index.html'
            if index.is_file():
                _respond(respond, 200, [('Content-Type', 'text/html')])
                return [index.read_bytes()] if method == 'GET' else []
            _respond(respond, 200)
            objs = (f'{x.relative_to(workspace)}\n'.encode()
                    for x in path.glob('**/*') if str(_meta) not in str(x))
            return objs if method == 'GET' else []
        metadata = json.loads(meta.read_text()) if meta.is_file() else {}
        u = metadata.get('username', '')
        p = metadata.get('password', '')
        if u or p:
            auth = environ.get('HTTP_AUTHORIZATION')
            if auth and 'Basic' in auth:
                b64a = auth.replace('Basic', '').strip().rstrip('=')
                b64b = base64.b64encode(f'{u}:{p}'.encode())
                if b64a != b64b.decode().rstrip('='):
                    _respond(respond, 401, [('WWW-Authenticate', 'Basic')])
                    return []
            else:
                _respond(respond, 401, [('WWW-Authenticate', 'Basic')])
                return []
        status = metadata.get('status', 200)
        headers = [(k, v) for k, v in metadata.get('headers', [])]
        _respond(respond, status, headers)
        return [path.read_bytes()] if method == 'GET' else []
    elif method == 'OPTIONS':
        allow_methods = 'DELETE GET OPTIONS POST PUT'.split()
        _respond(respond, 200,
                 [('Allow', ', '.join(allow_methods)),
                  ('Access-Control-Allow-Methods', ', '.join(allow_methods)),
                  ('Access-Control-Allow-Headers', 'Authorization')])
        return []
    elif method in ['POST', 'PUT']:
        if method == 'POST':
            for _ in range(8):
                new_filename = _random_filename()
                meta /= new_filename
                path /= new_filename
                if not path.exists():
                    break
            else:
                raise Exception('file creation failed')
        if username or password:
            try:
                _assert_owner(environ, username, password)
            except Exception:
                _respond(respond, 401, [('WWW-Authenticate', 'Basic')])
                return []
        u = p = link = data = None
        if (environ['CONTENT_TYPE'] == 'application/x-www-form-urlencoded'
                or 'multipart/form-data' in environ['CONTENT_TYPE']):
            form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
            form = {k: form[k].value for k in form}
            u = form.get('username', form.get('user', form.get('userid')))
            p = form.get('password', form.get('pass', form.get('passwd')))
            link = form.get('link', form.get('ref', form.get('to')))
            data = form.get('data', '').encode() or form.get('file', b'')
        else:
            content_length = int(environ.get('CONTENT_LENGTH', 0))
            data = environ['wsgi.input'].read(content_length)
        metadata = {}
        if link:
            metadata['status'] = 302
            metadata['headers'] = [('Location', link)]
        if u:
            metadata['username'] = u
        if p:
            metadata['password'] = p
        meta.parent.mkdir(parents=True, exist_ok=True)
        meta.write_text(json.dumps(metadata) + '\n')
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        _respond(respond, 200, [('Content-Type', 'text/plain')])
        return [str(path.relative_to(workspace)).encode()]
    else:
        _respond(respond, 405)
        return []
Example #9
0
#!/usr/bin/python2

from inventoryObjects import *
import cgi

store = cgi.FieldStorage()

if "tag" in store:
    htmlTypes = ""
    for Type in types:
        htmlTypes += "<option name=%s>%s</option>\n" % (Type, Type)

    html = """
	<html>
	<body>
	<form name="printOptions" action="input_cgi.py" method="get">
	Type of asset: <select name="type">
	%s
	</select>
	<input type="hidden" name="tag" value="%s">
	<input type="submit" value="Submit">
	</form>
	</body>
	</html>
	""" % (htmlTypes, store.getvalue("tag"))

else:
    htmlTypes = ""
    for Type in types:
        htmlTypes += "<option name=%s>%s</option>\n" % (Type, Type)
def main():
	resHTML = '<h2>That resource does not exist</h2>'
	resHistory = ''
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	galaxy = ''
	spawnName = ''
	spawnID = 0
	uiTheme = ''
	galaxyState = 0
	userReputation = 0
	admin = False
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session

	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if len(path) > 1:
		galaxy = dbShared.dbInsertSafe(path[0])
		spawnName = dbShared.dbInsertSafe(path[1])
		if galaxy != '':
			conn = dbShared.ghConn()
			spawn = getResource(conn, logged_state, currentUser, None, galaxy, spawnName)
			if spawn != None:
				spawnID = spawn.spawnID
				galaxyState = dbShared.galaxyState(spawn.spawnGalaxy)
				# Only show update tools if user logged in and has positive reputation
				stats = dbShared.getUserStats(currentUser, galaxy).split(",")
				userReputation = int(stats[2])
				admin = dbShared.getUserAdmin(conn, currentUser, galaxy)

				if logged_state > 0 and galaxyState == 1:
					controlsUser = currentUser
				else:
					controlsUser = ''

				resHTML = spawn.getHTML(0, "", controlsUser, userReputation, admin)

				resHistory = getResourceHistory(conn, spawn.spawnID)
			conn.close()
		else:
			resHTML = '<h2>No Galaxy/Resource name given</h2>'
	else:
		resHTML = '<h2>No Galaxy/Resource name given</h2>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')

	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(os.environ['HTTP_USER_AGENT'])
	template = env.get_template('resource.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), spawnName=spawnName, resHTML=resHTML, resHistory=resHistory, showAdmin=(userReputation >= ghShared.MIN_REP_VALS['EDIT_RESOURCE_GALAXY_NAME'] or admin), spawnID=spawnID, spawnGalaxy=galaxy, enableCAPTCHA=ghShared.RECAPTCHA_ENABLED, siteidCAPTCHA=ghShared.RECAPTCHA_SITEID)
Example #11
0
def main():
    """ Go Main Go """
    form = cgi.FieldStorage()
    if 'lon' in form and 'lat' in form:
        process(form.getfirst('model'), float(form.getfirst('lon')),
                float(form.getfirst('lat')))
Example #12
0
#!/usr/bin/env python3

# This file must be in the /cgi-bin/ directory of the server.
import cgitb, cgi, sports, sportslib

# Enable CGI errors and extract arguments
cgitb.enable()
arguments = cgi.FieldStorage()

# Filnames for header and footer
header_filename = "_header.html"
footer_filename = "_footer.html"
admin_menu_filename = "admin/_admin_menu.html"

# Determine the action and body file to open from the index directory
action = sportslib.sanitize_file_name(arguments.getvalue("action", "home"))
action_file = action + ".html"
# Admin action templates are withoud "admin_" prefix in admin directory.
action_file = action_file.replace("admin_", "admin/")

# Read cookies
cookies = sportslib.get_cookies()

# Start main web applicatiom action to get dynamic contents for body
app = sports.Application(action, arguments, cookies)
application_result = app.start()

# Test if there cookies to set (must set it before content type header).
if ("cookies" in application_result.keys()):
    sportslib.set_cookies(application_result['cookies'])
Example #13
0
                                          patientOrder["relative_time_start"])
        patientOrder["start_time.format"] = startTime.strftime(TIME_FORMAT)
        patientOrder["end_time.format"] = ""
        if patientOrder["relative_time_end"] is not None:
            endTime = BASE_TIME + timedelta(0,
                                            patientOrder["relative_time_end"])
            patientOrder["end_time.format"] = "<i>(%s)</i>" % endTime.strftime(
                TIME_FORMAT)

        if lastPatientOrder is None or patientOrder[
                "category_description"] != lastPatientOrder[
                    "category_description"]:
            patientOrder["category_description.format"] = patientOrder[
                "category_description"]
            # Only show category for first item for more of a less redundant tree layout
        else:
            patientOrder["category_description.format"] = ""
            # Blank for subsequent lines


# CGI Boilerplate to initiate script
if __name__ == "__main__":
    webController = ActiveOrders()
    webController.handleRequest(cgi.FieldStorage())

# WSGI Boilerplate to initiate script
if __name__.startswith("_mod_wsgi_"):
    webController = ActiveOrders()
    webController.setFilePath(__file__)
    application = webController.wsgiHandler
Example #14
0
#!/usr/bin/python2.7
#HASHBANG CHANGED FOR LINUX COMPATIBILITY

import cgi
import cgitb
import mysql.connector
import Cookie
import hashlib
import datetime
import os
import cookie_handler
import json

cgitb.enable()

sentData = cgi.FieldStorage()
messageID = sentData['messageID'].value
username = cookie_handler.readLoginCookieHeader()

conn = mysql.connector.connect(user='******', password='******', database='Ocean')
cursor = conn.cursor()
# query = "SELECT GROUP_CONCAT(MessageID separator ', ') FROM Favorites where Uname  = '"+username+"';"
query = "INSERT INTO Favorites(Uname, MessageID) VALUES(%s, %s);"
toAdd = (username, messageID)
cursor.execute(query, toAdd)
conn.commit()
conn.close()
"""INSERT INTO Messages
        (Data, Title, Posttime, UnameSent)
        VALUES (%s, %s, %s, %s)"""
Example #15
0
        print

        # Generate web page

        pageTemplate = ("""
            <html>
                <head>
                    <script type="text/javascript" src="../../jQuery/js/jquery-1.4.2.js"></script>                    
                </head>
                
                <body>
                    <div>
                        <span><a href="/"><img alt="site_logo" src="/images/Admiral-logo-284x100.png" border="0"/></a></span>
                    </div>
                    <h2>%(status)s</h2>
                </body>
            </html>
            """)
        print(pageTemplate % {'status': status})

    return


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    form = cgi.FieldStorage()  # Parse the query
    os.chdir("/home/")  # Base directory for admiral server data
    logoutResponseForm(form, sys.stdout)

# End.
def startFormatting(title, identifier, url, source):
    document = """Content-Type:text/html;charset=UTF-8

<!doctype html>
<html lang=en>
 <head>
  <title>%s Tracker</title>
  <style>
   html { background:#fff; color:#000; font:1em/1 Arial, sans-serif }
   form { margin:1em 0; font-size:.7em }
   fieldset { margin:0; padding:0; border:0 }
   legend { padding:0; font-weight:bold }
   input[type=number] { width:4.5em }
   table { border-collapse:collapse }
   table td { padding:.1em .5em }
   table td:last-child { white-space:nowrap }
   img { font-size:xx-small }

   .draft-content { background-color:#eee }
   .stable-draft { background-color:#fcc }
   .implemented { background-color:#f99 }
   .stable { background-color:#f66 }
   body .editorial { color:gray }

   :link { background:transparent; color:#00f }
   :visited { background:transparent; color:#066 }
   img { border:0; vertical-align:middle }

   td :link { color:inherit }
   td a { text-decoration:none; display:block }
   td a:hover { text-decoration:underline }

   .editorial tr.editorial { display:none }

   pre { display:table; white-space:normal }
   samp samp { margin:0; display:block; white-space:pre }
   .deletion { background:#fdd; color:#900 }
   .addition { background:#dfd; color:#000 }
   .line-info { background:#eee; color:#000 }
  </style>
  <script>
   function setCookie(name,value) { localStorage["tracker%s-" + name] = value }
   function readCookie(name) { return localStorage["tracker%s-" + name] }
   function setFieldValue(idName, n) { document.getElementById(idName).value = n }
   function getFieldValue(idName) { return document.getElementById(idName).value }
   function setFrom(n) {
     setCookie("from", n)
     setFieldValue("from", n)
     setFieldValue("to", "")
   }

   function showEdits() { return document.getElementById("editorial").checked }
   function updateEditorial() {
     var editorial = showEdits() ? "" : "editorial"
     setCookie("editorial", editorial)
     document.body.className = editorial
   }
  </script>
 </head>
 <body>
  <h1>%s</h1>
  <form>
   <fieldset>
    <legend>Diff</legend>
    <label>From: <input id=from type=number min=1 value="%s" name=from required></label>
    <label>To: <input id=to type=number min=0 value="%s" name=to></label> (omit for latest revision)
    <input type=submit value="Generate diff">
   </fieldset>
  </form>
  <form>
   <fieldset>
    <legend>Filter</legend>
    <label class="editorial">Show editorial changes <input type="checkbox" id="editorial" checked="" onchange="updateEditorial()"></label>
   </fieldset>
  </form>
  <script>
   if(getFieldValue("from") == "" && readCookie("from") != null)
     setFrom(readCookie("from"))
   if(readCookie("editorial") == "editorial") {
     document.getElementById("editorial").checked = false
     updateEditorial()
   }
  </script>
  %s
 </body>
</html>"""
    showDiff = False
    revFrom = 290  # basically ignored, but sometimes a useful fiction for debugging
    revTo = 0
    os.environ["TZ"] = ""  # Set time zone to UTC. Kinda hacky, but works :-)
    form = cgi.FieldStorage()

    if "from" in form:
        try:
            revFrom = toInt(form["from"].value)
            showDiff = True
        except:
            pass

    if showDiff and "to" in form:
        try:
            revTo = toInt(form["to"].value)
            if 0 < revTo < revFrom:
                revFrom, revTo = revTo, revFrom
        except:
            pass

    # Put it on the screen
    if not showDiff:
        #
        # HOME
        #
        if "limit" in form and form["limit"].value == "-1":
            limit = ""
        else:
            limit = " --limit 100"
            try:
                limit = " --limit %s" % toInt(form["limit"].value)
            except:
                pass
        svnLog = os.popen("svn log %s%s" % (source, limit))
        parsedLog = parseRawLog(svnLog)
        formattedLog = formatLog(parsedLog)
        print document % (title, identifier, identifier, title + " Tracker",
                          "", "", formattedLog)
    else:
        #
        # DIFF
        #
        diff = formatDiff(getDiff(source, revFrom, revTo, identifier))
        markuptitle = "<a href=" + url + ">" + title + " Tracker" + "</a>"
        try:
            # This fails if there is no diff -- hack
            revTo = getNumber(diff, 2)
            svnLog = os.popen(getLogCommand(source, revFrom, revTo))
            parsedLog = parseRawLog(svnLog)
            formattedLog = formatLog(parsedLog)
            result = """%s
  <pre id="diff"><samp>%s</samp></pre>
  <p><a href="?from=%s&amp;to=%s" rel=prev>Previous</a> | <a href="?from=%s&amp;to=%s" rel=next>Next</a>
  <p><input type="button" value="Prefill From field for next time!" onclick="setFrom(%s)">""" % (
                formattedLog, diff, revFrom - 1, revFrom, revTo, revTo + 1,
                revTo)

            # Short URL
            shorturlmarkup = ""
            if title == "HTML5":
                shorturl = "http://html5.org/r/"
                if revTo - revFrom == 1:
                    shorturl += str(revTo)
                else:
                    shorturl += str(revFrom) + "-" + str(revTo)
                shorturlmarkup = """<p>Short URL: <code><a href="%s">%s</a></code>\n  """ % (
                    shorturl, shorturl)
            shorturlmarkup += result
            print document % (title, identifier, identifier, markuptitle,
                              revFrom, revTo, shorturlmarkup)
        except:
            print document % (title, identifier, identifier, markuptitle,
                              revFrom, "", "No result.")
import cgitb
cgitb.enable()

import cgi
import athletemodel
import yate

athletes = athletemodel.get_from_store()
form_data = cgi.FieldStorage()
athlete_name = form_data['which_athlete'].value

print(yate.start_response())
print(yate.include_header("Athlete's timing data:"))
#print(yate.para(athlete_name+"'s time data:"))
print(
    yate.header("Athlete:" + athlete_name + ",DOB = " +
                athlete[athlete_name].dob + '.'))
print(yate.para("The top times for this athletes are:"))
print(yate.u_list(athletes[athlete_name].top3))

print(
    yate.include_footer({
        "Home": "index.html",
        "Choose another athlete": "generate_list.py"
    }))
Example #18
0

def tail():
    print '''</body>
			</html>'''


if __name__ == "__main__":
    try:
        head()
        db = MySQLdb.connect(host='localhost',
                             user='******',
                             passwd='',
                             db='courses')
        cur = db.cursor()
        formData = cgi.FieldStorage()
        old_dept_code = formData.getvalue('old_dept_code')
        dept_code = formData.getvalue('dept_code')
        dept_name = formData.getvalue('dept_name')
        try:
            cur.execute('delete from department where Dept_Code=%s;',
                        (old_dept_code))
            cur.execute('insert into department values(%s,%s);',
                        (dept_code, dept_name))
            db.commit()
            print ''' <p> Department details edited successfully. </p> '''
        except:
            print ''' <p> Department code is already registered </p> '''
        print '''   <br> <br> <br> <br> <br> <br>
					<h3>
					<a href='dept.py'> Go back </a> <br> <br>
Example #19
0
#!/usr/bin/python3
import subprocess
import cgi

print("context-type:text/html")
print()
rec = cgi.FieldStorage()
order = rec.getvalue("ord")
name = rec.getvalue("name")
value = rec.getvalue("val")
order = order.lower()
cmd = ""
if not ("don't" in order or "do not" in order):
    if "date" in order:
        print("DATE IS:")
        cmd = "date"
        print(subprocess.getoutput(cmd))
    elif "cal" in order:
        print("CALENDAR IS:")
        cmd = "cal"
        print(subprocess.getoutput(cmd))
    elif "docker" in order:
        if "run" in order:
            if value != None:
                print(
                    "Copy the following container name for future reference:")
                if name == None:
                    cmd = "sudo docker run -dit {}".format(value)
                else:
                    cmd = "sudo docker run -dit --name {0} {1}".format(
                        name, value)
Example #20
0
#!/usr/bin/env python3
print("Content-Type:text/html")
print("")

import cgi

import pandas as pd
import  seaborn  as  sb
from  sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

import cgitb   #cgitb to trace back error
cgitb.enable()
#this is http protocol model'
web=cgi.FieldStorage()
a=web.getvalue("Preg")
b=web.getvalue("glu")
c=web.getvalue("bp")
d=web.getvalue("ST")
e=web.getvalue("Insu")
f=web.getvalue("bmi")
g=web.getvalue("DPF")
h=web.getvalue("age")
#print([a,b,c,d,e,f,g,h])
print("-----------------------------------------------")

#print("Hello")

#  reading csv file and converting into data frames
df=pd.read_csv('/usr/lib/cgi-bin/diabetes.csv')
Example #21
0
#!/usr/bin/env python
'friendlist'

import cgi
import cgitb
import sqlite3
from collections import OrderedDict
import functions

cgitb.enable()
FORM = cgi.FieldStorage()

print 'Content-Type: text/html'
print
if FORM.has_key('id') and FORM.has_key('type'):
    SESSIONID = (FORM['id'].value, )
    TYPE = FORM['type'].value
    if FORM.has_key('friendEmail'):
        FRIENDEMAIL = (FORM['friendEmail'].value, )
    CONN = sqlite3.connect('accounts.db')
    C = CONN.cursor()

    C.execute(
        'CREATE TABLE IF NOT EXISTS friends(id INTEGER PRIMARY KEY AUTOINCREMENT, email1 varchar(100), email2 varchar(100))'
    )

    C.execute('SELECT username FROM sessionId WHERE id=?', SESSIONID)
    USERNAME = C.fetchone()
    if USERNAME is not None:
        C.execute('SELECT email FROM users WHERE username=?', USERNAME)
        EMAIL = C.fetchone()
Example #22
0
#!C:\Python27\python.exe
print "Content-Type:text/html\n\n"
import cgi,MySQLdb
cityname=cgi.FieldStorage().getvalue('cityname')
con=MySQLdb.connect('127.0.0.1','root','','speedex',3306)
cur=con.cursor()
q="insert into city(cityname) values('"+cityname+"')"

n=cur.execute(q)
if n==1:
 print "<script>alert('ADDED');window.location.href='addcity.py';</script>"
else:
 print "<script>alert('NOT ADDED');window.location.href='addcity.py';</script>"
Example #23
0
def Main():
    origReqUri = lib_util.RequestUri()

    # There is only one cgiEnv and "cgiEnv.OutCgiRdf()" does not generate anything.
    lib_common.CgiEnvMergeMode()

    arguments = cgi.FieldStorage()

    # The display mode is read now, otherwise the CGI arguments are later destroyed, in this script.
    theMode = lib_util.GuessDisplayMode()
    sys.stderr.write("merge_scripts.py theMode=%s\n" % (theMode))

    # Concatenation of error messages of each script.
    cumulatedError = ""

    for urlfil in arguments.getlist("url"):
        # The parameters are coded in base64, although we leave the possibility not to encode them,
        # for compatibility with test scripts.

        complete_url = lib_util.Base64Decode(urlfil)

        sys.stderr.write("complete_url=%s\n" % complete_url)

        # Only the URL without the arguments.
        urlSplit = complete_url.split("?")
        urlNoArgs = urlSplit[0]
        if len(urlSplit) > 1:
            cgiQueryString = urlSplit[1]
        else:
            cgiQueryString = ""

        # The URL might be absolute or relative. Example:
        # "survol/sources_types/enumerate_CIM_Process.py?xid=."
        idxHtbin = urlNoArgs.find("sources_types/")
        if idxHtbin == -1:
            # This may be the main presentation page of a Survol, WMI or WBEM object. Example:
            # "http://127.0.0.1:80/Survol/survol/entity.py?xid=CIM_Process.Handle=640"
            survolPrefix = "survol/"
            idxSurvol = urlNoArgs.find(survolPrefix)
            if idxSurvol == -1:
                # TODO: This happens if the URL is a main presentation page of an object,
                # instead of a script: Something like "survol/entity.py/entity.py?xid=..."
                # This should be fixed but is not an issue.
                sys.stderr.write("merge: SHOULD NOT HAPPEN url=%s\n" %
                                 complete_url)
                urlPathShort = "INVALID_MERGED_URL"
            else:
                # Just starts at the beginning of the script name: "entity.py", "entity_wmi.py", "entity_wbem.py".
                urlPathShort = urlNoArgs[idxSurvol + len(survolPrefix):]
        else:
            urlPathShort = urlNoArgs[idxHtbin:]

        # urlPathShort is the actual script to load.
        urlDirNam = os.path.dirname(urlPathShort)
        moduNam = urlDirNam.replace("/", ".")

        urlFilNam = os.path.basename(urlPathShort)

        sys.stderr.write(
            "urlPathShort=%s urlDirNam=%s moduNam=%s urlFilNam=%s\n" %
            (urlPathShort, urlDirNam, moduNam, urlFilNam))
        try:
            # argDir="sources_types.win32" urlFileNam="enumerate_top_level_windows.py"
            importedMod = lib_util.GetScriptModule(moduNam, urlFilNam)
        except Exception:
            errorMsg = sys.exc_info()[1]
            sys.stderr.write(
                "Caught %s when loading moduNam=%s urlFilNam=%s\n" %
                (errorMsg, moduNam, urlFilNam))
            continue

        if not importedMod:
            cumulatedError = "merge_scripts.py Cannot import complete_url=%s" % (
                complete_url)
            continue

        try:
            # The entire URL must be "injected" so the parameters will be properly parsed,
            # when Main() call lib_util.RequestUri().
            urlUnquote = lib_util.urllib_unquote(complete_url)
            os.environ["REQUEST_URI"] = urlUnquote

            os.environ['SCRIPT_NAME'] = urlFilNam
            # "xid=EURO%5CLONL00111310@process:16580"
            os.environ['QUERY_STRING'] = cgiQueryString

            lib_common.ErrorMessageEnable(False)
            importedMod.Main()
        except Exception:
            errorMsg = sys.exc_info()[1]
            sys.stderr.write(
                "Caught %s when executing Main in moduNam=%s urlFilNam=%s\n" %
                (errorMsg, moduNam, urlFilNam))
            if cumulatedError != "":
                cumulatedError += " ; "
            cumulatedError += " url=" + urlNoArgs + " / " + urlFilNam + ":" + str(
                errorMsg)

            continue
        lib_common.ErrorMessageEnable(True)

    os.environ["REQUEST_URI"] = origReqUri

    # OutCgiRdf has been called by each script without writing anything,
    # but the specific parameters per script are stored inside.

    # TESTER AVEC CA:
    # http://127.0.0.1:8000/survol/merge_scripts.py?url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9ob3N0LnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBc3No&url=aHRiaW4vc291cmNlc190eXBlcy9DSU1fQ29tcHV0ZXJTeXN0ZW0vaG9zdG5hbWVfbm1hcC5weT94aWQ9Q0lNX0NvbXB1dGVyU3lzdGVtLk5hbWUlM0RVbmtub3duLTMwLWI1LWMyLTAyLTBjLWI1LTI&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9ob3N0LnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBc3ZybG9j&url=aHRiaW4vZW50aXR5LnB5P3hpZD1zbWJzaHIuSWQ9Ly8vL1dETXlDbG91ZE1pcnJvci9yY2hhdGVhdQ&url=aHRiaW4vc291cmNlc190eXBlcy9DSU1fQ29tcHV0ZXJTeXN0ZW0vY29ubmVjdGVkX3NvY2tldHMucHk_eGlkPUNJTV9Db21wdXRlclN5c3RlbS5OYW1lJTNEVW5rbm93bi0zMC1iNS1jMi0wMi0wYy1iNS0y&url=aHRiaW4vc291cmNlc190eXBlcy9DSU1fQ29tcHV0ZXJTeXN0ZW0vaG9zdG5hbWVfbm1hcC5weT94aWQ9Q0lNX0NvbXB1dGVyU3lzdGVtLk5hbWUlM0RVbmtub3duLTMwLWI1LWMyLTAyLTBjLWI1LTI&url=aHRiaW4vc291cmNlc190eXBlcy9ncm91cC9saW51eF91c2VyX2dyb3VwLnB5P3hpZD1ncm91cC5OYW1lJTNEYXBhY2hl&url=aHRiaW4vc291cmNlc190eXBlcy91c2VyL3VzZXJfbGludXhfaWQucHk_eGlkPXVzZXIuRG9tYWluJTNETG9jYWxIb3N0JTJDTmFtZSUzRGFwYWNoZQ&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9jb25uZWN0ZWRfcHJvY2Vzc2VzLnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBdGVsbmV0&url=aHRiaW4vc291cmNlc190eXBlcy91c2VyL3VzZXJfcHJvY2Vzc2VzLnB5P3hpZD11c2VyLkRvbWFpbiUzRExvY2FsSG9zdCUyQ05hbWUlM0RhcGFjaGU&url=aHRiaW4vc291cmNlc190eXBlcy9DSU1fUHJvY2Vzcy9wcm9jZXNzX2N3ZC5weT94aWQ9Q0lNX1Byb2Nlc3MuSGFuZGxlJTNEMTQ3MDU&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9jb25uZWN0ZWRfcHJvY2Vzc2VzLnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBc3No&url=aHRiaW4vc291cmNlc190eXBlcy9DSU1fUHJvY2Vzcy9wcm9jZXNzX2N3ZC5weT94aWQ9Q0lNX1Byb2Nlc3MuSGFuZGxlJTNEMTQ3MDU&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9jb25uZWN0ZWRfcHJvY2Vzc2VzLnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBdGVsbmV0&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9jb25uZWN0ZWRfcHJvY2Vzc2VzLnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBdGVsbmV0&url=aHRiaW4vc291cmNlc190eXBlcy9hZGRyL3NvY2tldF9jb25uZWN0ZWRfcHJvY2Vzc2VzLnB5P3hpZD1hZGRyLklkJTNEMTkyLjE2OC4xLjg4JTNBc3No&url=aHR0cDovLzE5Mi4xNjguMS44ODo4MC9TdXJ2b2wvaHRiaW4vZW50aXR5LnB5P3hpZD1DSU1fUHJvY2Vzcy5IYW5kbGU9MjA1MTI
    lib_common.MergeOutCgiRdf(theMode, cumulatedError)
Example #24
0
#!/usr/bin/python3.7
"""
Реализует веб-интерфейс для просмотра и изменения экземпляров классов
в хранилище; хранилище находится на сервере (или на том же компьютере,
если используется имя localhost)
"""

# cgi.test() выведет поля ввода
import cgi, html, shelve, sys, os

# файлы хранилища находятся в текущем каталоге
shelve_name = 'class-shelve'
field_names = ('name', 'age', 'job', 'pay')

form = cgi.FieldStorage()             # Парсинг данных формы
print('Content-type: text/html\n')    # заголовок + пустая строка для ответа
sys.path.insert(0, os.getcwd())

# Главный шаблон разметки html
reply_html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>People Input Form</title>
</head>
<body>
<form method="post" action="peoplecgi.py">
    <table>
        <tr><th>key<td><input type="text" name="key" value="%(key)s">
        $ROWS$
Example #25
0
def main():
    rtlist = []

    print "Content-type: text/html\n\n"
    print "<h1>Results:</h1>"
    print "(Use your browser's back button to return to the previous page.)"
    print "</br></br>"

    # If an exception is thrown, cgitb will allow errors to be printed to
    # the web page, in addition to the python version and a timestamp.
    # This is useful for debugging purposes. If you don't want this to happen,
    # either comment out the next line, or see the python documentation
    # on how to make it write to a log file.
    cgitb.enable()
    form = cgi.FieldStorage()

    if (not "summary-input" in form):
        print "Error: One or more prefixes required."
        return 1

    args = form["summary-input"].value.split()

    if (args.__len__() > ARGS_LIMIT):
        print "The web version of this demo is artificially limited to", \
              ARGS_LIMIT, "prefixes so the web server doesn't get too bogged " \
              "down. Consider downloading a command line version from " \
              "acrs.googlecode.com (it's open source and no cost) " \
              "or bribing the server operator to increase ARGS_LIMIT in ", \
              "acrs-web-demo.py."
        return 1

    for rtstr in args:
        ret = rtstr.split("/")
        if (ret.__len__() != 2):
            print "Error, use CIDR notation (e.g. 1.1.1.0/24):", rtstr
            return 1

        try:
            addr, mask = ret[0], int(ret[1])
        except:
            print "Error, use CIDR notation (e.g. 1.1.1.0/24):", rtstr
            return 1

        rt = ip4route.IP4Route(addr, mask)
        if (rt.isValid() == False):
            print "Error, invalid route:", rtstr
            return 1

        rtlist.append(rt)

    if (rtlist == []):
        print "One or more valid routes required."
        return 1

    rtlist, summarized = acrs.summarize(rtlist)

    for rt in rtlist:
        assert (rt.isValid() == True)
        print rt, "</br>"

    return 0
Example #26
0
#!/usr/bin/python
#james huang
#HW58
#introcs2 pd03
#05-26-2017
print 'content-type: text/html'
print ""
print '<!DOCTYPE html><html><body>'

import os
import cgi

print '<form>a:<br><input type="number" name="a"><br>b:<br><input type="number" name="b"><br>c:<br><input type="number" name="c"><br> <input type="submit" value="Submit"></form>'
cgi.FieldStorage()
foo = cgi.FieldStorage()


#diag output
def life(foo):
    a = []
    for k in foo.keys():
        a += [foo[k].value]
    return a


def quor(a):
    if a == []:
        return 'no query string:input 3 values into form above'
    else:

        perimeter = 0
Example #27
0
import cgi, pymysql

print("Content-Type: text/html")
print()

fs = cgi.FieldStorage()

input = {}

for key in fs:
    input[key] = fs[key].value

# print(input["id"])

sql = "delete from user where id={id}".format(id=input["id"])
# print(sql)

db = pymysql.connect("192.168.0.171", "sjl", "123456", "myserver")
cursor = db.cursor()

# print(sql)
try:
    cursor.execute(sql)
    db.commit()
    print("<script>alert('删除成功');location.href='list.py'</script>")
except:
    db.rollback()
    print("<script>alert('删除失败!');</script>")

cursor.close()
db.close()
Example #28
0
    if su_name in org_list.su_names_isect: #hillight table row and show "add 
      #file" button if subunit is shared by all enzymes:
      html += '<tr class = "active_green">' + common_str + al_field + \
              '</td><td>' + bm_field 
    else:
      html += '<tr>' + common_str + '</td><td></td>'
    html += '</td></tr>\n'
  html += '</table>\n</div>\n</div>\n'
  return html
  
def get_filter_str(post_data, id_set):
  if id_set:
    return post_data.getvalue('filter_vals_ta', '').replace('\n', ' | ')
  return 'no enzymes with applied filters were checked, showing all the enzymes'
  
post_data = cgi.FieldStorage()
page_name, label, content, html = 'getSuSeqLoadAl.py', [], '', ''
su_name_to_fasta, org_list = dict(), sc.OrgList()
if not post_data:
  html = sh.mk_page_header(page_name, no_post_data = True)
else:
  id_set = sh.get_id_set_from_cb(post_data, 'enzymes')
  filter_str = get_filter_str(post_data, id_set)
  # if no id_set is provided - output has all the enzymes
  wc = sf.get_where_id_case(id_set, 'enzymes', True)
  db_name = sh.get_db_name(post_data)
  if db_name:
    db_link, db_cursor = df.get_link_and_cursor(db_name)
    if db_cursor:
      db_rows = df.get_db_rows(db_cursor, ' WHERE ' + wc if wc else '')
      org_list.fill_from_db_rows(db_rows)
Example #29
0
#!/usr/bin/python
import json
import os
import sys
from peewee import *
from datetime import datetime, timedelta, time, date
import pymeteosalute

import cgi
import cgitb

cgitb.enable()
form = cgi.FieldStorage()

############################################################
# Set missing data

tmpf = float('-99.9')
rhf = float('-99.9')
pvapf = float('-99.9')
tdewf = float('-99.9')
tmrtf = tmpf
vvf = float('0.5')
vdirf = float('-99.9')
atif = float('-99.9')
ati = float('-99.9')
utci = float('-99.9')
utci_c = float('-99.9')
raduv = float('-99.9')
precipf = float('-99.9')
radf = float('-99.9')
Example #30
0
#! /usr/local/bin/python3

import sys  # for debugging purposes
import cgi
import json
import athletemodel
import yate
from athletelist import AthleteList

form_data = cgi.FieldStorage(
)  # process the stat send with the request and extract the ahtlete's name
athlete_id = form_data['which_athlete'].value
athlete = athletemodel.get_athlete_from_id(athlete_id)
print(yate.start_response(
    'application/json'))  # start a web response, with JSON as the data type
print(
    json.dumps(athlete)
)  # include the indicated athlete's data in the web response, formatted by JSON