コード例 #1
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def deletarScript(codProj):
    cursor = conn.cursor()
    cursor.execute(
        "SELECT Tab_Cod FROM bancoprojeto2020.tabela WHERE Proj_Cod=%s",
        (codProj))
    results = cursor.fetchall()
    cursor.close()

    for tabelaCod in results:
        cursor = conn.cursor()
        cursor.execute(
            "DELETE FROM bancoprojeto2020.atributo WHERE Tab_Cod = %s",
            (tabelaCod))
        conn.commit()
        cursor.close()

    cursor = conn.cursor()
    linhasAfetadas = cursor.execute(
        "DELETE FROM bancoprojeto2020.tabela WHERE Proj_Cod = %s", (codProj))
    conn.commit()
    cursor.close()

    operacao = True
    if linhasAfetadas == 0:
        operacao = False

    return jsonify(operacao=operacao)
コード例 #2
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def cadPergunta():
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM bancoprojeto2020.fatorajusteperguntas")
    results = cursor.fetchall()
    cursor.close()
    lista = []

    #pega o codigo do tipo de contagem do banco e adiciona na lista o tipo de contagem daquele codigo
    for row in results:
        cod = row[2]
        cursor = conn.cursor()
        cursor.execute(
            "SELECT * FROM bancoprojeto2020.tipocontagem WHERE TC_Cod=%s",
            (cod))
        results2 = cursor.fetchone()
        cursor.close()
        tc_descricao = results2[1]

        lista.append(tc_descricao)

    #pega os tipos de contagem para utilizar na hora de alterar
    select = "SELECT * FROM bancoprojeto2020.tipocontagem"
    cursor = conn.cursor()
    cursor.execute(select)
    results3 = cursor.fetchall()
    cursor.close()

    tam = len(lista)

    return render_template('cadPergunta.html',
                           results=results,
                           results3=results3,
                           lista=lista,
                           tam=tam)
コード例 #3
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def adicionaContagem():
    req = request.get_json()
    contCod = req['contCod']
    fCod = req['fCod']
    pCod = req['pCod']
    tpCod = req['tpCod']
    desc = req['desc']
    td = req['td']
    tr = req['tr']
    complexidade = req['complexidade']
    pf = req['pf']

    cursor = conn.cursor()
    if contCod == '0':
        cursor.execute(
            "INSERT INTO bancoprojeto2020.contagem (Fun_Cod,TP_Cod,Proj_Cod,Cont_Descricao,Cont_TD,Cont_TR,Cont_Complexidade,Cont_Contribuicao) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
            (fCod, tpCod, pCod, desc, td, tr, complexidade, pf))
        conn.commit()
        cursor.close()
    else:
        cursor.execute(
            "UPDATE bancoprojeto2020.contagem SET TP_Cod=%s,Cont_Descricao=%s, Cont_TD=%s, Cont_TR=%s, Cont_Complexidade=%s, Cont_Contribuicao=%s WHERE Cont_Cod=%s",
            (tpCod, desc, td, tr, complexidade, pf, contCod))
        conn.commit()
        cursor.close

    cursor = conn.cursor()
    cursor.execute(
        "SELECT MAX(Cont_Cod) FROM bancoprojeto2020.contagem WHERE Proj_Cod=%s",
        (pCod))
    cod = cursor.fetchall()[0]
    cursor.close()

    return jsonify(cod=cod)
コード例 #4
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def calcFatorAjuste():
    if session.get("USERNAME", None) is not None:
        cursor = conn.cursor()
        if session.get('USERNAME') == '*****@*****.**' or session.get(
                'USERNAME') == '*****@*****.**':
            select = "SELECT * FROM bancoprojeto2020.projeto"
        else:
            select = "SELECT * FROM bancoprojeto2020.projeto WHERE Emp_Cod=" + str(
                session.get('ID'))

        cursor.execute(select)
        results = cursor.fetchall()
        cursor.close()

        cursor = conn.cursor()
        select2 = "SELECT * FROM bancoprojeto2020.fatorajusteperguntas"
        cursor.execute(select2)
        results2 = cursor.fetchall()
        cursor.close()

        return render_template('cadFatorAjuste.html',
                               results=results,
                               results2=results2)
    else:
        return redirect(url_for("login.sign_in"))
コード例 #5
0
def salvaEstimativa():
    req = request.get_json()
    codProj = req['codProj']
    modelo = req['modelo']
    modo = req['modo']

    loc = req['loc']
    kloc = req['kloc']
    esforco = req['esforco']
    prazo = req['prazo']
    produtividade = req['produtividade']
    tam = req['tam']

    cursor = conn.cursor()
    cursor.execute(
        "DELETE FROM bancoprojeto2020.estimativa WHERE Proj_Cod = %s",
        (codProj))
    conn.commit()
    cursor.close()

    cursor = conn.cursor()
    cursor.execute(
        "INSERT INTO bancoprojeto2020.estimativa(Est_Modelo,Est_Modo,Est_Loc,Est_Kloc,Est_Esforco,Est_Prazo,Est_Produtividade,Est_TamEquipe,Proj_Cod) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
        (modelo, modo, loc, kloc, esforco, prazo, produtividade, tam, codProj))
    conn.commit()
    cursor.close()

    operacao = True

    return jsonify(operacao=operacao)
コード例 #6
0
def getContagemDado(codProj):
    cursor = conn.cursor()
    cursor.execute(
        "SELECT f.Fun_Cod,Fun_Nome,Cont_Descricao,Fun_Caminho,TP_Descricao,Cont_TD,Cont_TR,Cont_Complexidade,Cont_Contribuicao FROM bancoprojeto2020.funcao as f INNER JOIN bancoprojeto2020.contagem as c ON f.Fun_Cod = c.Fun_Cod and c.Proj_Cod = %s and f.Fun_Tipo = 'M' INNER JOIN bancoprojeto2020.tipo as p ON p.TP_Cod = c.TP_Cod",
        (codProj))
    results = cursor.fetchall()
    cursor.close()

    operacaoScript = False
    operacao = True

    if results == ():
        cursor = conn.cursor()
        cursor.execute(
            "SELECT f.Fun_Cod,Fun_Nome,Cont_Descricao,Fun_Caminho,TP_Descricao,Cont_TD,Cont_TR,Cont_Complexidade,Cont_Contribuicao FROM bancoprojeto2020.funcao as f INNER JOIN bancoprojeto2020.contagem as c ON f.Fun_Cod = c.Fun_Cod and c.Proj_Cod = %s and f.Fun_Tipo = 'S' INNER JOIN bancoprojeto2020.tipo as p ON p.TP_Cod = c.TP_Cod",
            (codProj))
        results = cursor.fetchall()
        cursor.close()
        operacaoScript = True

    if results == ():
        operacao = False

    return jsonify(operacaoScript=operacaoScript,
                   operacao=operacao,
                   results=results)
コード例 #7
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def adicionaAtributo(codProj, lista):
    sql = "INSERT INTO bancoprojeto2020.atributo (AT_Descricao,Tab_Cod,Proj_Cod) VALUES "
    sql2 = ""
    tam = len(lista)
    i = 1
    while i < tam:
        j = 0
        tam2 = len(lista[i])
        sql2 = "SELECT Tab_Cod FROM bancoprojeto2020.tabela WHERE Tab_Nome = '" + lista[
            i - 1] + "' AND Proj_Cod = " + codProj

        cursor = conn.cursor()
        cursor.execute(sql2)
        res = cursor.fetchone()
        cursor.close()
        Tab_Cod = res[0]

        while j < tam2:
            sql += "(" + "'" + lista[i][j] + "'" + "," + str(
                Tab_Cod) + "," + str(codProj) + "),"
            j = j + 1

        i = i + 2

    result = sql.rstrip(',')
    cursor = conn.cursor()
    linhasAfetadas = cursor.execute(result)
    conn.commit()
    cursor.close()

    operacao = False
    if linhasAfetadas > 0:
        operacao = True

    return operacao
コード例 #8
0
def login():
    if request.method == 'POST':
        if request.form['type'] == 'signin':
            # Query Database
            cur = conn.cursor()
            cur.execute("select email, username, password from accounts where email=%s", [request.form['email']])
            data = cur.fetchone()
            # Fail conditions [no user by that email or password does not match]
            if data == None: return '', 298
            if not bcrypt.verify(request.form['pass'], data[2]): return '', 299
            # If good go to home page
            login_user(User(data[0], data[1]), remember=True, duration=timedelta(days=1))
            return redirect(url_for('home'), 303)

        elif request.form['type'] == 'signup':
            try:
                albums = json.dumps([{ 'album_name': "My Gallery", 'images': [] }])
                #Query Database
                cur = conn.cursor()
                # Attempt to add new user and login
                password = bcrypt.hash(request.form['pass'])
                cur.execute("insert into accounts (email, username, password, albums) values (%s, %s, %s, %s)",
                            [request.form['email'], request.form['user'], password, albums])
                conn.commit()
                login_user(User(request.form['email'], request.form['user']), remember=True, duration=timedelta(days=1))
                return redirect(url_for('home'), 303)
            except psycopg2.IntegrityError:
                cur.execute('ROLLBACK')
                return '', 299

    if current_user.is_authenticated:
        return redirect(url_for('home'))
    else:
        return render_template('login.html')
コード例 #9
0
def add_curr():
    with conn.cursor() as cursor:
        cursor.execute('select * from subject;')
        subjects = [{'id': x[0], 'title': x[1]} for x in cursor.fetchall()]
    with conn.cursor() as cursor:
        cursor.execute('select * from "group";')
        groups = [{'id': x[0], 'title': x[1]} for x in cursor.fetchall()]
    if request.method == 'POST' and is_admin:
        try:
            if request.form["stop"] == 'true':
                return render_template('add_curr.html', is_admin=is_admin)
            with conn.cursor() as cursor:
                cursor.execute(f'INSERT INTO curriculum (subject_id, group_id)\
                    VALUES ({int(request.form.get("subject_id"))}, {int(request.form.get("group_id"))});'
                               )
                cursor.execute(f'select subject_id, group_id from curriculum \
                    where subject_id={int(request.form.get("subject_id"))}, group_id = {int(request.form.get("group_id"))};'
                               )
                x = cursor.fetchall()
                flash(
                    f'Добавлена связь, номер предмета: {x[0][1]}, номер группы: {x[0][2]}'
                )
            conn.commit()
        except:
            flash('Что-то пошло не так, обратитесь к разработчику')
    return render_template('add_curr.html',
                           subjects=subjects,
                           groups=groups,
                           is_admin=is_admin)
コード例 #10
0
def add_mark():
    with conn.cursor() as cursor:
        cursor.execute('select id, name from student;')
        students = [{'id': x[0], 'name': x[1]} for x in cursor.fetchall()]
        cursor.execute('select * from task;')
        tasks = [{'id': x[0]} for x in cursor.fetchall()]
    if request.method == 'POST' and is_admin:
        if request.form["stop"] == 'true':
            return render_template('add_mark.html', is_admin=is_admin)
        with conn.cursor() as cursor:
            cursor.execute(f'INSERT INTO mark (student_id, task_id, mark)\
                VALUES (\'{int(request.form["student_id"])}\', {int(request.form["task_id"])},\
                {request.form["mark"]});')
            cursor.execute('select mark.id, mark, name\
                 from (select max(id) as maxid from mark) as foo\
                    join mark on maxid=mark.id join student on mark.student_id = student.id;'
                           )
            try:
                x = cursor.fetchall()
                flash(f'Добавлена оценка: id: {x[0][0]}, оценка: {x[0][1]},\
                имя: {x[0][2]}')
            except:
                flash('Что-то пошло не так, обратитесь к разработчику')
        conn.commit()
    return render_template('add_mark.html',
                           students=students,
                           tasks=tasks,
                           is_admin=is_admin)
コード例 #11
0
def add_student():
    with conn.cursor() as cursor:
        cursor.execute('select * from "group";')
        groups = [{'id': x[0], 'chair': x[1]} for x in cursor.fetchall()]
    if request.method == 'POST' and is_admin:
        if request.form["stop"] == 'true':
            print('stop')
            return render_template('add_student.html', is_admin=is_admin)
        with conn.cursor() as cursor:
            cursor.execute(
                f'INSERT INTO student (group_id, name, birth, admission)\
                VALUES ({int(request.form.get("group_id"))},\'{request.form["name"]}\',\
                \'{request.form["bith"]}\', \'{request.form["admission"]}\');')
            cursor.execute('select id, group_id, name, birth, admission from\
                 (select max(id) as maxid from student) as foo\
                 join student on id = maxid;')
            try:
                x = cursor.fetchall()
                print(x)
                flash(
                    f'Добавлен студент, id: {x[0][0]}, номер группы: {x[0][1]},\
                ФИО: {x[0][2]}, дата рождения: {x[0][3]}, \
                дата поступления: {x[0][0]}')
            except:
                flash('Что-то пошло не так, обратитесь к разработчику')
        conn.commit()
    return render_template('add_student.html',
                           groups=groups,
                           is_admin=is_admin)
コード例 #12
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def cadFuncao():
    if session.get("USERNAME", None) is not None:
        cursor = conn.cursor()
        if session.get('USERNAME') == '*****@*****.**' or session.get(
                'USERNAME') == '*****@*****.**':
            select = "SELECT * FROM bancoprojeto2020.projeto"
        else:
            select = "SELECT * FROM bancoprojeto2020.projeto where emp_cod = " + str(
                session.get('ID'))

        cursor.execute(select)
        results3 = cursor.fetchall()
        cursor.close()

        codProj = 0
        if results3 != ():
            codProj = results3[0][0]

        cursor = conn.cursor()
        cursor.execute(
            "SELECT * FROM bancoprojeto2020.funcao as f INNER JOIN bancoprojeto2020.projeto as p ON f.proj_cod = p.proj_cod and p.proj_cod=%s",
            (str(codProj)))
        results = cursor.fetchall()
        cursor.close()

        tam = len(results)
        return render_template('cadFuncao.html',
                               results=results,
                               results3=results3,
                               tam=tam)
    else:
        return redirect(url_for("login.sign_in"))
コード例 #13
0
def obtemContagemTipoDado(codProj):
    cursor = conn.cursor()
    cursor.execute(
        "SELECT Cont_Descricao,TP_Descricao,Cont_TD,Cont_TR,Cont_Complexidade,Cont_Contribuicao,c.Fun_Cod FROM bancoprojeto2020.contagem AS c INNER JOIN bancoprojeto2020.funcao AS f ON c.Fun_Cod = f.Fun_Cod and c.Proj_Cod = %s and f.Fun_Tipo = 'M' INNER JOIN bancoprojeto2020.tipo AS t ON c.TP_Cod = t.TP_Cod",
        (codProj))
    results = cursor.fetchall()
    cursor.close()

    operacaoModelo = True
    operacaoScript = False

    cursor = conn.cursor()
    if results == ():
        operacaoModelo = False
        cursor.execute(
            "SELECT Cont_Descricao,TP_Descricao,Cont_TD,Cont_TR,Cont_Complexidade,Cont_Contribuicao,c.Fun_Cod FROM bancoprojeto2020.contagem AS c INNER JOIN bancoprojeto2020.funcao AS f ON c.Fun_Cod = f.Fun_Cod and c.Proj_Cod = %s and f.Fun_Tipo = 'S' INNER JOIN bancoprojeto2020.tipo AS t ON c.TP_Cod = t.TP_Cod",
            (codProj))
        results = cursor.fetchall()
        cursor.close()

        if results != ():
            operacaoScript = True

    return jsonify(operacaoModelo=operacaoModelo,
                   operacaoScript=operacaoScript,
                   dados=results)
コード例 #14
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def adicionaPrimaryAndForeign(codProj, lista, listaPrimary, listareferencia):
    tam = len(listareferencia)
    i = 0
    while i < tam:
        j = 0
        tam2 = len(listareferencia[i])
        if tam2 > 0:
            #pega o codigo da tabela onde está o atributo
            cursor = conn.cursor()
            sql = "SELECT Tab_Cod FROM bancoprojeto2020.tabela WHERE Tab_Nome = '" + listareferencia[
                i][j] + "' AND Proj_Cod = " + str(codProj)
            cursor.execute(sql)
            res = cursor.fetchone()
            cursor.close()
            tab_cod2 = res[0]

            while j + 1 < tam2:
                #adiciona o atributo como foreign key
                cursor = conn.cursor()
                sql = "UPDATE bancoprojeto2020.atributo set AT_Foreign = True WHERE Tab_Cod = " + str(
                    tab_cod2) + " AND AT_Descricao = '" + listareferencia[i][
                        j + 1] + "' AND Proj_Cod = " + str(codProj)
                cursor.execute(sql)
                conn.commit()
                cursor.close()

                j = j + 1

        i = i + 1

    #gera chave primaria de cada tabela
    i = 0
    results = getCodTabela(codProj)
    tam = len(results)
    while i < tam:
        j = 0
        tam2 = len(listaPrimary[i])
        while j < tam2:
            cursor = conn.cursor()
            sql = "UPDATE bancoprojeto2020.atributo set AT_Primary = True WHERE Tab_Cod = " + str(
                results[i][0]) + " AND AT_Descricao = '" + listaPrimary[i][
                    j] + "' AND Proj_Cod = " + str(codProj)
            cursor.execute(sql)
            conn.commit()
            cursor.close()

            j = j + 1

        i = i + 1

    operacao = True

    return operacao
コード例 #15
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def cadProjeto():
    if session.get("USERNAME", None) is not None:
        cursor = conn.cursor()
        if session.get('USERNAME') == '*****@*****.**' or session.get(
                'USERNAME') == '*****@*****.**':
            cursor.execute("SELECT * FROM bancoprojeto2020.projeto")
        else:
            cursor.execute(
                "SELECT * FROM bancoprojeto2020.projeto WHERE Emp_Cod=%s",
                (session.get('ID')))

        results = cursor.fetchall()
        cursor.close()

        lista = []

        #pega o codigo do tipo de contagem do banco e adiciona na lista o tipo de contagem daquele codigo
        for row in results:
            cod = row[1]
            cursor = conn.cursor()
            cursor.execute(
                "SELECT * FROM bancoprojeto2020.tipocontagem WHERE TC_Cod=%s",
                (cod))
            results2 = cursor.fetchone()
            cursor.close()

            tc_descricao = results2[1]
            lista.append(tc_descricao)

        #pega os tipos de contagem para utilizar na hora de alterar
        cursor = conn.cursor()
        select = "SELECT * FROM bancoprojeto2020.tipocontagem"
        cursor.execute(select)
        results4 = cursor.fetchall()
        cursor.close()

        #pega as linguagens para utilizar na hora de alterar
        cursor = conn.cursor()
        select = "SELECT * FROM bancoprojeto2020.linguagem"
        cursor.execute(select)
        results6 = cursor.fetchall()
        cursor.close()

        tam = len(lista)

        return render_template('cadProjeto.html',
                               results=results,
                               results4=results4,
                               results6=results6,
                               lista=lista,
                               tam=tam)
    else:
        return redirect(url_for("login.sign_in"))
コード例 #16
0
def postAuth():
    username = session['username']
    filepath = request.form['filepath']
    Followers = request.form['allFollowers']
    Tag = request.form['tag']
    time = datetime.now()
    if Followers == 'accept':
        allFollowers = 1
    else:
        allFollowers = 0
    caption = request.form['caption']
    cursor = conn.cursor()
    cursor.execute('INSERT INTO Photo (postingDate, filepath, allFollowers, caption, photoPoster) VALUES(%s,%s,%s,%s,%s)',
                   (time, filepath, allFollowers, caption, username))
    cursor.execute('SELECT photoID FROM Photo WHERE photoID = (SELECT MAX(photoID) FROM Photo)')
    data = cursor.fetchone()
    photoID = data.get('photoID')
    cursor.execute('SELECT groupName, owner_username FROM BelongTo WHERE member_username = %s', (username))
    data = cursor.fetchall()
    for line in data:
        groupName = line.get('groupName')
        owner = line.get('owner_username')
        if request.form[groupName] == 'accept':
            cursor.execute('INSERT INTO SharedWith VALUES(%s,%s,%s)', (owner, groupName, photoID))
    if len(Tag) != 0:
        cursor.execute('SELECT * FROM Person WHERE username = %s', (Tag))
        user = cursor.fetchone()
        if not (user):
            error = 'This user doesn\'t exist.'
            return render_template('post.html', data = data, error = error)
        cursor.execute('INSERT INTO Tagged VALUES(%s,%s,%s)', (Tag, photoID, 0))
    conn.commit()
    cursor.close()
    return render_template('home.html')
コード例 #17
0
def notificationsAuth():
    username = session['username']
    cursor = conn.cursor()
    cursor.execute('SELECT username_follower FROM Follow WHERE username_followed = %s AND followstatus = 0', (username))
    data = cursor.fetchall()
    for line in data:
        follower = line.get('username_follower')
        if request.form[follower] == 'accept':
            cursor.execute('UPDATE Follow SET followstatus = 1 WHERE username_followed = %s AND username_follower = %s',
                           (username, follower))  
        elif request.form[follower] == 'deny':
            cursor.execute('DELETE FROM Follow WHERE username_followed = %s AND username_follower = %s',
                           (username, follower))
        else:
            pass
    cursor.execute('SELECT photoID FROM Tagged WHERE username = %s AND tagstatus = 0', (username))
    data = cursor.fetchall()
    for line in data:
        photoID = line.get('photoID')
        if request.form[str(photoID)] == 'accept':
            cursor.execute('UPDATE Tagged SET tagstatus = 1 WHERE username = %s AND photoID = %s',
                           (username, photoID))
        elif request.form[str(photoID)] == 'deny':
            cursor.execute('DELETE FROM Tagged WHERE username = %s AND photoID = %s',
                           (username, photoID))
        else:
            pass
    conn.commit()
    cursor.close()
    return render_template('home.html', username = session['username'])
コード例 #18
0
def people():
    cursor = conn.cursor()
    query = 'SELECT username, firstName, lastName from person'
    cursor.execute(query)
    data = cursor.fetchall()
    cursor.close()
    return render_template('show_people.html', data = data)
コード例 #19
0
def getSubmission(sub_id):
    cursor = conn.cursor()
    sql = "select * from submissions where id = '%s'" % (sub_id)
    cursor.execute(sql)
    data = cursor.fetchone()
    cursor.close()
    return data
コード例 #20
0
def registerAuth():
    #form request
    username = request.form['username']
    password = request.form['password']
    firstName = request.form['First Name']
    lastName = request.form['Last Name']
    bio = request.form['Bio']

    #hashing password
    hashword = hashlib.sha256(password.encode())
    newpassword = (hashword.hexdigest())
    
    cursor = conn.cursor()
    query = 'SELECT * FROM person WHERE username = %s'
    cursor.execute(query, (username))
    data = cursor.fetchone()
    error = None
    if(data):
        error = "This user already exists"
        return render_template('register.html', error = error)
    else:
        ins = 'INSERT INTO person VALUES(%s, %s, %s, %s, %s)'
        cursor.execute(ins, (username, newpassword, firstName, lastName, bio))
        conn.commit()
        cursor.close()
        return render_template('index.html')
コード例 #21
0
def browsegroup():
    cursor = conn.cursor()
    query = 'SELECT groupName, groupOwner from Friendgroup'
    cursor.execute(query)
    data = cursor.fetchall()
    cursor.close()
    return render_template('show_friendgroups.html', data = data)
コード例 #22
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def obtemTodasContagem():
    req = request.get_json()

    codProj = req['codProj']
    tableJa = req['tableJa']

    auxTab = "Tab_Cod = " + str(tableJa[0])
    i = 1
    tam = len(tableJa)
    while i < tam:
        auxTab += " or Tab_Cod = " + str(tableJa[i])
        i = i + 1

    cursor = conn.cursor()
    sql = "SELECT AT_Descricao,AT_Primary,AT_Foreign,Tab_Cod FROM bancoprojeto2020.atributo WHERE Proj_Cod = " + str(
        codProj) + " AND " + auxTab
    cursor.execute(sql)
    results = cursor.fetchall()
    cursor.close()

    operacao = True

    if results == ():
        operacao = False

    return jsonify(operacao=operacao, results=results)
コード例 #23
0
def getSubmissionlist(name):
    cursor = conn.cursor()
    sql = "select * from submissions where author = '%s'" % (name)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    return data
コード例 #24
0
def getALlGrades():
    if "loggedIN" in session:
        if (session['loggedIN']):
            cursor = conn.cursor()
            cursor.execute(
                "SELECT gradelevel, quarter, english, math, science, filipino, aralPan, mapeh FROM grades WHERE user_id = %s",
                (session['uID']))
            rows = cursor.fetchall()
            ret = {}
            for row in rows:
                if not "grade" + row[0] in ret:
                    ret["grade" + row[0]] = []
                ret["grade" + row[0]].append(
                    [row[2], row[3], row[4], row[5], row[6], row[7]])
            nR = len(ret)
            nRR = len(ret[-1])
            for i in range(nRR):
                ret[-1].append([None, None, None, None, None, None])
            for i in range(nR, 11):
                ret["grade" + i] = []
                for j in range(4):
                    ret["grade" + i].append(
                        [None, None, None, None, None, None])

            return js.dumps(ret)
    return redirect(url_for('index'))
コード例 #25
0
def galleries():
    cur = conn.cursor()
    if request.method == 'POST':
        if request.form['type'] == 'name':
            data = get_galleries(cur)
            for i in data:
                if i['album_name'] == request.form['old']:
                    i['album_name'] = request.form['new']
            update_galleries(cur, data)
            return 'update'
        elif request.form['type'] == 'add':
            data = get_galleries(cur)
            data.append({ 'album_name' : request.form['name'], 'images': [] })
            update_galleries(cur, data)
            return 'add'
        elif request.form['type'] == 'remove':
            data = get_galleries(cur)
            for i in data:
                if i['album_name'] == request.form['name']:
                    data.remove(i)
                    break
            update_galleries(cur, data)
            return 'delete'
        elif request.form['type'] == 'addimg':
            data = get_galleries(cur)
            for i in data:
                if i['album_name'] == request.form['name']:
                    i['images'].append(request.form['img'])
                    break
            update_galleries(cur, data)
            return 'addimg'
    data = get_galleries(cur)
    return json.dumps(data)
コード例 #26
0
ファイル: views.py プロジェクト: gustavobega/sistemaprojeto
def alterarproj():
    if request.method == "POST":
        id = request.form['id']
        nome = request.form['nome']
        gerente = request.form['gerente']
        descricao = request.form['descricao']
        cod = request.form.get('tc')
        tempocontagem = request.form['tempocontagem']
        temporeal = request.form['temporeal']
        datainicio = request.form['datainicio']
        dataprevista = request.form['dataprevista']
        fct = request.form['fct']
        lingcod = request.form.get('ling')
        escopo = request.form.get('escopo')

        cursor = conn.cursor()
        cursor.execute(
            "UPDATE bancoprojeto2020.projeto SET TC_Cod=%s,Proj_Nome=%s,Proj_Descricao=%s,Proj_TempoContagem=%s,Proj_TempoReal=%s,Proj_Gerente=%s,Proj_DataInicio=%s,Proj_DataP=%s,Proj_FCT=%s, Ling_Cod=%s, Proj_Escopo=%s WHERE Proj_Cod=%s",
            (cod, nome, descricao, tempocontagem, temporeal, gerente,
             datainicio, dataprevista, fct, lingcod, escopo, id))
        conn.commit()
        cursor.close()

        flash("Alterado com Sucesso!")

        return redirect(url_for('projeto.cadProjeto'))
コード例 #27
0
def login():
    cursor = conn.cursor()
    uname = request.json["username"]
    password = request.json["pass"]
    cursor.execute(
        "SELECT user_id, username, password, gradeLevel, trackEquipped, carrerChosen, programChosen, email FROM users WHERE username = '******' AND password = '******'"
        % (uname, password))
    row = cursor.fetchone()
    if (row):
        session['loggedIN'] = True
        #user ID
        session['uID'] = row[0]
        #gradelevel
        session['gL'] = int(row[3])
        ret = {
            'success': True,
            'User': {
                'id': str(row[0]),
                'username': str(row[1]),
                'password': str(row[2]),
                'gradeLevel': str(row[3]),
                'equippedTrack': str(row[4]),
                'chosenCareer': str(row[5]),
                'chosenProgram': str(row[6]),
                'email': str(row[7])
            }
        }
    else:
        ret = {'success': False}
    #if success is true just use ret['User'] to get the user infos
    return js.dumps(ret)
コード例 #28
0
def joingroupAuth():
    username = session['username']
    group = request.form['Friend Group']
    groupleader = request.form['Group Creator']
    cursor = conn.cursor()
    query = 'SELECT * FROM Friendgroup WHERE groupName = %s AND groupOwner = %s'
    cursor.execute(query, (group, groupleader))
    data = cursor.fetchone()
    error = None
    if (data):
        cursor.execute(
            'SELECT * FROM BelongTo WHERE member_username = %s AND owner_username = %s AND groupName = %s',
            (username, groupleader, group))
        data = cursor.fetchone()
        if (data):
            error = 'You already belong to this group.'
            return render_template('joingroup.html', error=error)
        else:
            cursor.execute('INSERT INTO BelongTo VALUES(%s,%s,%s)',
                           (username, groupleader, group))
            conn.commit()
            cursor.close()
            return render_template('home.html', username=session['username'])
    else:
        error = 'Incorrect Group Name and/or Group Creator'
        return render_template('joingroup.html', error=error)
コード例 #29
0
    def post(self):
        try:
            """
            Synchronous Key Auth
            """
            # Parse the arguments
            parser = reqparse.RequestParser()
            parser.add_argument('username', type=str, help='username for authentication')
            parser.add_argument('password', type=str, help='Password for authentication')
            parser.add_argument('encoded', type=str, help='encoded payload')
            args = parser.parse_args()

            _username = args['username']
            _password = args['password']
            __encoded = args['encoded']
            _hashed_password = generate_password_hash(_password)

            conn = mysql.connect()
            cursor = conn.cursor()
            data = cursor.callproc('sp_AuthenticateUser', (_username, _hashed_password))
            secret = data[0]

            result = jwt.decode(_encoded,  secret, algorithm='HS512')

            if(_username == result.username):
                return {'status' : 200, 'message' : 'authenticated'}
            else:
                return {'status' : 100, 'message' : 'rejected'}
        except Exception as e:
            return {'error': str(e)}
コード例 #30
0
def list_threads():	
	tosend = {}	
	try:
		user_email = request.args.get('user')	
		if user_email is None:
			forum_short = request.args.get('forum')
			user_email = ''
			if forum_short is None:
				tosend['code'] = 2
				tosend['response'] = "forum short name or user email is required"
				return jsonify(**tosend)
		else:
			forum_short = ''		
		
		since = request.args.get('since')
		limit = request.args.get('limit')
		order = request.args.get('order')	
		
		resp = []
		#conn =mysql.connect()
		cursor = conn.cursor()
		
		if getThreadsResp(resp, cursor, forum_short, user_email) == False:
			tosend['code'] = 2
			tosend['response'] = "forum or user do not exist"
			return jsonify(**tosend)
		tosend['code'] = 0
		tosend['response'] = resp
	except:
		tosend['code'] = 4
		tosend['response'] = 'unknown error'
	cursor.close()	
	return jsonify(**tosend)