def get_videos():
    """
    Retrieves a list of available video resources, potentially filtered by
    it's YouTube video id
    """

    data = request.args
    if 'vid' in data:
        cursor = database.execute(
            """
            SELECT video_id, video_vid, video_title, video_screening_status FROM Videos
            WHERE video_vid = ?
            """,
            data['vid'],
        )
    else:
        cursor = database.execute("""
            SELECT video_id, video_vid, video_title, video_screening_status FROM Videos
            """)

    row = cursor.fetchall()

    if not row:
        return Response(status=http.HTTPStatus.NOT_FOUND)
    else:
        return Response(response=json.dumps(list(map(dict, row))),
                        headers={"Content-Type": "text/json"},
                        status=http.HTTPStatus.OK)
Beispiel #2
0
def login(username):
    if username:
        return render_template('index.html',
                               username=username,
                               error='Already logged in.')

    if request.method == 'GET':
        return render_template('login.html')

    username = request.form['username']
    password = request.form['password']
    if not username.isalnum():
        return render_template('login.html', error='Bad username!')

    correct = auth_helper.check_login(username, password)
    if not correct:
        return render_template('login.html', error='Incorrect password.')

    session_id = auth_helper.generate_session_id()
    database.execute("INSERT INTO sessions VALUES ('{}', '{}');".format(
        session_id, username))

    resp = redirect(url_for('wall'))
    resp.set_cookie('SESSION_ID', session_id)
    return resp
Beispiel #3
0
def profile(username):
    if not username:
        return render_template('login.html', error='Please log in.')

    if request.method == 'GET':
        avatar_filename, age = get_user_info(username)
        age = escape_html(str(age))
        return render_template('profile.html',
                               username=username,
                               avatar=avatar_filename,
                               age=age)

    if 'avatar' in request.files:
        avatar = request.files['avatar']
        stored_avatar_filename = avatar_helper.save_avatar_image(
            avatar, username)
        stored_avatar_filename = escape_sql(
            escape_html(stored_avatar_filename))
        if stored_avatar_filename:
            database.execute(
                "UPDATE users SET avatar='{}' WHERE username='******';".format(
                    stored_avatar_filename, username))
    else:
        username = escape_sql(request.form['username'])
        age = escape_html(escape_sql(request.form['age']))
        database.execute("UPDATE users SET age={} WHERE username='******';".format(
            age, username))

    return redirect(url_for('wall'))
Beispiel #4
0
def publishPost(postId):
	database.execute(sql="""
		UPDATE post SET
			  postStatusId=(SELECT id FROM poststatus WHERE status='Published' LIMIT 1)
			, publishedDateTime=CASE
				WHEN publishedDateTime IS NULL THEN %s
				ELSE publishedDateTime
			END
			, publishedYear=CASE
				WHEN publishedYear IS NULL THEN %s
				ELSE publishedYear
			END
			, publishedMonth=CASE
				WHEN publishedMonth IS NULL THEN %s
				ELSE publishedMonth
			END
		WHERE id=%s
	""", parameters=(
		dthelper.formatDateTime(date=dthelper.utcNow()),
		dthelper.getYear(date=dthelper.utcNow()),
		dthelper.getMonth(date=dthelper.utcNow()),
		postId,
	))

	return database.LAST_NUM_AFFECTED
Beispiel #5
0
    def execute(self):
        if self.if_exists():
            print(
                f"There are records for {self.date}, therefore deleting them before insert"
            )
            execute(
                f"DELETE FROM {USER_EVENTS_TABLE} WHERE date = '{self.date}'")

        query = f"""
        INSERT INTO {self.table}
        SELECT
            id,
            event_type AS status,
            username AS name,
            user_email AS email,
            user_type AS type,
            organization_name,
            plan_name,
            received_at,
            date AS start_date
        FROM {USER_EVENTS_TABLE}
        WHERE date = '{self.date}'
        RETURNING *;
        """
        results = execute(query)
        print_results(results)
Beispiel #6
0
def index(request):
    init.first()
    
    if request.POST.has_key('taskname'):
        taskname = str(request.POST['taskname'])
        description = str(request.POST['taskdescription'])
        content = str(request.POST['taskcode'])
        fw = open("%s.sql" % taskname,"w")
        fw.write(content)
        fw.close()
            
            #fw.write("mysql -h localhost -u root -pflanker < %s.sql\n" %(taskname))
            #subprocess.Popen("chmod +x %s.sh" %(taskname), shell = True)
    else:
        taskname = ''
        description = ''
        content = ''
        
    if taskname == '':
        return render_to_response('addpage.html', {'taskname': taskname, 'taskdescription': description, 'sqlcode': content,'addstatus':'no'})

    
    try:
        database.execute('insert tasklist (name,file,status,description) values(\'%s\',\'%s.sql\',\'did not start\',\'%s\')' % (taskname, taskname, description))
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
	def register_device(self, registrar_key):
		keyfound_token = False
		for user in unregistered_dataset():
			if build_test_hash(user) == registrar_key:
				database.execute("UPDATE users SET registered = 1 WHERE codename = ?;", (str(user[1]),))
				keyfound_token = True
		return keyfound_token
Beispiel #8
0
def runsql(taskname,sqlfile):
    
    username = '******'
    password = '******'
    if(os.path.exists('config.txt')):
        fr = open("config.txt","r")
        list_of_all_the_lines = fr.readlines()
        username = list_of_all_the_lines[2][0:-1]
        password = list_of_all_the_lines[3][0:-1]
        fr.close()
    
    cmd = "mysql -h localhost -u %s -p%s < %s" %(username, password, sqlfile)
    ferr = open('test.txt','w')
    ferr.write('update tasklist set status = \'running\' where name = \'%s\'' %taskname)
    ferr.close()
    database.execute('update tasklist set status = \'running\' where name = \'%s\'' %taskname)
    child = subprocess.Popen(cmd, shell = True)
    child.wait()
    
    database.execute('update tasklist set status = \'finished\' where name = \'%s\'' %taskname)
    
    nexttask = database.getlist("select name from tasklist where status = \'started\'")
    for task in nexttask:
        
        #parent = database.getlist("select u from edges where v = \'%s\'" %task)
        #if taskname not in parent:
            #continue
        
        if judge(task):
            thread.start_new_thread(runsql, (task, '%s.sql' %task)) 
Beispiel #9
0
def create_user(username, email, password):
    now = datetime.datetime.now().strftime('%Y%m%d %H:%M:%S')
    sql = """
    INSERT INTO user (username, email, password, create_time)
    values ('%s', '%s', '%s', '%s')
    """ % (username, email, password, now)
    execute(sql)
def create_service(device,
                   name="telnet",
                   n=1,
                   part_owner=None,
                   owner=super_uuid,
                   speed=None,
                   clear_service=True):
    if clear_service:
        clear_services()

    service_uuids = []
    for i in range(n):
        service_uuids.append(uuid())
        execute(
            "INSERT INTO service_service (uuid, device, owner, name, running, running_port, part_owner, speed) "
            "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
            service_uuids[i],
            device,
            owner,
            name,
            i % 2 == 0,
            1337,
            part_owner,
            speed,
        )

    return service_uuids
Beispiel #11
0
def addMatch(mentorId, menteeId):
	if mentorId!=menteeId:
		sql = """INSERT INTO matches(mentorId,
	    menteeId)
	    VALUES ('%d', '%d')""" % (mentorId, menteeId)
		database.execute(sql)
		return True
	return False
Beispiel #12
0
def update(key, value):
    if not is_exists(key):
        raise DocumentNotExist

    database.execute(
        "UPDATE documents SET value = ? WHERE id = ?", json.dumps(value), key
    )
    return Document(key, value)
def _store_city(resp):
    """Check cities exists in the DB, and if not stores them in the places table."""
    city = resp['city']
    row = database.query_row('SELECT COUNT(*) FROM Place WHERE Id = ?', (city['id'],))    
    if (row[0] == 0):
        database.execute('INSERT INTO Place (Id, Name, CoordLon, CoordLat, Country) VALUES (?,?,?,?,?)', (city['id'], city['name'], city['coord']['lon'], city['coord']['lat'], city['country']))
        database.commit()
        app.logger.info('Place %s added', city['name'])
    return city['id']
Beispiel #14
0
def delete_trip(id=None):
    trip = database.fetchone('SELECT * FROM trips WHERE id="{}";'.format(id))
    if not trip:
        return render_template('trips.html', error='Invalid trip ID')
    trip = get_trip_obj(trip)

    database.execute('DELETE FROM trips WHERE id="{}";'.format(id))
    database.execute('DELETE FROM carpools WHERE id="{}";'.format(id))
    return redirect(url_for('my_trips'))
Beispiel #15
0
def delete_survey(survey_id):
    stmt = "delete from survey where id = {survey_id}".format(
        survey_id=survey_id)
    db.execute(stmt)
    #     stmt = "delete from question where survey_id = {survey_id}".format(survey_id = survey_id)
    #     db.execute(stmt)
    #     stmt = "delete from option where survey_id = {survey_id}".format(survey_id = survey_id)
    #     db.execute(stmt)
    return surveys()
def post(username):
    if not username:
        return render_template('login.html', error='Please log in.')

    if request.method == 'GET':
        return render_template('post.html', username=username)

    post = escape_sql(request.form['post'])
    database.execute("INSERT INTO posts VALUES ('{}', '{}');".format(username, post))
    return redirect(url_for('wall'))
def setup_service_req(device_uuid) -> str:
    execute("TRUNCATE device_service_req")
    execute(
        "INSERT INTO device_service_req "
        "(service_uuid, device_uuid, allocated_cpu, allocated_ram, allocated_gpu, allocated_disk, allocated_network) "
        "VALUES (%s, %s, 1, 4, 2, 8, 16)",
        service_uuid := uuid(),
        device_uuid,
    )
    return service_uuid
Beispiel #18
0
def archivePost(postId):
	database.execute(sql="""
		UPDATE post SET
			postStatusId=(SELECT id FROM poststatus WHERE status='Archived' LIMIT 1)
		WHERE id=%s
	""", parameters=(
		postId,
	))

	return database.LAST_NUM_AFFECTED
Beispiel #19
0
def deletePost(postId):
	database.execute(sql="""
		DELETE FROM post_posttag
		WHERE postId=%s
	""", parameters=(postId,))

	database.execute(sql="""
		DELETE FROM post
		WHERE id=%s
	""", parameters=(postId,))
Beispiel #20
0
def index(request):
    init.first()
    
    try:

        name = ''
        ss = request.path
        if name == '':
            name = ss[21:]
                
        res = database.getlist('select description from tasklist where name = \'%s\'' % (name))
        description = res[0]

		
        ferr = open("error_modify.log","w")
        
        task = ''
        if request.POST.has_key('taskname'):
            task = str(request.POST['taskname'])

        ferr.write(r'-----%s' %(task))
        if task == name:
            code = str(request.POST['taskcode'])
            description = str(request.POST['taskdescription'])
            isModify = 'yes'
            fw = open("%s.sql" %(task),"w")
            fw.write(code)
            fw.close()
            database.execute('update tasklist set name = \'%s\', file = \'%s.sql\', description = \'%s\' where name = \'%s\'' %(task, task, description, name))
            database.execute('update edges set u = \'%s\' where u = \'%s\'' %(task, name))
            database.execute('update edges set v = \'%s\' where v = \'%s\'' %(task, name))
        else:
            task = name
            isModify = 'no'
            fr = open("%s.sql" %(name),"r")
            code = fr.read()
            fr.close()

        ferr.write(code)
        
        ferr.close()
        
        if request.POST.has_key('taskkind'):
            taskkind = str(request.POST['taskkind'])
            if taskkind == 'timed':
                hour = str(request.POST['hour'])
                minute = str(request.POST['minute'])
                database.execute('update tasklist set type = \'%s-%s\' where name = \'%s\'' %(hour, minute, task))
            else:
                database.execute('update tasklist set type = NULL where name = \'%s\'' %task )
            
        return render_to_response('modifypage.html', {'taskname': task,'modifystatus': isModify, 'taskdescription': description,'taskcode': code})
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
         return render_to_response('modifypage.html')
Beispiel #21
0
def addPerson(username, password, fname, lname, status):
	sha1.update(password)
	if usernameAvailable(username):
		sql = """INSERT INTO person(username,
	    password, fname, lname, status)
	    VALUES ('%s', '%s', '%s', '%s', '%s');""" % (username, sha1.hexdigest(), fname, lname, status)
		cursor = database.execute(sql)
		cursor = database.execute("""SELECT id FROM person WHERE username = '******';""" % username)
		person_id = cursor.fetchone()[0]
		return person_id
	return None
Beispiel #22
0
def saveSettings(accessKeyId, secretAccessKey, s3Bucket):
	database.execute(sql="""
		UPDATE awssettings SET
			  accessKeyId=%s
			, secretAccessKey=%s
			, s3Bucket=%s
	""", parameters=(
		accessKeyId,
		secretAccessKey,
		s3Bucket,
	))
Beispiel #23
0
def leave_trip(id=None):
    username = session['username']
    trip = database.fetchone('SELECT * FROM trips WHERE id="{}";'.format(id))
    if not trip:
        return render_template('trips.html', error='Invalid trip ID')
    trip = get_trip_obj(trip)

    database.execute(
        'DELETE FROM carpools WHERE id="{}" AND username="******";'.format(
            id, username))
    return redirect(url_for('trip', id=id))
    def test_delete_successful(self):
        clear_devices()
        device = Device.starter_device(self.client)
        execute("UPDATE device_device SET starter_device=FALSE WHERE uuid=%s", device.uuid)

        expected = {"ok": True}
        actual = self.client.ms("device", ["device", "delete"], device_uuid=device.uuid)
        self.assertEqual(expected, actual)

        with self.assertRaises(DeviceNotFoundException):
            device.update()
Beispiel #25
0
def append_database(id_, created_at, name, message, sender):
    logging.info(f'Appending message: {created_at}')
    logging.info(f'Messages: {message}, sender: {sender}')
    message = message.replace("'", '').replace('"', '')
    name = name.replace("'", '').replace('"', '')
    try:
        database.execute('groupmebot', f"INSERT INTO GROUPMEBOT.MESSAGES VALUES('{id_}', {created_at}, '{name}', '{message}', "
                                       f"{sender})")
    except Exception as e:
        logging.error(e)
        logging.error('Failed to upload to database')
Beispiel #26
0
def init():    
    today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    database.init()
    database.execute('update tasklist set status = \'started\'')
    fw = open('date.log', 'w')
    fw.write(today)
    fw.close()
    tasklist = database.getlist('select name from tasklist')
    statuslist = database.getlist('select status from tasklist')
    for i in range(0,len(tasklist)):
        if(statuslist[i] == 'started'):
            checktask(tasklist[i])
Beispiel #27
0
def deleteUnusedPostTags(postId, tagsToKeep):
	tableName = "tagstodelete{0}".format(uuid.uuid4().hex)

	database.execute(sql="""
		CREATE TEMPORARY TABLE {tablename} (
			id INT UNSIGNED,
			tag VARCHAR(20)
		);
	""".format(
		tablename=tableName
	))

	database.execute(sql="""
		INSERT INTO {tablename} (id, tag)
		SELECT posttag.id, posttag.tag
		FROM post_posttag
			JOIN posttag ON posttag.id=post_posttag.postTagId
		WHERE
			post_posttag.postId={postId}
			AND posttag.tag NOT IN ({tagPlaceholders})
		;
	""".format(
		tablename=tableName,
		postId=postId,
		tagPlaceholders=", ".join(["%s" for t in tagsToKeep]),
	), parameters=tuple(tagsToKeep))

	database.execute(sql="""
		DELETE post_posttag FROM post_posttag
		JOIN {tablename} ON {tablename}.id=post_posttag.postTagId
		WHERE
			postId=%s
		;
	""".format(
		tablename=tableName,
	), parameters=(postId,))

	database.execute(sql="""
		UPDATE posttag SET
			howManyTimesUsed = howManyTimesUsed - 1
		WHERE
			id=(SELECT id FROM {tablename})
		;
	""".format(
		tablename=tableName,
	))

	database.execute(sql="""
		DROP TABLE {tablename};
	""".format(
		tablename=tableName,
	))
def setup_workload(device_uuid=None, clear_device=True) -> str:
    if clear_device:
        clear_devices()
    if device_uuid is None:
        device_uuid = uuid()
    execute("TRUNCATE device_workload")
    execute(
        "INSERT INTO device_workload "
        "(uuid, performance_cpu, performance_gpu, performance_ram, performance_disk, performance_network, "
        "usage_cpu, usage_gpu, usage_ram, usage_disk, usage_network) VALUES "
        "(%s, 10, 20, 40, 80, 160, 1, 4, 16, 64, 256)",
        device_uuid,
    )
    return device_uuid
Beispiel #29
0
    def update2db(self, commit=True, **kwargs):
        assert hasattr(self, self.primary_key)
        if kwargs:
            kw = dict(**kwargs)
        else:
            kw = {key: value for key,
                  value in self._obj.items() if key != self.primary_key}
        sql = "update {0} set {1} where {2}='{3}'".format(self.table,
                                                          ', '.join(["{}={}".format(key, self.keys[key]) for key in kw.keys()]),
                                                          self.primary_key, getattr(self, self.primary_key))
        execute(sql, sql_params=kw.values(), conn=self.conn, commit=commit)


        for k, v in kw.items():
            setattr(self, k, v)
Beispiel #30
0
def createUpdatePostTags(postId, tags):
	createTagSql = """
		INSERT INTO posttag (
			  tag
			, howManyTimesUsed
		) VALUES
	"""

	createLinkSql = """
		INSERT INTO post_posttag (postId, postTagId)
		SELECT %s, id FROM posttag WHERE tag IN (
	"""

	createTagParameters = []
	createLinkParameters = [int(postId)]

	for index, tagName in enumerate(tags):
		createTagSql += " (%s, 1)"
		createLinkSql += "%s"

		if index < len(tags) - 1:
			createTagSql += ","
			createLinkSql += ", "

		createTagParameters.append(tagName)
		createLinkParameters.append(tagName)

	createTagSql += " ON DUPLICATE KEY UPDATE howManyTimesUsed = howManyTimesUsed + 1"
	createLinkSql += ") ON DUPLICATE KEY UPDATE postTagId = VALUES(postTagId)"

	createTagParameters = tuple(createTagParameters)
	createLinkParameters = tuple(createLinkParameters)

	#
	# First create any new tags or update usage counts for existing tags.
	#
	database.execute(sql=createTagSql, parameters=createTagParameters)

	#
	# Next delete post -> tag association records that are no longer
	# needed.
	#
	deleteUnusedPostTags(postId=postId, tagsToKeep=tags)

	#
	# Create any new post -> tag association records.
	#
	database.execute(sql=createLinkSql, parameters=createLinkParameters)
Beispiel #31
0
 def reload(self):
     assert hasattr(self, self.primary_key)
     keys = ["unix_timestamp(%s)" % key if self.keys[key] == 'from_unixtime(%s)' else key for key in self.keys.keys()]
     sql = 'select %s from %s %s' % (','.join(keys), self.table, "where %s='%s'" % (
         self.primary_key, getattr(self, self.primary_key)))
     _, res = execute(sql, conn=self.conn, commit=True)
     self._obj.update(dict(zip(self.keys.keys(), res[0])))
Beispiel #32
0
def updatePost(id, title, slug, content, tags, status, publishedDateTime=None, publishedYear=None, publishedMonth=None):
	if len(title) < 3: return (False, "Title must be at least 3 characters", None)
	if len(slug) < 3: return (False, "Slug must be at least 3 characters", None)
	if len(content) < 3: return (False, "Content must be at least 3 characters", None)

	post = getPostById(id=id)
	tags = tags.split(",")

	if post:
		post["title"] = title
		post["slug"] = slug
		post["content"] = content
		post["tags"] = tags
		post["status"] = status
		post["postStatusId"] = getPostStatus(status=status)["id"]
		post["publishedDateTime"] = None if publishedDateTime is None else dthelper.formatDateTime(date=publishedDateTime)
		post["publishedYear"] = None if publishedYear is None else dthelper.getYear(date=publishedYear)
		post["publishedMonth"] = None if publishedMonth is None else dthelper.getMonth(date=publishedMonth)

		sql = """
			UPDATE post SET
				  title=%s
				, slug=%s
				, content=%s
				, publishedDateTime=%s
				, publishedYear=%s
				, publishedMonth=%s
				, postStatusId=%s
			WHERE id=%s
		"""

		parameters = (
			post["title"],
			post["slug"],
			post["content"],
			post["publishedDateTime"],
			post["publishedYear"],
			post["publishedMonth"],
			post["postStatusId"],
			id,
		)

		database.execute(sql=sql, parameters=parameters)
		createUpdatePostTags(postId=id, tags=post["tags"])

	return post
Beispiel #33
0
def createPost(title, author, slug, content, createdDateTime, tags, status, publishedDateTime=None, publishedYear=None, publishedMonth=None):
	if len(title) < 3: return (False, "Title must be at least 3 characters", None)
	if len(slug) < 3: return (False, "Slug must be at least 3 characters", None)
	if len(content) < 3: return (False, "Content must be at least 3 characters", None)

	if isinstance(tags, basestring):
		tags = tags.split(",")

	id = database.execute(sql="""
		INSERT INTO post (
			  title
			, authorId
			, slug
			, content
			, createdDateTime
			, postStatusId
			, publishedDateTime
			, publishedYear
			, publishedMonth
		) VALUES (
			  %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
		)
	""", parameters=(
		  title
		, author["id"]
		, slug
		, content
		, dthelper.formatDateTime(date=createdDateTime)
		, status["id"]
		, None if publishedDateTime is None else dthelper.formatDateTime(date=publishedDateTime)
		, None if publishedYear is None else dthelper.getYear(date=publishedYear)
		, None if publishedMonth is None else dthelper.getMonth(date=publishedMonth)
	))

	createUpdatePostTags(postId=id, tags=tags)

	return newPostBean(
		title            = title,
		authorId         = author["id"],
		slug             = slug,
		content          = content,
		createdDateTime  = dthelper.parseDateTime(date=createdDateTime),
		publishedDateTime= None if publishedDateTime is None else dthelper.parseDateTime(date=publishedDateTime),
		publishedYear    = None if publishedYear is None else dthelper.getYear(date=publishedYear),
		publishedMonth   = None if publishedMonth is None else dthelper.getMonth(date=publishedMonth),
		postStatusId     = status["id"],
		tags             = tags,
	)
Beispiel #34
0
def index(request):
    init.first()
    
    u = ''
    v = ''
    if request.POST.has_key('pretask'):
        u = str(request.POST['pretask'])
        v = str(request.POST['subtask'])

    else:
        return render_to_response('prepage.html')
    
    try:
        database.execute('insert edges (u,v) values(\'%s\',\'%s\')' % (u,v))
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])
        fw = open('error.txt','w')
        fw.write("Mysql Error %d: %s" % (e.args[0], e.args[1]))
        fw.close()
Beispiel #35
0
 def loadfromdb(cls, where='', **kwargs):
     condition = cls.condition(where, **kwargs)
     keys = ["unix_timestamp(%s)" % key if cls.keys[key] == 'from_unixtime(%s)' else key for key in cls.keys.keys()]
     sql = 'select {0} from {1} {2}'.format(
         ','.join(keys), cls.table, condition)
     # sql = 'select %s from %s %s' % (
     #    ','.join(cls.keys), cls.table, condition)
     _, res = execute(
         sql, sql_params=dict(**kwargs).values(), conn=cls.conn, commit=True)
     return [cls(**dict(zip(cls.keys.keys(), r))) for r in res]
Beispiel #36
0
def createPostStatus(status):
	id = database.execute(sql="""
		INSERT INTO poststatus (
			status
		) VALUES (
			%s
		)
	""", parameters=(
		status,
	))

	return newPostStatusBean(id=id, status=status)
def get_data(v_id, user):
    if v_id is None:
        return None
    sql = "SELECT t1.vid, t1.data"\
           + " FROM t_data t1, t_user t2, t_user_data t3"\
           + " WHERE t2.username = %s"\
           + " AND t2.id = t3.userid"\
           + " AND t1.id = t3.dataid"\
           + " AND t1.vid = %s"
    params = (user, str(v_id))
    with execute(sql, params) as dataset:
        return dataset
Beispiel #38
0
 def load_keys(cls):
     if cls.table:
         sql = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name='%s'" % cls.table
         _, res = execute(
             sql=sql, conn=cls.conn, commit=True)
         cls.keys = dict(res)   # {column_name: data_type}
         for key, value in cls.keys.items():
             if value == 'timestamp':
                 cls.keys[key] = "from_unixtime(%s)"
             else:
                 cls.keys[key] = "%s"
         del res
def store_data(req, user):
    req["_id"] = generate_vid()
    req_str = json.dumps(req)
    sql = "START TRANSACTION;"\
        + "INSERT INTO t_data(vid, data) VALUES(%s, %s);"\
        + "SELECT @A:= LAST_INSERT_ID();"\
        + "INSERT INTO t_user_data (userid, dataid) SELECT id, @A "\
        + "FROM t_user WHERE username = %s;"\
        + "COMMIT;"
    params = (req["_id"], req_str, user)
    with execute(sql, params):
        pass
Beispiel #40
0
def update(user):
    if not ('id' in user and ('role' in user or 'is_disabled' in user) ):
        return False

    sql = 'update gambler set '
    if 'role' in user:
        sql += ' role = %(role)s'

    if 'is_disabled' in user:
        sql += ' is_disabled = %(is_disabled)s'

    sql += ' where id = %(id)s ' 
    return db.execute(sql, user)
Beispiel #41
0
def getIds(thisAge, thisSex, thisReligion, thisEthnicity, thisIncome, thisEducation, thisInterest):
	personIds = """SELECT personId FROM description
	WHERE age = '%s'
	AND sex = '%s'
	AND religion = '%s'
	AND ethnicity = '%s'
	AND income = '%s'
	AND education = '%s'
	AND interest = '%s'""" % (thisAge, thisSex, thisReligion, thisEthnicity, thisIncome, thisEducation, thisInterest)
	cursor = database.execute(personIds)
	rows = cursor.fetchall()
	data = []
	for row in rows:
		data.append(int(row[0]))
	return data
Beispiel #42
0
def login(username, password):
	sha1.update(password)
	sql = """SELECT * FROM person WHERE username = '******'""" % (username)
	cursor = database.execute(sql)
	print cursor.rowcount
	if cursor.rowcount == 1:
		data= cursor.fetchone()
		user= {}
		if sha1.hexdigest() == str(data[2]):
			user['id']=(data[0])
			user['username']=(data[1])
			user['fname']=(data[3])
			user['lname']=(data[4])
			user['status']=(data[5])
			print user
			return user
	return None
def _store_measurements(place_id, resp):
    """Stores the measurement values in the database."""
    i = 0
    j = 0
    for item in resp['list']:
        m = {}
        dt = datetime.datetime.utcfromtimestamp(int(item['dt']))
        if 'main' in item:
            if 'temp' in item['main']: 
                m[MT_TEMP] = item['main']['temp']
            if 'temp_min' in item['main']: 
                m[MT_TEMP_MIN] = item['main']['temp_min']
            if 'temp_max' in item['main']: 
                m[MT_TEMP_MAX] = item['main']['temp_max']
            if 'pressure' in item['main']: 
                m[MT_PRESS] = item['main']['pressure']
            if 'sea_level' in item['main']: 
                m[MT_PRESS_SEALEV] = item['main']['sea_level']
            if 'grnd_level' in item['main']: 
                m[MT_PRESS_GRNDLEV] = item['main']['grnd_level']
            if 'humidity' in item['main']: 
                m[MT_HUMID] = item['main']['humidity']
        if 'wind' in item:    
            if 'speed' in item['wind']: 
                m[MT_WIND_SPEED] = item['wind']['speed']
            if 'deg' in item['wind']: 
                m[MT_WIND_DEG] = item['wind']['deg']
        if 'rain' in item:
            if '3h' in item['rain']: 
                m[MT_RAIN_3H] = item['rain']['3h']
        for key in m:
            row = database.query_row('SELECT COUNT(*) FROM Measurement WHERE Time = ? AND Place = ? AND Type = ?', (dt, place_id, key))
            if row[0] == 0:
                (rowcount, lastid) = database.execute('INSERT INTO Measurement (Time, Place, Type, Value) VALUES (?,?,?,?)', (dt, place_id, key, m[key]))
                i = i + 1
            else:
                j = j + 1
    database.commit()    
    app.logger.info('%s measurements inserted for %s' % (i, place_id))
    if j > 0:
        app.logger.info('%s measurements skipped for %s' % (j, place_id))
Beispiel #44
0
def createUser(email, password, firstName, lastName):
    hashedPassword = securityservice.hash(value=password)

    id = database.execute(
        sql="""
		INSERT INTO user (
			  email
			, password
			, firstName
			, lastName
		) VALUES (
			  %s
			, %s
			, %s
			, %s
		)
	""",
        parameters=(email, hashedPassword, firstName, lastName),
    )

    return newUserBean(id=id, email=email, password=hashedPassword, firstName=firstName, lastName=lastName)
Beispiel #45
0
def deleteAllPosts():
	database.execute(sql="DELETE FROM post_posttag")
	database.execute(sql="DELETE FROM posttag")
	database.execute(sql="DELETE FROM post")