예제 #1
0
파일: wsgi.py 프로젝트: martinohmann/ctplot
def handle_action(environ, start_response, config):
    global available_tables
    fields = FieldStorage(fp = environ['wsgi.input'], environ = environ)
    action = fields.getfirst('a')
    datadir = config['datadir']
    sessiondir = config['sessiondir']

    if action in ['plot', 'png', 'svg', 'pdf']:

        settings = {}
        for k in fields.keys():
            if k[0] in 'xyzcmsorntwhfgl':
                settings[k] = fields.getfirst(k).strip().decode('utf8', errors = 'ignore')

        images = make_plot(settings, config)
        for k, v in images.items():
            images[k] = 'plots/' + basename(v)

        if action == 'plot':
            return serve_json(images, start_response)

        elif action in ['png', 'svg', 'pdf']:
            return serve_plot(images[action], start_response, config)



    elif action == 'list':
        if not available_tables or time() - available_tables[0] > 86400:
            available_tables = time(), ctplot.plot.available_tables(datadir)
        return serve_json(available_tables[1], start_response)

    elif action == 'save':
        id = fields.getfirst('id').strip()
        if len(id) < 8: raise RuntimeError('session id must have at least 8 digits')
        data = fields.getfirst('data').strip()
        with open(os.path.join(sessiondir, '{}.session'.format(id)), 'w') as f:
            f.write(data.replace('},{', '},\n{'))
        return serve_json('saved {}'.format(id), start_response)

    elif action == 'load':
        id = fields.getfirst('id').strip()
        if len(id) < 8: raise RuntimeError('session id must have at least 8 digits')
        try:
            with open(os.path.join(sessiondir, '{}.session'.format(id))) as f:
                return serve_plain(f.read(), start_response)
        except:
            return serve_json('no data for {}'.format(id), start_response)

    elif action == 'newid':
        id = randomChars(16)
        while os.path.isfile(os.path.join(sessiondir, '{}.session'.format(id))):
            id = randomChars(16)
        return serve_plain(id, start_response)

    else:
        raise ValueError('unknown action {}'.format(action))
예제 #2
0
def get_comments():
    #Function to take in user comments, add them to a database & display them

    from cgi import FieldStorage, escape
    import pymysql as db
    from os import environ

    comments = ''
    url = environ.get('SCRIPT_NAME')
    try:
        connection = db.connect('cs1.ucc.ie', 'cgg1', 'weeS2dih', '2021_cgg1')
        cursor = connection.cursor(db.cursors.DictCursor)
        form_data = FieldStorage()
        if len(form_data) != 0:
            if form_data.getfirst('username') != None and form_data.getfirst(
                    'new_comment') != None:
                username = escape(form_data.getfirst('username'))
                new_comment = escape(form_data.getfirst('new_comment'))
                username = profanity(username)
                new_comment = profanity(new_comment)
                cursor.execute(
                    """INSERT INTO comments_table (username, url, comment)
                                  VALUES (%s, %s, %s)""",
                    (username, url, new_comment))
                connection.commit()
        cursor.execute(
            """SELECT * FROM comments_table
                          WHERE url = %s
                          ORDER BY comment_id DESC""", (url))
        for row in cursor.fetchall():
            comments += '<article><h1>%s</h1><p>%s</p></article>' % (
                row['username'], row['comment'])
        cursor.close()
        connection.close()
    except db.Error:
        comments = '<p class="error">Sorry! We are experiencing problems at the moment. Please call back later.</p>'

    return """
        <h1>Comments</h1>
        <form action="%s" method="post">
            <fieldset>
                <legend>Post a new comment</legend>
                <label for="username">Name:</label>
                <input type="text" name="username" id="username" maxlength="255"/>
                <label for="new_comment">Comment:</label>
                <textarea name="new_comment" id="new_comment" rows="5" cols="30" maxlength="255"></textarea>
                <input type="submit" value="Post" />
            </fieldset>
        </form>
        %s""" % (url, comments)
예제 #3
0
def main():
	form = FieldStorage(keep_blank_values=True)
	ft=form.getfirst('ft',False)
	cat=form.getfirst('cat',None)
	if cat == None: return
	from MySQLdb import connect
	db = connect(db=WIKIDB, host=HOSTNAME, read_default_file=CNFFILE)
	cursor=db.cursor()
	query="SELECT CatCount,concat('20',CatDate) FROM "+DB+".CatTrack where CatId=(select cat_id from category where cat_title=%s) ORDER BY CatDate;"
	cursor.execute(query,(cat,))
	print 'Content-type: text\n'	
	print '{| class = "wikitable"\n|-\n!Date!!Number of Pages in [[:Category:'+cat.replace('_',' ')+']]'
	for count,date in cursor.fetchall():
		print '|-\n|'+str(date)+'||'+str(count)
	print'|}'
예제 #4
0
파일: CatCsv.py 프로젝트: tim1357/CatTrack
def main():
        form = FieldStorage(keep_blank_values=True)
        ft=form.getfirst('ft',False)
        cat=form.getfirst('cat',None)
        if cat == None: return
        from MySQLdb import connect
        db = connect(db=WIKIDB, host=HOSTNAME, read_default_file=CNFFILE)
        cursor=db.cursor()
        query="SELECT CatCount,CONCAT('20',CatDate) FROM "+DB+".CatTrack where CatID=(select cat_id from category where cat_title=%s) ORDER BY CatDate;"
        cursor.execute(query,(cat,))
        print 'Content-type: application/download\nContent-disposition: attachment; filename="Tim1357-CatTracker-'+cat.replace('_',' ').replace(' ','-')+'.csv"\n'
        
        print '"Date","# of Pages in Category"'
        for count,date in cursor.fetchall():
                print '"'+strftime('%Y-%m-%d',strptime(date,'%Y%m%d'))+'",'+str(count)
예제 #5
0
파일: handlers.py 프로젝트: EricDoug/imsto
def StoredHandler(environ, start_response):
	from cgi import FieldStorage
	import cgitb; cgitb.enable(display=0, logdir="/tmp")
	form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
	print(form.keys())

	start_response('200 Ok', [('Content-type', 'text/javascript')])

	if "oper" not in form:
		#print("Bad Request")
		return [json.dumps([False, 'Bad Request'])]

	method = environ['REQUEST_METHOD'].upper()
	if method == 'GET' or method == 'HEAD':
		return [json.dumps([False, 'bad request'])]
	oper = form['oper']
	print(oper)
	section = form.getfirst('roof', 'imsto')
	# section = form['section'] if form.has_key('section') else 'imsto'

	imsto = load_imsto(section)
	if oper.value == 'delete':
		id = form['id']
		r = imsto.delete(id.value)
		print r
		return [json.dumps(r)]
	if oper.value == 'add':

		if "new_file" not in form:
			return [json.dumps([False, 'please select a file'])]

		new_file = form['new_file']
		if new_file is None:
			return [json.dumps([False, 'invalid upload field'])]
		# print(type(new_file))
		result = []
		if type(new_file) == type([]):
			for f in new_file:
				print('%r %r %r %r %r %r' % (f.name, f.filename, f.type, f.disposition, f.file, f.length))
				r = imsto.store(f.file, ctype=f.type, name=f.filename)
				print 'store: %r, result %r' % (f.name, r)
				if type(r) == type([]):
					result.append(r)
				else:
					result.append(False)
		else:
			f = new_file
			print('single file %r %r' % (f.name, f.filename))
			try:
				result = imsto.store(f.file, ctype=f.type, name=f.filename)
				print 'store: %r, result %r' % (f.name, result)
			except Exception, e:
				result = [False, e.message]
				print "\n".join(get_traceback()) + "\n"
			
		if hasattr(imsto, 'close'):
			imsto.close()
		
		return [json.dumps(result)]
예제 #6
0
    def getfirst(self, name, default=None, fce=uni):
        """Returns first variable value for key or default, if key not exist.

        Arguments:
            fce - function which processed value.
        """
        val = CgiFieldStorage.getfirst(self, name, default)
        if val is None:
            return None

        return fce(val)
예제 #7
0
파일: request.py 프로젝트: JPilarr/PoorWSGI
    def getfirst(self, name, default=None, fce=uni):
        """Returns first variable value for key or default, if key not exist.

        Arguments:
            fce - function which processed value.
        """
        val = CgiFieldStorage.getfirst(self, name, default)
        if val is None:
            return None

        return fce(val)
예제 #8
0
파일: CatImg.py 프로젝트: tim1357/CatTrack
def main():
        form = FieldStorage(keep_blank_values=True)
        ft=form.getfirst('ft',False)
        cat=form.getfirst('cat',None)
        if cat == None: return
        from MySQLdb import connect
        db = connect(db=WIKIDB, host=HOSTNAME, read_default_file=CNFFILE)
        cursor=db.cursor()
        query="SELECT CatCount,concat('20',CatDate) FROM "+DB+".CatTrack where CatID=(select cat_id from category where cat_title=%s) ORDER BY CatDate;"
        cursor.execute(query,(cat,))
        g=[]
        for y,x in cursor.fetchall():
                g.append((x,y))
        gg=graph()
        gg.g=g
        if ft: del gg.parameters['chf']
        gg.title('Number of Pages in Category:'+cat.replace('_',' '))
        t= gg.uobj()
        if not ft:print "Content-Type: image/png\n"
        else: print 'Content-type: application/download\nContent-disposition: attachment; filename="Tim1357-CatTracker-'+cat.replace('_',' ').replace(' ','-')+'.png"\n'
        print t
예제 #9
0
def getInt(key, min_int=None, max_int=None, default=0):
    form_data = FieldStorage()
    value = escape(form_data.getfirst(key, '')).strip()

    if value:
        try:
            value = int(value)
            if (min_int and value <= min_int) or (max_int and value > max_int):
                value = default
        except ValueError:
            value = default
    else:
        value = default
    return value
예제 #10
0
    def getfirst(self, key: str, default: Any = None, fce: Callable = str):
        """Returns first variable value for key or default, if key not exist.

        Arguments:
            key : str
                key name
            default : None
                default value if key not found
            fce : convertor (str)
                Function or class which processed value.
        """
        # pylint: disable=arguments-differ
        val = CgiFieldStorage.getfirst(self, key, default)
        if val is None:
            return None
        return fce(val)
예제 #11
0
파일: handlers.py 프로젝트: wateroot/imsto
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]
예제 #12
0
def contactUs():
    # Function to take in user information from contact us and insert it into a database

    from cgi import FieldStorage, escape
    import pymysql as db
    from os import environ

    result = ''
    url = environ.get('SCRIPT_NAME')
    try:
        connection = db.connect('cs1.ucc.ie', 'cgg1', 'weeS2dih', '2021_cgg1')
        cursor = connection.cursor(db.cursors.DictCursor)
        form_data = FieldStorage()

        if len(form_data) != 0:
            if form_data.getfirst('name') != None and form_data.getfirst(
                    'phone') != None and form_data.getfirst('comment') != None:
                name = escape(form_data.getfirst('name')).strip()
                phone = escape(form_data.getfirst('phone')).strip()
                comment = escape(form_data.getfirst('comment')).strip()
                comment = profanity(comment)
                if not phone.isnumeric() or len(phone) != 10:
                    result += '<p class="error">Please enter a valid phone number.</p>'
                else:
                    cursor.execute(
                        """INSERT INTO contact_us (name, url, phone, comment)
                                    VALUES (%s, %s, %s, %s)""",
                        (name, url, phone, comment))
                    connection.commit()
                    result += "<p>Message successfully sent.</p>"
            else:
                result += '<p class="error">Please fill in all the text boxes.</p>'
        cursor.close()
        connection.close()
    except db.Error:
        result += '<p class="error">Sorry! We are experiencing problems at the moment. Please call back later.</p>'

    return """
        <h1>Contact Us</h1>
        <form action="%s" method="post">
            <fieldset>
                <legend>Send A Message</legend>
                <label for="name">Name: </label>
                <input type="text" name="name" id="name" maxlength="40"/>
                <label for="phone">Phone: </label>
                <input type="text" name="phone" id="phone" maxlength="10"/>
                <label for="comment">Comment:</label>
                <textarea name="comment" id="comment" rows="4" cols="30"></textarea>
                <input type="submit" value="Send"/>
            </fieldset>
        </form>
        %s""" % (url, result)
예제 #13
0
파일: handlers.py 프로젝트: EricDoug/imsto
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]
예제 #14
0
파일: app.py 프로젝트: fluxid/pyhaa_site
def page_exec_shit(environ):
    if environ['REQUEST_METHOD'] == 'POST':
        fields = FieldStorage(
            fp = environ['wsgi.input'],
            environ = environ,
        )
        code = fields.getfirst('code')
        if code:
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.settimeout(8.0)
            sock.connect('/home/fluxid/main/dev/sandboxed/socket')
            code = code.replace('\r\n', '\n')
            sock.sendall(code.encode('utf8') + b'\0')

            c.code = code
            print('===')
            print(code)
            print('===')

            def _gen_receive():
                try:
                    continue_recv = True
                    while continue_recv:
                        try:
                            data = sock.recv(4096)
                        except socket.timeout:
                            yield '\n\nExecution timed out'
                            return
                        if not data:
                            return
                        zeropos = data.find(b'\0')
                        if zeropos > -1:
                            data = data[:zeropos]
                            continue_recv = False
                        if not data:
                            return
                        # Let's say it won't stop in the middle
                        # octet stream ;)
                        yield data.decode('utf8', 'ignore')
                finally:
                    sock.close()

            c.result = _gen_receive()
예제 #15
0
#!/usr/local/bin/python3

from cgitb import enable
enable()
from cgi import FieldStorage
from shelve import open
from html import escape
import pymysql as db

print('Content-Type: text/plain')
print()

form_data = FieldStorage()
score = int(escape(form_data.getfirst('score', '').strip()))
game = escape(form_data.getfirst('game', '').strip())
sid = escape(form_data.getfirst('sid', '').strip())
game = game + '_score'
try:
    session_store = open('sess_' + sid, writeback=False)
    username = session_store['username']
    authenticated = session_store['authenticated']
    if authenticated:
        connection = db.connect('localhost', 'cmd14', 'idaeh',
                                'cs6503_cs1106_cmd14')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("SELECT %s FROM users WHERE username = '******';" %
                       (game, username))
        current_score = cursor.fetchone()
        if game == 'pong_score':
            if current_score[game] == None or score < int(current_score[game]):
                cursor.execute("""
예제 #16
0
building = ""
contents = ""
full_name = ""
age = ""
phone = ""
email = ""

cookie = SimpleCookie()
http_cookie_header = environ.get('HTTP_COOKIE')
try:
    form_data = FieldStorage()
    if len(form_data) != 0:
        dbList = []

        #Property
        if form_data.getfirst('property') != None and form_data.getfirst(
                'cover') != None and form_data.getfirst(
                    'occupants') != None and form_data.getfirst(
                        'insurance') != None:
            property = escape(form_data.getfirst('property'))
            cover = escape(form_data.getfirst('cover'))
            occupants = escape(form_data.getfirst('occupants'))
            insurance = escape(form_data.getfirst('insurance'))

            dbList.append(property)
            dbList.append(cover)
            dbList.append(occupants)
            dbList.append(insurance)
        else:
            propertyError = "<p class='error'>Please select an option from all of the dropdown menus.</p>"
예제 #17
0
                    connection.close()

                except db.Error:
                    result = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'

                teacher_email_name = teacher_name.replace(" ", "")
                teacher_email_name = teacher_email_name.lower()

                if len(form_data) != 0:

                    try:
                        # check which input fields contain data
                        # and from with source, i.e. from searching or from adding event
                        try:
                            student_id = escape(
                                form_data.getfirst('student_id'))
                        except:
                            student_id = ''
                        try:
                            event_date_input = escape(
                                form_data.getfirst('event-date-input'))
                        except:
                            event_date_input = ''
                        try:
                            event_descrition_input = escape(
                                form_data.getfirst('event-description-input'))
                        except:
                            event_descrition_input = ''
                        try:
                            student_1_attendance = escape(
                                form_data.getfirst('optradio1'))
예제 #18
0
     Hey, %s. Sorry to see you go.
 </p>
 <p>
     <strong>Warning! This action is permenant.</strong> All of your scores will be lost.
 </p>
 <form action="delete_account.py" method="post">
     <label for="pass1">Enter password: </label>
     <input type="password" name="pass1" id="pass1" placeholder="Enter password" required />
     <label for="pass2">Reenter password: </label>
     <input type="password" name="pass2" id="pass2" placeholder="Reenter password" required />
     <label for="confirm">Confirm Deletion: </label>
     <input type="checkbox" name="confirm" id="confirm" value="yes" />
     <input type="submit" value="Delete Account" />
 </form>""" % username
 if len(form_data) != 0:
     pass1 = escape(form_data.getfirst('pass1', '').strip())
     pass2 = escape(form_data.getfirst('pass2', '').strip())
     confirm = escape(form_data.getfirst('confirm', '').strip())
     if confirm == 'yes':
         if pass1 == pass2:
             sha256_password = sha256(
                 pass1.encode()).hexdigest()
             connection = db.connect('localhost', 'cf26',
                                     'pecah',
                                     'cs6503_cs1106_cf26')
             cursor = connection.cursor(db.cursors.DictCursor)
             cursor.execute(
                 """SELECT * FROM users
                               WHERE username = %s
                               AND password = %s""",
                 (username, sha256_password))
예제 #19
0
                                            <form action='protected_add_to_playlist.py?song_id=%s' method='post'>
                                                <select name="playlist">
                                                    %s
                                                </select>
                                                <input type="submit" value='Add'/>
                                            </form>
                                            </td>
                                    </tr>""" % (row['location'], row['name'],
                                                row['artist'], row['song_id'],
                                                playlists)
                    result += '</table>'
                    cursor.close()

                    if len(form_data) != 0:

                        genre = escape(form_data.getfirst('genre', '')).strip()
                        sort = escape(form_data.getfirst('sort', '')).strip()
                        new_playlist = escape(
                            form_data.getfirst('new_playlist', '')).strip()
                        search = escape(form_data.getfirst('search', ''))

                        genre_selection = [
                            'rock', 'punk', 'hiphop', 'electric', 'freaky', ''
                        ]
                        sort_selection = [
                            'song_id', 'artist', 'name', 'date_of_release'
                        ]

                        cursor = connection.cursor(db.cursors.DictCursor)

                        if new_playlist != '':
    if session_store.get('authenticated'):
        result2 = """<p id='larger'>No Need to Register - You are Logged In!</p>
                <p>Click on the links to continue shopping and add to your basket!</i></p>
                <p><a href="http://cs1.ucc.ie/~jd23/cgi-bin/lab7/boys.py" id='larger' >Continue to Shop for <b>Boys Toys</b></a></p>
                <p><a href="http://cs1.ucc.ie/~jd23/cgi-bin/lab7/girls.py" id='larger' >Continue to Shop for <b>Girls Toys</b></a></p>
                <p><a href="http://cs1.ucc.ie/~jd23/cgi-bin/lab7/show_cart.py" id='larger' ><b>See Your Basket</b></a></p>
                <p><a href="http://cs1.ucc.ie/~jd23/cgi-bin/lab7/checkout.py" id='larger' ><b>or... Check Out</b></a></p>
"""
        loggedIn=True
    else:
        result2 = "<p><b>Please enter in your details to Sign Up!</b></p>"
except (IOError):
    result2 = "<p>Sorry! We can't confirm you are logged in or not. Please call back later.</p>"
    
if len(form_data) != 0:
    username = escape(form_data.getfirst('username', '').strip())
    password1 = escape(form_data.getfirst('password1', '').strip())
    password2 = escape(form_data.getfirst('password2', '').strip())
    fname = escape(form_data.getfirst('fname', '').strip())
    lname = escape(form_data.getfirst('lname', '').strip())
    full_address = escape(form_data.getfirst('full_address', '').strip())
    phone = escape(form_data.getfirst('phone', '').strip())
    email = escape(form_data.getfirst('email', '').strip())
    if not username or not password1 or not password2 or not fname or not lname or not full_address or not phone or not email:
        result = '<p>Sorry! - you must fill out all the boxes</p>'
    elif password1 !=  password2 :
        result = '<p>Sorry! - your passwords much match up. Please try again.</p>'
    elif '@' not in email:
        result = '<p>Sorry! - Please enter in a valid email address. Please try again.</p>'
    else:
        try:
예제 #21
0
from cgitb import enable 
enable()

from cgi import FieldStorage, escape
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db

form_data = FieldStorage()
username = ''
result = ''
if len(form_data) != 0:
    username = escape(form_data.getfirst('username', '').strip())
    password1 = escape(form_data.getfirst('password1', '').strip())
    password2 = escape(form_data.getfirst('password2', '').strip())
    email1 = escape(form_data.getfirst('email1', '').strip())
    email2 = escape(form_data.getfirst('email2', '').strip())
    if not username or not password1 or not password2 or not email:
        result = '<p>Error: user name and passwords are required</p>'
    elif password1 != password2:
        result = '<p>Error: passwords must be equal</p>'
    elif email1 != email2:
        result = '<p>Error: emails must be equal</p>'
    else:
        try: #Begin Try
            connection = db.connect('localhost', 'userid', 'password', 'WD2_Vinyl')
            cursor = connection.cursor(db.cursors.DictCursor)
            cursor.execute("""SELECT * FROM users
예제 #22
0
파일: login.py 프로젝트: timlehane/Telocity
from cgitb import enable 
enable()

from cgi import FieldStorage, escape
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db

form_data = FieldStorage()
username = ''
result = ''
if len(form_data) != 0:
    username = escape(form_data.getfirst('username', '').strip())
    password = escape(form_data.getfirst('password', '').strip())
    if not username or not password:
        result = '<p>Error: user name and password are required</p>'
    else:
        sha256_password = sha256(password.encode()).hexdigest()
        try:
            connection = db.connect('localhost', 'userid', 'password', 'database_name')
            cursor = connection.cursor(db.cursors.DictCursor)
            cursor.execute("""SELECT * FROM users 
                              WHERE username = %s
                              AND password = %s""", (username, sha256_password))
            if cursor.rowcount == 0:
                result = '<p>Error: incorrect user name or password</p>'
            else:
                cookie = SimpleCookie()
예제 #23
0
#!/usr/local/bin/python3

from cgitb import enable
enable()

from cgi import FieldStorage
import pymysql as db

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

form_data = FieldStorage()
result =''
first_name = form_data.getfirst('name', '').strip() # we can grab any form data sent to us here

if len(form_data) != 0 : # check if there is any form data, if there is we need to do something
    #do something
    try :
        # OPTION 1:
        # if you want to add something to the database
        connection = db.connect('credentials')
        cursor = connection.cursor(db.cursors.DictCursor) # we set up a cursor to interact with the databse
        cursor.execute("""INSERT INTO people (name)
                    VALUES (%s)""", (first_name)) # always use the comma to sanitize our code
        
        connection.commit() #WaRNING HERE# # this is only needed if we are adding data to our database
    
    except db.Error : # if there is an error connecting to the database do something
        result = "Sorry yo, couldn't do what you asked" # in this case we set the result to an error message
        # this is the final print statement, it returns our edited web page
 
예제 #24
0
파일: main.py 프로젝트: tim1357/CatTrack
        return '<a href="'+to+'">'+title+'</a>'
def hitmark():
	import pickle
	
	i=pickle.load(open('hitcount','r'))
	pickle.dump(i+1,open('hitcount','w'))
	return str(i+1)
	
def topline(cat):
        return '%s| Download Raw Data (%s or %s)'%(link('CatImg.py?cat='+quote(cat),'Image'),link('CatCsv.py?cat='+quote(cat),'.csv'),link('CatWikiText.py?cat='+quote(cat),'wikitable'))

def header():
        return '''<div id="header"><center><span><font color="ccffff">Bugs/Feedback Appreciated <a style= "color: #aaffee" href="http://en.wikipedia.org/wiki/User%20talk%3ATim1357">here</a> | Check out <a style= "color: #aaffee" href="http://toolserver.org/~tim1357/cgi-bin/wikiproject_watchlist.py">my other tool</a> | '''+hitmark()+''' Hits .</font></span></center></div><h2>Tim1357's Category Tracking Tool</h2>'''

out_="""<html xmlns="http://www.w3.org/1999/xhtml"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/><link rel="stylesheet" type="text/css" href="http://toolserver.org/~tim1357/meta/style.css" />"""
_CATEGORY=form.getfirst('cat',None)
if _CATEGORY == None:
        out_+='<title>Tim1357\'s CatTrack Tool</title>'
        out_+=header()
        
else:
        from MySQLdb import connect
        db = connect(db=DB, host=HOSTNAME, read_default_file=CNFFILE)
        cursor=db.cursor()
        cursor.execute('SELECT 1 from u_tim1357.CatTrack where CatID=(select cat_id from category where cat_title=%s) limit 1;',(_CATEGORY.replace(' ','_'),))
        _temp=cursor.fetchall()
        if not _temp:
                print 'Location: https://wiki.toolserver.org/view/User:Tim1357/CatTrack/NotWatched\n\n'
                quit()
        out_+='<title>CatTrack - '+escape(_CATEGORY).replace('_',' ')+'</title>'
        out_+=header()
예제 #25
0
            
print('Content-Type: text/html') 		# this is the http header data
print()						# this is the break in the header response



form_data = FieldStorage()										# grab the submitted data (if any) into an object called 'form_data'

result = ''												# make sure to declare variables that are used in the final http response below

if len(form_data) != 0 :										# check if there is any form data, if there is we need to do something
	#do something
	result = 'change'										# this is where we can make changes to the result of our web page
	try :
		first_name = escape(form_data.getfirst('name')).strip()					# we can grab any form data sent to us here

		# 	OPTION 1: 
		# 	if you want to add something to the database

		connection = db.connect('localhost', 'userid', 'password', 'database_name')		# this is how we create a connection to the database
        	cursor = connection.cursor(db.cursors.DictCursor)					# we set up a cursor to interact with the databse
        	cursor.execute("""INSERT INTO people (name)						
                          VALUES (%s, %s)""", (first_name))						# always use the comma to sanitize our code
        	connection.commit()		#WARNING HERE#						# this is only needed if we are adding data to our database

        	# OPTION 2:
        	# else if you want to fetch something from the database
        	connection = db.connect('localhost', 'userid', 'password', 'database_name')
        	cursor = connection.cursor(db.cursors.DictCursor)
        	cursor.execute("""SELECT * FROM people
예제 #26
0
            <input type="submit" value="See Leaderboard">
            </form>"""

try:
    cookie = SimpleCookie()
    http_cookie_header = environ.get('HTTP_COOKIE')
    if http_cookie_header:
        cookie.load(http_cookie_header)
        if 'cfgof_sid' in cookie:
            cfgof_sid = cookie['cfgof_sid'].value
            session_store = open('users/sess_' + cfgof_sid, writeback=False)
            username = session_store.get("username")
            if session_store.get('authenticated'):
                result = ""
                if len(form_data) != 0:
                    type = escape(form_data.getfirst('type', '').strip())
                    game = escape(form_data.getfirst('game', '').strip())
                    result = """
                                <table>
                                    <th scope="col">Username</th><th scope="col">Score</th><th scope="col">Date</th>
                            """
                    connection = db.connect('cs1.ucc.ie', 'cjb4', 'ohchu',
                                            'cs6503_cs1106_cjb4')
                    cursor = connection.cursor(db.cursors.DictCursor)
                    if type == "personal":
                        if game == "cr":
                            cursor.execute(
                                """SELECT username, score, date_scored FROM scores
                                                WHERE username = username AND game = "chicken_run"
                                                ORDER BY score;
                                              """ (username))
예제 #27
0
파일: News.py 프로젝트: timlehane/Telocity
from cgitb import enable 
enable()

from cgi import FieldStorage
import pymysql as db

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

comments = ''
try:
    connection = db.connect('localhost', 'userid', 'password', 'database_name')
    cursor = connection.cursor(db.cursors.DictCursor)
    form_data = FieldStorage()
    if len(form_data) != 0:   
        username = form_data.getfirst('username')
        new_comment = form_data.getfirst('new_comment')
        cursor.execute("""INSERT INTO comments_table (username, comment)
                          VALUES (%s, %s)""", (username, new_comment))
        connection.commit()
    cursor.execute("""SELECT * FROM comments_table 
                      ORDER BY comment_id DESC""")
    for row in cursor.fetchall(): 
        comments += '<article><h1>%s</h1><p>%s</p></article>' % (row['username'], row['comment'])
    cursor.close()  
    connection.close()
except db.Error:
    comments = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'

print("""
    <!DOCTYPE html>
예제 #28
0
            API endpoint for updating product location.
            
    An ajax request is made to execute this endpoint. Url is /api/update_product_location.py?pid=PRODUCT_ID&lid=LOCATION_ID .
    API returns json with updated and message fields
    "updated" field --> True if the location was updated. False if not
    "message" field --> Different messages depending on outcome. These are ready to be inserted into HTML and displayed to the the user.

"""
print('Content-Type: text/json')
print()
message = {"updated": False, "message": ""}
if not loggedIn():
    message["message"] = "Sorry, you don't seem to be logged in"
else:
    form_data = FieldStorage()
    pid = form_data.getfirst("pid")
    lid = form_data.getfirst("lid")
    if pid and lid:
        result = update_location(pid, lid)
        if result == 1:
            message["message"] = "That was updated"
            message["updated"] = True
        elif result == 0:
            message["message"] = "Sorry, that location does not exist"

        elif result == -1:
            message["message"] = "Sorry, that product does not exist"

        elif result == -2:
            message["message"] = "Sorry, something went wrong"
예제 #29
0
year = ''
answer = ''
book_msg = ''
author_msg = ''
year_msg = ''
file_txt_msg = ''
file_img_msg = ''
file1 = ''
file2 = ''

if len(form_data) != 0:
    try:
        connection = db.connect('cs1dev.ucc.ie', 'sy1', 'gaequaez',
                                'csdipact2015_1_sy1')
        cursor = connection.cursor(db.cursors.DictCursor)
        bookname = escape(form_data.getfirst('bookname', "").strip())
        author = escape(form_data.getfirst('author', "").strip())
        year = escape(form_data.getfirst('year', "").strip())
        book_link = escape(form_data.getfirst('book_link', "").strip())
        images = escape(form_data.getfirst('images', "").strip())
        cursor.execute(
            "Insert INTO library (book_name, author, written, book_link, images) VALUES (%s, %s, %s, CONCAT('library/',%s), CONCAT('images/',%s))",
            (bookname, author, year, book_link, images))
        result = "<p>Congratulations! Your book_information was inserted successfully.</p>"
        connection.commit()
    except db.Error:
        result = """DB is in trouble at the moment. Call again later."""
try:
    cookie = SimpleCookie()
    http_cookie_header = environ.get('HTTP_COOKIE')
    if http_cookie_header:
예제 #30
0
#!/usr/local/bin/python3
from cgitb import enable
enable()

from os import environ
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db
from cgi import FieldStorage, escape
from datetime import datetime
cookie = SimpleCookie()
http_cookie_header = environ.get('HTTP_COOKIE')
curdate = (str(datetime.now()).split('.'))[0]
form_data = FieldStorage()
forumName = escape(form_data.getfirst('forum', ''))
post = escape(form_data.getfirst('post', '.'))

logedin = False
if http_cookie_header:
    cookie.load(http_cookie_header)
    if 'sid' in cookie:
        sessionId = cookie['sid'].value
        sessionStore = open('../session_stores/session-' + sessionId,
                            writeback=False)
        if sessionStore.get('authenticated'):
            logedin = True

if logedin == True:
    logout = "<form action='logout.py'><input type='submit' value='Log Out'></form>"

else:
예제 #31
0
def start_sse_stream(output_stream=sys.stdout):
    """Generate a stream of server-sent events according to state changes.

    This function is activated by making a request to the JavaScript
    function "initialiseEventSource()" which is located in "sse.js".
    This operation is performed by the JavaScript waitingGame function,
    and hence, other JavaScript code need only "get" a reference to
    the EventSource object (by calling "getEventSource()" from
    "sse.js").

    Reads in the game id, and repeatedly does each of the following:
        1) Check whose turn it is.
        2) Check if any new players have joined the waiting game lobby.
        3) Check if any of the players' balances have changed in a game.
        4) Check if any of the players' positions have changed in a game.
        5) Check if the specified game's status has changed to "playing".

    """
    # The following headers are compulsory for SSE.
    output_stream.write('Content-Type: text/event-stream\n')
    output_stream.write('Cache-Control: no-cache\n')
    output_stream.write('\n')

    # Read in the game id from standard input (aka. FieldStorage) and create
    # an empty dictionary of current players, positions, balances, new
    # players, new positions, new balances and turn orders. All the "new"
    # dicts will be populated with the most up to date data from the
    # **database**, while non-"new" dicts will be populated only after a
    # comparison between it and the corresponding "new" dict has been made.
    input_data = FieldStorage()
    game_id = input_data.getfirst('game')
    last_game_state = "waiting"
    players = {}
    positions = {}
    balances = {}
    new_players = {}
    new_positions = {}
    new_balances = {}
    turn = None
    turn_order = {}
    jailed_players = {}
    new_jailed_players = {}
    push_initial_user_details = True
    houses = {}
    property_ownership = {}

    # These statements are executed constantly once the first request to this
    # function is made.
    while True:
        # Create a Game object representing the game in the database.
        # This can be thought of as a "pointer" to the appropriate game in the
        # database.
        game = Game(game_id)

        # Go through each player in the game and populate the "new"
        # dictionaries with user_id (aka. player_id) as the key, and
        # username/position/balance/turn-order as the value.
        # These are the latest values retrieved from the database.
        for player in map(Player, game.players):
            new_players[player.uid] = player.username
            new_jailed_players[player.uid] = player.jail_state
            new_positions[player.uid] = player.board_position
            new_balances[player.uid] = player.balance
            turn_order[player.uid] = player.turn_position

        # Assign the current (aka. non-new) dictionaries to the value of the
        # "new" (aka. latest) dictionaries, after calling the appropriate
        # comparison function to determine whether an event should be
        # generated.
        turn = check_new_turn(output_stream, turn, game.current_turn,
                              turn_order)
        players = check_new_players(output_stream, players, new_players)
        balances = check_new_balances(output_stream, balances, new_balances)
        jailed_players = check_new_jailed_players(output_stream,
                                                  jailed_players,
                                                  new_jailed_players)
        positions = check_new_positions(output_stream, positions,
                                        new_positions, new_jailed_players)
        houses = check_property_houses(output_stream, game_id, houses)
        property_ownership = check_property_ownership(
            output_stream,
            game_id,
            property_ownership,
        )

        # Pushes data to update the players info table on game start
        if push_initial_user_details and last_game_state == "playing":
            push_initial_user_details = False
            start_game_push(output_stream, turn_order)

        # Call function to check the current state of this game.
        # A game state may be "waiting" or "playing".
        last_game_state = check_game_playing_status(output_stream, game,
                                                    last_game_state)

        time.sleep(3)

        # Flush standard out which forcefully sends everything that might be
        # buffered in standard out to the client. No need to worry about tech
        # details too much, it's just standard SSE procedure!
        output_stream.flush()
예제 #32
0
#!/usr/local/bin/python3

from cgi import FieldStorage
from random import shuffle
from cgitb import enable

enable()

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

form_data = FieldStorage()
players = form_data.getfirst('players', '')

rsp_dict = {
    0: 'Dynamite',
    1: 'Tornado',
    2: 'Quicksand',
    3: 'Pit',
    4: 'Chain',
    5: 'Gun',
    6: 'Law',
    7: 'Whip',
    8: 'Sword',
    9: 'Rock',
    10: 'Death',
    11: 'Wall',
    12: 'Sun',
    13: 'Camera',
    14: 'Fire',
    15: 'Chainsaw',
예제 #33
0
                        x[1] = 'Absent'
                    attendance_dict[x[0]] = x[1]
                cursor.close()
                cursor = connection.cursor(db.cursors.DictCursor)
                cursor.execute("""SELECT * FROM students
                                WHERE class=1""")
                for row in cursor.fetchall():
                    class_ids_list.append(row['student_id'])
                cursor.close()

            except db.Error:
                result = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'

            if len(form_data) != 0:
                try:
                    student_id = escape(form_data.getfirst('student_id'))
                    connection = db.connect('cs1.ucc.ie', 'rjf1', 'ahf1Aeho',
                                            '2021_rjf1')
                    cursor = connection.cursor(db.cursors.DictCursor)

                    cursor.execute("""SELECT * FROM students
                                    WHERE student_id = '%s'""" % (student_id))
                    for row in cursor.fetchall():
                        #result+=row
                        student_firstname = row['first_name']
                        student_lastname = row['last_name']
                        student_phone_number = row['phone_number']
                    #result += '</table>'
                    cursor.close()

                    cursor = connection.cursor(db.cursors.DictCursor)
예제 #34
0
#!/usr/bin/python3
from cgi import FieldStorage
from python.login import *
from python.databases.databaseQueries import get_product_info
"""
API endpoint for getting product location on map.

An ajax request is made to execute this endpoint. Url is /api/get_product_map?pid=PRODUCT_ID .
API returns an image tag containing the map
"""
print('Content-Type: text/html')
print()
message = "/assets/images/404.gif"
if not loggedIn():
    pass
else:
    form_data = FieldStorage()
    pid = form_data.getfirst("pid")

    result = form_data.getfirst("pid")
    if pid:
        result = get_product_info(pid)
        if result:
            map_image = result["location_info"]["map"]
            map_image = map_image.split(".")[0]
            map_image += "-min.png"
            message = map_image

print(str(message))
예제 #35
0
        cookie.load(http_cookie)
        if 'karols_sid' in cookie:
            try:
                karols_sid = cookie['karols_sid'].value
                session_store = open('../js_python/sessions/sess_' +
                                     karols_sid,
                                     writeback=True)
                if session_store['authenticated']:
                    return session_store['username'] == 'admin'
            except IOError:
                return ''
    return ''


if len(form_data):
    comment_id = escape(form_data.getfirst('my_id', '')).strip()
    if isAdmin():

        try:
            connection = db.connect('localhost', 'kpp1', 'mah9eiQu',
                                    '2021_kpp1')
            cursor = connection.cursor(db.cursors.DictCursor)

            cursor.execute('SELECT * from comments WHERE comment_id = %s',
                           comment_id)
            if cursor.rowcount == 0:
                result = 'fail'
            else:
                cursor.execute(
                    """
                    DELETE from comments WHERE comment_id = %s
예제 #36
0
파일: login.py 프로젝트: AdamBOD/arcade
#!/usr/local/bin/python3

from cgitb import enable
enable()

from cgi import FieldStorage, escape
from hashlib import sha256
import pymysql as db
from http.cookies import SimpleCookie
from shelve import open
from time import time

form_data = FieldStorage()
username = escape(form_data.getfirst("username", '').strip())
password = escape(form_data.getfirst("password", '').strip())
result = """"""

if len(form_data) > 0:
    #try:
    connection = db.connect('cs1dev.ucc.ie', 'ajbod1', 'eimaidae',
                            'users_ajbod1')
    cursor = connection.cursor(db.cursors.DictCursor)
    cursor.execute(
        """SELECT * 
                      FROM register 
                      WHERE username=%s AND userpassword=%s """,
        (username, password))

    if cursor.rowcount > 0:
        cookie = SimpleCookie()
        sid = sha256(repr(time()).encode()).hexdigest()
예제 #37
0
            session_store = open('sess_' + sid, writeback=False)
            if session_store.get('authenticated'):
                username = session_store.get('username')
                try:
                    connection = db.connect('localhost', 'root', 'fordemc2', 'projects')
                    cursor = connection.cursor(db.cursors.DictCursor)

                    cursor.execute("""SELECT DISTINCT playlist_name FROM playlists 
                    where username=%s""", username)
                    if cursor.rowcount != 0:
                        playlists = ''
                        for row in cursor.fetchall():
                            playlists += '<option value="%s">%s</option>' % (row['playlist_name'], row['playlist_name'])

                    if len(form_data) != 0:
                        playlist = escape(form_data.getfirst('playlist', '')).strip()
                        cursor.execute("""SELECT * FROM music WHERE song_id in (select song_id from playlists where username = %s and playlist_name = %s)""", (username, playlist))
                        result = """
                                <audio controls source src='' type='audio/mp3' id='audioPlayer'>
                                    <p>Sorry, Your browser doesn't support HTML5</p>
                                </audio>
                                <table id='songlist'>
                                    <tr><th colspan="3">Your %s Playlist</th></tr>
                                    <tr><th>Name</th><th>Artist</th><th>Delete</th></tr>""" % playlist

                        for row in cursor.fetchall():
                            result += """<tr>
                                            <td><a href='%s'>%s</a></td>
                                            <td>%s</td>
                                            <td>       
                                                <form action="protected_remove_from_playlist.py?playlist=%s&song_id=%s" method='post'>
예제 #38
0
#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db

form_data = FieldStorage()
username = ''
result = ''
if len(form_data) != 0:
    username = escape(form_data.getfirst('username', '').strip())
    password = escape(form_data.getfirst('password', '').strip())
    if not username or not password:
        result = '<p>Error: username and password are required</p>'
    else:
        sha256_password = sha256(password.encode()).hexdigest()
        try:
            connection = db.connect('localhost', 'cmd14', 'idaeh',
                                    'cs6503_cs1106_cmd14')
            cursor = connection.cursor(db.cursors.DictCursor)
            cursor.execute(
                """SELECT * FROM users
                              WHERE username = %s
                              AND password = %s""",
                (username, sha256_password))
            if cursor.rowcount == 0:
예제 #39
0
      </label>
    </div>
    <button class="landing btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="error-message">No account? <a href="signup.py">Sign up</a></p>
  </form>

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>"""

cookie = SimpleCookie()
http_cookie_header = environ.get('HTTP_COOKIE')

form_data = FieldStorage()
email = escape(form_data.getfirst('email', "").strip())
password = escape(form_data.getfirst('password', "").strip())

if email != '':
    connection = db.connect('cs1.ucc.ie', 'rjf1', 'ahf1Aeho', '2021_rjf1')
    cursor = connection.cursor(db.cursors.DictCursor)
    search_result = cursor.execute(
        """SELECT * FROM users WHERE email = %s AND password = %s""",
        (email, password))

    #user found and password match, issue cookie and redirect to homepage
    if search_result == 1:
        cookie = SimpleCookie()
        sid = sha256(repr(time()).encode()).hexdigest()
        cookie['sid'] = sid
        session_store = open('sess_' + sid, writeback=True)
예제 #40
0
from os import environ                        # import files needed
from http.cookies import SimpleCookie         # the header section will most likely be provided by Derek Bridge


print("Content-Type: text/html")              # very likely he might ask us for this
print()                                       # don't forget this print, it signals the end of the HTTP header

form_data = FieldStorage()      # grab the data that has been sent to us 

http_cookie_header = environ.get('HTTP_COOKIE')     # check if there are any cookies in the header
if not http_cookie_header :                         # if there isn't proceed
  if len(form_data) != 0 :                          # check if we have been given form data
    # we have data, let's do something with it
    try :
      band_vote = escape(form_data.getfirst('bands')).strip()     # store the band voted for as band_vote
      
      connection = db.connect('localhost', 'userid', 'password', 'database_name')     # connect to database
      cursor = connection.cursor(db.cursors.DictCursor)           # set up cursor
      cursor.execute("""UPDATE votes
                        SET num_votes = num_votes + 1
                        WHERE band = '%s'""", (band_vote))        # don't forget the comma to sanitize
      cursor.commit()                                             # needed because we updated the database
      cookie = SimpleCookie()                         # create a cookie object called cookie 
      cookie['band'] = band_vote                      # set it's value to the band we voted for
      cookie['band']['expires'] = 9999999             # don't firget to set an expiration date
      result = 'Woo, you voted for %s. What terrible taste' % band_vote;
    except db.Error :                       # this is called if something goes wrong connecting to the database
      result = 'Something went wrong!'         # create an error message if we coudn't connect
else :                                      # the user already voted
  cookie.load(http_cookie_header)
예제 #41
0
#!/usr/local/bin/python3

from cgi import FieldStorage
import pymysql as db
from math import ceil
from html import escape
from cgitb import enable
enable()

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

form_data = FieldStorage()
country = escape(form_data.getfirst('country', '')).strip()
points = escape(form_data.getfirst('points', '')).strip()

form = ''
output = ''

try:
    connection = db.connect('localhost', 'cf26', 'pecah', 'cs6503_cs1106_cf26')
    # connection = db.connect('localhost', 'cf26', 'p', 'cs6503_cs1106_cf26')
    cursor = connection.cursor(db.cursors.DictCursor)
    cursor.execute("""SELECT DISTINCT country FROM winners""")
    form = """<form action="eurovision.py" method="get">
        <label for="country">Search by Country:</label>
        <select name="country" id="country">
            <option value="" label="Please select a country"></option>"""
    for row in cursor.fetchall():
        if row['country'] == country:
            form += """<option value="%s" selected>%s</option>""" % (
from cgitb import enable 
enable()

from cgi import FieldStorage, escape
import pymysql as db
            
print('Content-Type: text/html')
print()

form_data = FieldStorage()

result = ''
candidate=''

candidate= form_data.getfirst('candidate')

try:
    if candidate !=None:
        connection = db.connect(# login)
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT candidate_name FROM candidates WHERE candidate_name= %s""" , (candidate))
        if cursor.rowcount==1 :
            result=('Sorry, your candidate was already found in the database.')
        else:
            cursor.execute("""INSERT into candidates (candidate_name, total_votes)
                      values (%s,0)""" , (candidate))
            connection.commit()
            cursor.close()
            connection.close()
            result=('Thanks for adding a candidate!')
예제 #43
0
#!/usr/local/bin/python3

from cgitb import enable

enable()

from cgi import FieldStorage

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

form_data = FieldStorage()
mass_kg = form_data.getfirst('mass_kg', '').strip()
height_m = form_data.getfirst('height_m', '').strip()

outcome = ''
try:
    mass_kg = float(mass_kg)
    height_m = float(height_m)
    bmi = mass_kg / (height_m * height_m)
    category = ''
    if bmi < 18.5:
        category = 'underweight'
    elif bmi > 25:
        category = 'overweight'
    else:
        category = 'normal'
    outcome = """Your mass in kg is %.1f. Your height in m is %.1f.
                 Your BMI is %.2f. You are %s.""" % (mass_kg, height_m, bmi,
                                                     category)
except ValueError:
예제 #44
0
class application(object):
    # don't serve static by default
    static_serve = False
    static_alias = { '' : 'ketcher.html' }
    static_root = None

    indigo = None
    indigo_inchi = None

    def __init__(self, environ, start_response):
        self.path = environ['PATH_INFO'].strip('/')
        self.method = environ['REQUEST_METHOD']
        self.content_type = environ.get('CONTENT_TYPE', '')
        self.fields = FieldStorage(fp=environ['wsgi.input'],
                                   environ=environ, keep_blank_values=True)
        self.FileWrapper = environ.get('wsgi.file_wrapper', FileWrapper)
        self.headers = Headers([])

        route = getattr(self, 'on_' + self.path, None)
        if route is None:
            route = self.serve_static if self.method == 'GET' and \
                                         self.static_serve else self.notsupported

        status = "200 OK"
        try:
            self.response = route()
        except self.HttpException as e:
            status = e.args[0]
            self.response = [e.args[1]]

        self.headers.setdefault('Content-Type', 'text/plain')
        start_response(status, self.headers.items())

    def __iter__(self):
        for chunk in self.response:
            yield chunk if sys.version_info[0] < 3 or \
                           not hasattr(chunk, 'encode') else chunk.encode()

    def notsupported(self):
        raise self.HttpException("405 Method Not Allowed",
                                 "Request not supported")

    def indigo_required(method):
        def wrapper(self, **args):
            if not self.indigo:
                raise self.HttpException("501 Not Implemented",
                                         "Indigo libraries are not found")
            try:
                return method(self, **args)
            except indigo.IndigoException as e:
                message = str(sys.exc_info()[1])
                if 'indigoLoad' in message:    # error on load
                    message = "Cannot load the specified " + \
                              "structure: %s " % str(e)
                raise self.HttpException("400 Bad Request",
                                         message)
        return wrapper

    @indigo_required
    def on_knocknock(self):
        return ["You are welcome!"]

    @indigo_required
    def on_layout(self):
        moldata = None
        if self.method == 'GET' and 'smiles' in self.fields:
            moldata = self.fields.getfirst('smiles')
        elif self.is_form_request() and 'moldata' in self.fields:
            moldata = self.fields.getfirst('moldata')
        selective = 'selective' in self.fields
        if moldata:
            if '>>' in moldata or moldata.startswith('$RXN'):
                rxn = self.indigo.loadQueryReaction(moldata)
                if selective:
                    for mol in rxn.iterateMolecules():
                        self.selective_layout(mol)
                else:
                    rxn.layout()
                return ["Ok.\n",
                        rxn.rxnfile()]
            elif moldata.startswith('InChI'):
                mol = self.indigo_inchi.loadMolecule(moldata)
                mol.layout()
                return ["Ok.\n",
                        mol.molfile()]
            else:
                mol = self.indigo.loadQueryMolecule(moldata)
                if selective:
                    for rg in mol.iterateRGroups():
                        for frag in rg.iterateRGroupFragments():
                            self.selective_layout(frag)
                    self.selective_layout(mol)
                else:
                    mol.layout()
                return ["Ok.\n",
                        mol.molfile()]
        self.notsupported()

    @indigo_required
    def on_automap(self):
        moldata = None
        if self.method == 'GET' and 'smiles' in self.fields:
            moldata = self.fields.getfirst('smiles')
        elif self.is_form_request() and 'moldata' in self.fields:
            moldata = self.fields.getfirst('moldata')

        if moldata:
            mode = self.fields.getfirst('mode', 'discard')
            rxn = self.indigo.loadQueryReaction(moldata)
            if not moldata.startswith('$RXN'):
                rxn.layout()
            rxn.automap(mode)
            return ["Ok.\n",
                    rxn.rxnfile()]
        self.notsupported()

    @indigo_required
    def on_aromatize(self):
        try:
            md, is_rxn = self.load_moldata()
        except:
            message = str(sys.exc_info()[1])
            if message.startswith("\"molfile loader:") and \
               message.endswith("queries\""): # hack to avoid user confusion
                md, is_rxn = self.load_moldata(True)
            else:
                raise
        md.aromatize()
        return ["Ok.\n",
                md.rxnfile() if is_rxn else md.molfile()]

    @indigo_required
    def on_getinchi(self):
        md, is_rxn = self.load_moldata()
        inchi = self.indigo_inchi.getInchi(md)
        return ["Ok.\n", inchi]

    @indigo_required
    def on_dearomatize(self):
        try:
            md, is_rxn = self.load_moldata()
        except:                 # TODO: test for query features presence
            raise self.HttpException("400 Bad Request",
                                     "Molecules and reactions " + \
                                     "containing query features " + \
                                     "cannot be dearomatized yet.")
        md.dearomatize()
        return ["Ok.\n",
                md.rxnfile() if is_rxn else md.molfile()]

    def on_open(self):
        if self.is_form_request():
            self.headers.add_header('Content-Type', 'text/html')
            return ['<html><body onload="parent.ui.loadMoleculeFromFile()" title="',
                    b64encode("Ok.\n"),
                    b64encode(self.fields.getfirst('filedata')),
                    '"></body></html>']
        self.notsupported()

    def on_save(self):
        if self.is_form_request():
            type, data = self.fields.getfirst('filedata').split('\n', 1)
            type = type.strip()
            if type == 'smi':
                self.headers.add_header('Content-Type',
                                        'chemical/x-daylight-smiles')
            elif type == 'mol':
                if data.startswith('$RXN'):
                    type = 'rxn'
                self.headers.add_header('Content-Type',
                                        'chemical/x-mdl-%sfile' % type)

            self.headers.add_header('Content-Length', str(len(data)))
            self.headers.add_header('Content-Disposition', 'attachment',
                                    filename='ketcher.%s' % type)
            return [data]
        self.notsupported()

    class HttpException(Exception): pass
    def load_moldata(self, is_query=False):
        moldata = self.fields.getfirst('moldata')
        if moldata.startswith('$RXN'):
            if is_query:
                md = self.indigo.loadQueryReaction(moldata)
            else:
                md = self.indigo.loadReaction(moldata)
            is_rxn = True
        else:
            if is_query:
                md = self.indigo.loadQueryMolecule(moldata)
            else:
                md = self.indigo.loadMolecule(moldata)
            is_rxn = False
        return md, is_rxn

    def selective_layout(self, mol):
        dsgs = [dsg for dsg in mol.iterateDataSGroups() \
                if dsg.description() == '_ketcher_selective_layout' and \
                dsg.data() == '1']
        atoms = sorted([atom.index() for dsg in dsgs \
                        for atom in dsg.iterateAtoms()])
        for dsg in dsgs:
            dsg.remove()
        mol.getSubmolecule(atoms).layout()
        return mol

    def serve_static(self):
        root = self.static_root or getcwd()
        fpath = self.static_alias.get(self.path, self.path)
        fpath = path.abspath(path.join(root, fpath))

        if not fpath.startswith(root + path.sep) or not path.isfile(fpath) \
           or fpath == path.abspath(__file__):
            raise self.HttpException("404 Not Found",
                                     "Requested file isn't accessible")

        self.headers['Content-Type'] = guess_type(fpath)[0] or 'text/plain'
        try:
            fd = open(fpath, 'rb')
            return self.FileWrapper(fd) if self.method == 'GET' else ['']
        except (IOError, OSError):
            raise self.HttpException("402 Payment Required",  # or 403, hmm..
                                     "Must get more money for overtime")

    def is_form_request(self):
        return self.method == 'POST' and \
               (self.content_type.startswith('application/x-www-form-urlencoded')
                or self.content_type.startswith('multipart/form-data'))