Example #1
0
def new_password_t():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    sql = "SELECT password from staff where id=%s"
    id = L['id']
    password = L['old_passwd']
    new_password = L['new_passwd']
    cursor.execute(sql, id)
    ((results, ), ) = cursor.fetchall()
    if check_password_hash(results, password):
        new_password = generate_password_hash(new_password)
        sql = "UPDATE staff set password=%s WHERE id = %s "
        cursor.execute(sql, (new_password, id))
        db.commit()
        db.close()
        return '200'
    else:
        return '300'
Example #2
0
def login():
    """Render website's home page."""
    # print("This is the session in login:"******"logged_in"])
    if 'logged_in' in session:
        return redirect(url_for('home'))

    loginform = LoginForm()

    if request.method == "POST" and loginform.validate_on_submit():
        username = loginform.username.data
        password = loginform.password.data
        db, cur = DB_Conn()
        q = 'select * from users_ where uname="{}" and passcode="{}";'
        q = q.format(username, password)
        cur.execute(q)
        r = cur.fetchall()
        cur.close
        print("this:", r)
        db.close()
        if r == []:
            flash("Incorrect username or password", "danger")
            redirect("login.html")
        else:
            session['logged_in'] = True
            session['user_id'] = r[0][0]
            flash('You were logged in')
            print("This is the session before home:", session["logged_in"])
            return redirect(url_for('home'))
    flash_errors(loginform)
    return render_template('login.html', loginform=loginform)
Example #3
0
def select_achievement():
    db = pymysql.connect("127.0.0.1", "root", "638436", "adms")
    cursor = db.cursor()
    # username = "******"
    # r_mname = "ADNI_002_S_0295_MR_HarP_135_final_release_2015_Br_20150226095012465_S13408_I474728.nii"
    # mri = "select * from mri where m_name='" + r_mname + "'"
    # 方法一:
    # select Score, (select count(distinct Score) from Scores where Score>=s.Score) as Rank from Scores as s order by Score desc;
    # rank = "select ea_eid, ea_score, (select count(distinct ea_score) from eachievement where ea_score >= s.ea_score) " \
    #        "as Rank from eachievement as s order by ea_score desc"
    username = "******"
    resu = "select * from resu where r_uid='" + username + "'"
    cursor.execute(resu)
    rhipvlou_r = cursor.fetchall()
    print(rhipvlou_r)
    data = []
    for i in rhipvlou_r:
        x_data = "海马体数量" + "-" + i[4].strftime('%Y.%m.%d')
        y_data = int(i[6])
        print(x_data)
        print(y_data)
        data_dict = {"name":x_data,"num":y_data}
        data.append(data_dict)
    print(data)
    # r_uid = mri_r[0][1]
    # r_utime = mri_r[0][3]
    # print(mri_r)
    # print(r_uid)
    # print(r_utime)
    db.commit()
    db.close()
Example #4
0
def Movie(title):
    """Render website's home page."""
    if 'logged_in' in session:
        s = request.args.get('feedback')
        print("here2:", s)
        db, cur = DB_Conn()
        if s != None:
            #print "t: %s || s: %s" % (title, s)
            r = RekoCommander.RunCommand('5', session['user_id'], title,
                                         int(s) * 2)
            print "RekoAPI response:", r
            pass
        q = "SELECT * FROM {} WHERE tconst_='{}';"
        q = q.format("titles", title)
        cur.execute(q)
        res = cur.fetchall()
        #print("query result: %s" % res) # here is the error now
        img = GetTitleImage(title.strip())
        db.close()
        return render_template('movie.html',
                               themovie=res[0],
                               imgurl=img,
                               title=title)
    else:
        flash("Please log in first", "danger")
        return redirect(url_for("login"))
Example #5
0
def heaven_for_users():
    try:
        db = pymysql.connect(host="rm-uf6gw23j409s5ui7qmoo.mysql.rds.aliyuncs.com", port=3306, user="******",
                             password="******",
                             charset="utf8")
        res = request.get_json()
        user_id = res.get('user_id')
        open_id = res.get('open_id')
        new_user_id = res.get('new_user_id')
        new_open_id = res.get('new_open_id')
        if not all([user_id, open_id, new_user_id, new_open_id]):
            return jsonify(errno=-1, errmsg="参数不完整")
        cursor = db.cursor()
        timeStamp = int(time.time())
        dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
        otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
        sql = f"INSERT INTO zjlivenew.zj_heaven_for_user(create_time,update_time,user_id,openid,new_user_id,new_openid,status)" \
              f"VALUES('{otherStyleTime}','{otherStyleTime}',{int(user_id)},'{open_id}',{int(new_user_id)},'{new_open_id}',{int(0)})"
        print(sql)
        cursor.execute(sql)
        db.commit()
        db.close()
        return jsonify(errno=0, errmsg="OK")
    except Exception as e:
        Logging.logger.error('errmsg:{0}'.format(e))
        return jsonify(errno=-1, errmsg='网络异常')
Example #6
0
def promote_user(email, username, password):
    """Make a new admin"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute('SELECT COUNT(*) FROM user')
        users = cur.fetchone()

        if users == (1, ):
            cur.execute('UPDATE user SET enable = True WHERE email = %s',
                        (email, ))
            cur.execute('UPDATE user SET is_admin = True WHERE email = %s',
                        (email, ))
            db.commit()
            db.close()
            click.echo('User (' + email + ') enabled and admin now.')
        else:
            click.echo('Access denied.')
    else:
        click.echo('Invalid password')
Example #7
0
def add_players(tournamentID):
    form = AddPlayers(request.form)
    db = get_db()
    if request.method == 'POST':
        db.close()
        return redirect(url_for("round", tournamentID=tournamentID, round_num=1))
    return render_template('add_players.html', form=form)
Example #8
0
def newNotebook():
    if current_user.enable:
        res = requests.post(f'{APISERVER}/api/notebook',
                            json={'name': request.form['name']})

        if res.status_code == 201:

            dates = json.loads(res.text)
            notebook_id = dates.get('id')

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute(
                'INSERT INTO user_object_id (object_id, object_type, user_name) VALUES (%s,%s,%s)',
                (
                    notebook_id,
                    "notebook",
                    current_user.username,
                ))
            db.commit()
            db.close()

            flash(f'Notebook created!')
        else:
            flash(res.status_code)
        return redirect(url_for('notebooks'))
    else:
        return redirect(url_for('403'))
Example #9
0
def init_db(database=None):
    if not database:
        database = app.config["DATABASE"]
    db.init(database)
    db.connect()
    db.create_tables([Author, Content])
    Author.create(id=1, name="author")
    db.close()
Example #10
0
def newEndpoint():
    if current_user.enable:

        name = request.form['name']
        training_id = request.form['training_id']

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute(
            'SELECT * FROM user_object_id WHERE object_id =%s AND object_type=%s AND user_name=%s',
            (
                training_id,
                "training",
                current_user.username,
            ))
        training = cur.fetchone()
        db.close()

        if training == None:
            flash('Invalid training id')
        else:
            training_id = training[1]
            res = requests.post(f'{APISERVER}/api/endpoints/endpoint',
                                json={
                                    'name': name,
                                    'training_id': training_id
                                })

            if res.status_code == 201:

                dates = json.loads(res.text)
                endpoint_id = dates.get('id')

                db = mysql.connect(host=MYSQL_HOST,
                                   user=MYSQL_USER,
                                   password=MYSQL_PSSW,
                                   database=MYSQL_DB)
                cur = db.cursor()
                cur.execute(
                    'INSERT INTO user_object_id (object_id, object_type, user_name) VALUES (%s,%s,%s)',
                    (
                        endpoint_id,
                        "endpoint",
                        current_user.username,
                    ))
                db.commit()
                db.close()

                flash(f'Endpoint created!')
            else:
                flash(res.status_code)

        return redirect(url_for('endpoints'))
    else:
        return redirect(url_for('403'))
Example #11
0
def questions():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    id = L["id"]
    cursor.execute("SELECT c_id from Enrolment where s_id=%s", id)
    course = cursor.fetchall()
    print(course)

    if len(course) != 3:
        return '404'

    questions = []
    for i in course:
        cursor.execute(
            "SELECT question,answer FROM new_answer_new  where course_id = %s ORDER BY time desc LIMIT 0,3",
            i)
        result = cursor.fetchall()
        questions.append([])
        for j in range(len(result)):
            questions[-1].append(result[j][0])
            questions[-1].append(result[j][1])
    print(questions)

    qst = {
        "c1": course[0],
        "question11": questions[0][0],
        "answer11": questions[0][1],
        "question12": questions[0][2],
        "answer12": questions[0][3],
        "question13": questions[0][4],
        "answer13": questions[0][5],
        "c2": course[1],
        "question21": questions[1][0],
        "answer21": questions[1][1],
        "question22": questions[1][2],
        "answer22": questions[1][3],
        "question23": questions[1][4],
        "answer23": questions[1][5],
        "c3": course[2],
        "question31": questions[2][0],
        "answer31": questions[2][1],
        "question32": questions[2][2],
        "answer32": questions[2][3],
        "question33": questions[2][4],
        "answer33": questions[2][5]
    }
    print(qst)
    qst = json.dumps(qst)
    db.close()
    return qst
Example #12
0
def load_tournament():
    db = get_db()
    cur = db.execute('SELECT id, name, round_num FROM tournament')
    TOURNS = cur.fetchall()
    db.close()
    if request.method == 'POST':
        tourn_to_load = request.form['tourn']
        return redirect(url_for("round", tournamentID=tourn_to_load, round_num=2))

    return render_template('load_tournament.html', tourns=TOURNS)
Example #13
0
def sign_in():
    form = RegisterForm()
    if request.method == 'GET':
        return render_template("register.html", title='register', form=form)
    else:
        db = pymysql.connect(
            host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
            user='******',
            password='******',
            port=3306,
            db='chatbot')
        cursor = db.cursor()
        sql = [
            "INSERT INTO student(id,email,password,name) VALUES (%s,%s,%s,%s)",
            "INSERT INTO staff(id,email,password,name) VALUES (%s,%s,%s,%s)"
        ]
        if form.validate_on_submit():
            id = form.id.data
            name = form.name.data
            email = form.email.data
            password = form.password.data
            SorT = form.SorT.data
            password = generate_password_hash(password)
            if SorT == 1:
                cursor.execute("SELECT * from student where id=%s", id)
                result = cursor.fetchall()
                if len(result) != 0:
                    flash(
                        'Registration failed, zID has been registered, please log in directly.',
                        'error')
                    return render_template("register.html",
                                           title='register',
                                           form=form)
                else:
                    cursor.execute(sql[0], (id, email, password, name))
            else:
                cursor.execute("SELECT * from staff where id=%s", id)
                result = cursor.fetchall()
                if len(result) != 0:
                    flash(
                        'Registration failed, zID has been registered, please log in directly.',
                        'error')
                    return render_template("register.html",
                                           title='register',
                                           form=form)
                else:
                    cursor.execute(sql[1], (id, email, password, name))
            db.commit()
            db.close()
            # flash('Congratulations, your register are success.', 'info')
            return redirect(url_for('login'))
        db.rollback()
        db.close()
        flash('Sorry, your register not success, please try again.', 'error')
        return render_template("register.html", title='register', form=form)
Example #14
0
def home():
	conn = sqlite3.connect(DATABASE)
	TOURNS = conn.execute('SELECT * FROM tournament').fetchall()
	if request.method == 'POST':
		if request.form['choice'] == 'Create new':	
			return redirect(url_for("create_tournament"))
			db.close()
		elif request.form['choice'] == 'Load old':
			# go to load pages and pull in all tournament entries from the database
			return redirect(url_for("load_tournament"))
	return render_template('index.html', tourns=TOURNS, title="Main menu")
Example #15
0
def satistics():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    id = L["id"]
    cursor.execute("SELECT c_id from Teaching where T_id=%s", id)
    course = cursor.fetchall()
    print(course)

    if len(course) != 3:
        return '404'

    sat = []
    for i in course:
        cursor.execute(
            "SELECT COUNT(question) FROM new_answer_new  where course_id = %s ",
            i)
        result = cursor.fetchall()
        sat.append(int(re.findall(r"\d+", str(result[0]))[0]))
        cursor.execute(
            "SELECT COUNT(question) FROM new_question  where course_id = %s ",
            i)
        result = cursor.fetchall()
        sat.append(int(re.findall(r"\d+", str(result[0]))[0]))

    print(sat)
    s1 = int((sat[0] / (sat[0] + sat[1])) * 100)
    s2 = int((sat[2] / (sat[2] + sat[3])) * 100)
    s3 = int((sat[4] / (sat[4] + sat[5])) * 100)
    satistics = {
        "c1": course[0],
        "q1": sat[0],
        "qq1": sat[1],
        "s1": s1,
        "c2": course[1],
        "q2": sat[2],
        "qq2": sat[3],
        "s2": s2,
        "c3": course[2],
        "q3": sat[4],
        "qq3": sat[5],
        "s3": s3,
    }
    print(satistics)
    satistics = json.dumps(satistics)
    db.close()
    return satistics
Example #16
0
def db_create():
  db.connect()
  User.create_table(True) # True means fail siliently if table exists
  SocialCounter.create_table(True)
  SocialCount.create_table(True)
  ChannelCounter.create_table(True)
  Channel.create_table(True)
  UserFunction.create_table(True)
  FunctionResult.create_table(True)
  Crawler.create_table(True)
  CrawlerPage.create_table(True)
  Mozscape.create_table(True)
  MozscapeResult.create_table(True)
  MozscapeIndexMetadata.create_table(True)
  db.close()
Example #17
0
def select_japply():
    db = pymysql.connect("127.0.0.1", "root", "638436", "adms")
    cursor = db.cursor()
    username = "******"
    r_mname = "ADNI_002_S_0295_MR_HarP_135_final_release_2015_Br_20150226095012465_S13408_I474728.nii"
    mri = "select * from mri where m_name='" + r_mname + "'"
    cursor.execute(mri)
    mri_r = cursor.fetchall()
    r_uid = mri_r[0][1]
    r_utime = mri_r[0][3]
    print(mri_r)
    print(r_uid)
    print(r_utime)
    db.commit()
    db.close()
Example #18
0
def deleteTraining(username, id_to_delete, password):
    """Delete endpoint"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):
        if user.enable:

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute(
                'SELECT * FROM user_object_id WHERE user_name = %s AND object_id = %s',
                (user.username, id_to_delete))
            endpoint_to_delete = cur.fetchone()
            db.close()

            if endpoint_to_delete:
                res = requests.delete(
                    f'{APISERVER}/api/endpoint/{id_to_delete}')

                if res.status_code == 200:

                    db = mysql.connect(host=MYSQL_HOST,
                                       user=MYSQL_USER,
                                       password=MYSQL_PSSW,
                                       database=MYSQL_DB)
                    cur = db.cursor()
                    cur.execute(
                        'DELETE FROM user_object_id WHERE object_id = %s AND object_type = %s',
                        (
                            id_to_delete,
                            "notebook",
                        ))
                    db.commit()
                    db.close()

                    click.echo('\nEndpoint eliminated!\n')
                else:
                    click.echo(res.status_code)
            else:
                click.echo('Invalid endpoint_id')
        else:
            click.echo('You can\'t delete endpoint')
    else:
        click.echo('Invalid password')
Example #19
0
def read_sql():
    list = []
    db = pymysql.connect("127.0.0.1", "root", "123456", "db_demo1")
    # SQL 查询语句
    sql = "SELECT terminalid FROM CAR "
    try:
        cursor = db.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        db.close()
    except:
        logging.info(u"数据路查询异常")
        read_sql()
    for obj in result:
        list.append(obj[0])
    return list
Example #20
0
 def get_data(self,db_name,table_name):
      global data
      sql_columns_name=str("desc %s" %table_name)
      db=pymysql.connect("localhost","root","123456",db_name,charset = 'utf8')
      cursor=db.cursor()
      cursor.execute(sql_columns_name)
      columns_name =list(cursor.fetchall())
      sql_data_count=str("select count(*) from %s" %table_name)
      cursor.execute(sql_data_count)
      data_count=list(cursor.fetchall())
      
      sql_data=str("select * from %s" %table_name)
      cursor.execute(sql_data)
      data = pd.DataFrame(np.array(cursor.fetchall()))
      data.columns=[np.array(columns_name)[:,0]]
      db.close()
      return columns_name,data_count,data
Example #21
0
def newTraining(username, name, file, password):
    """Create a new training"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):
        if user.enable:
            upload_file = os.environ.get("UPLOAD_FOLDER")

            files = {'file': file}
            print(upload_file)
            print(file)
            print(files)
            res = requests.post(f'{APISERVER}/api/training/{name}',
                                files=files)

            if res.status_code == 201:

                dates = json.loads(res.text)
                training_id = dates.get('id')

                db = mysql.connect(host=MYSQL_HOST,
                                   user=MYSQL_USER,
                                   password=MYSQL_PSSW,
                                   database=MYSQL_DB)
                cur = db.cursor()
                cur.execute(
                    'INSERT INTO user_object_id (object_id, object_type, user_name) VALUES (%s,%s,%s)',
                    (
                        training_id,
                        "training",
                        user.username,
                    ))
                db.commit()
                db.close()

                click.echo('Training created!\n')
                click.echo(res.content)
            else:
                click.echo(res.status_code)
        else:
            click.echo('You can\'t create training')
    else:
        click.echo('Invalid password')
Example #22
0
 def loop_run(self):
     count = 0
     while 1:
         try:
             if count > 60:
                 db.connect()
                 maxid = self.get_maxid()
                 self.delete(maxid - self.rest)
                 count = 0
                 db.close()
             else:
                 count += 1
         except Exception as e:
             logger.error(e)
             time.sleep(1)
         finally:
             time.sleep(1)
             if self.is_quit:
                 break
Example #23
0
def create_tournament():
    form = CreateTournament(request.form)
    db = get_db()
    if request.method == 'POST':
        nam = request.form['tourn_name']
        loc = request.form['location']
        cal = request.form['calendar']
        sys = request.form['system']
        tie = request.form['tie_break']
        db.execute('''INSERT INTO tournament \
			(id, name, location, calendar, system, tie_break, round_num) \
			VALUES (NULL, ?, ?, ?, ?, ?, ?)''', (nam, loc, cal, sys, tie, 1))
        db.commit()
        tournamentID = str(
            db.execute('''SELECT max(id) FROM tournament''').fetchone()[0])
        db.close()
        return redirect(url_for('add_players', tournamentID=tournamentID))

    return render_template('create_tournament.html', title='Create new tournament', form=form)
Example #24
0
def new_email_t():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    sql = "SELECT email from staff where id=%s"
    id = L['id']
    email = L['email']
    cursor.execute(sql, id)
    sql = "UPDATE staff set email=%s WHERE id = %s "
    cursor.execute(sql, (email, id))
    db.commit()
    db.close()
    return '200'
Example #25
0
def notebooks(username, password):
    """Show your notebook list"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):
        if user.enable:

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute('SELECT * FROM user_object_id')
            objects = cur.fetchall()
            db.close()

            notebooks = []
            for notebook in objects:
                if notebook[3] == user.username and notebook[2] == "notebook":
                    notebook_id = notebook[1]

                    res = requests.get(
                        f'{APISERVER}/api/notebook/{notebook_id}').content
                    notebook = json.loads(res)

                    notebooks.append(notebook)
                else:
                    if user.is_admin and notebook[2] == "notebook":
                        notebook_id = notebook[1]

                        res = requests.get(
                            f'{APISERVER}/api/notebook/{notebook_id}').content
                        notebook = json.loads(res)

                        notebooks.append(notebook)

            click.echo(notebooks)
        else:
            click.echo('You can\'t create notebook')
    else:
        click.echo('Invalid password')
Example #26
0
def endpoints(username, password):
    """Show your endpoint list"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):
        if user.enable:

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute('SELECT * FROM user_object_id')
            objects = cur.fetchall()
            db.close()

            endpoints = []
            for endpoint in objects:
                if endpoint[3] == user.username and endpoint[2] == "endpoint":
                    endpoint_id = endpoint[1]

                    res = requests.get(
                        f'{APISERVER}/api/endpoint/{endpoint_id}').content
                    endpoint = json.loads(res)

                    endpoints.append(endpoint)
                else:
                    if user.is_admin and endpoint[2] == "endpoint":
                        endpoint_id = endpoint[1]

                        res = requests.get(
                            f'{APISERVER}/api/endpoint/{endpoint_id}').content
                        endpoint = json.loads(res)

                        endpoints.append(endpoint)

            click.echo(endpoints)
        else:
            click.echo('You can\'t create endpoint')
    else:
        click.echo('Invalid password')
Example #27
0
def classes_t():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    id = L["id"]
    cursor.execute("SELECT c_id from Teaching where T_id=%s", id)
    result = cursor.fetchall()
    print(result)
    if len(result) == 3:
        classes = {"c0": result[0], "c1": result[1], "c2": result[2]}
        return json.dumps(classes)
    db.commit()
    db.close()
    return "404"
Example #28
0
def up_course_t():
    L = request.get_data()
    L = json.loads(L)
    db = pymysql.connect(
        host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
        user='******',
        password='******',
        port=3306,
        db='chatbot')
    cursor = db.cursor()
    id = L["id"]
    cursor.execute("INSERT INTO Teaching (T_id,c_id) VALUES (%s,%s)",
                   (id, str.upper(L["course1"])))
    cursor.execute("INSERT INTO Teaching (T_id,c_id) VALUES (%s,%s)",
                   (id, str.upper(L["course2"])))
    cursor.execute("INSERT INTO Teaching (T_id,c_id) VALUES (%s,%s)",
                   (id, str.upper(L["course3"])))
    db.commit()
    db.close()
    return "200"
Example #29
0
def deleteEndpoint():
    if current_user.enable:

        id_to_delete = request.form['id_to_delete']

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute(
            'SELECT * FROM user_object_id WHERE user_name = %s AND object_id = %s',
            (current_user.username, id_to_delete))
        endpoint_to_delete = cur.fetchone()
        db.close()

        if endpoint_to_delete or current_user.is_admin:
            res = requests.delete(f'{APISERVER}/api/endpoint/{id_to_delete}')

            if res.status_code == 200:

                db = mysql.connect(host=MYSQL_HOST,
                                   user=MYSQL_USER,
                                   password=MYSQL_PSSW,
                                   database=MYSQL_DB)
                cur = db.cursor()
                cur.execute(
                    'DELETE FROM user_object_id WHERE object_id = %s AND object_type = %s',
                    (
                        id_to_delete,
                        "endpoint",
                    ))
                db.commit()
                db.close()

                flash(f'Endpoint eliminated!')
            else:
                flash(res.status_code)
        return redirect(url_for('endpoints'))
    else:
        return redirect(url_for('403'))
Example #30
0
def init_db():
    '''Initial database'''
    db.connect()

    print('Creating tables ...')
    db.create_tables(tables)
    print('Tables have been created.')

    print('Writing default configurations ...')
    Config.create(name='site_name', value=app.config['DEFAULT_SITE_NAME'])
    Config.create(name='site_url', value=app.config['DEFAULT_SITE_URL'])
    Config.create(name='count_topic',
                  value=app.config['DEFAULT_TOPICS_PER_PAGE'])
    Config.create(name='count_post',
                  value=app.config['DEFAULT_POSTS_PER_PAGE'])
    Config.create(name='count_list_item',
                  value=app.config['DEFAULT_LIST_ITEM_PER_PAGE'])
    #   Config.create(name='count_subpost', value=app.config['DEFAULT_SUBPOSTS_PER_PAGE'])
    print('Default configurations have been written into database.')

    db.close()
Example #31
0
def trainings():
    if current_user.enable:

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute('SELECT * FROM user_object_id')
        objects = cur.fetchall()
        db.close()

        trainings = []
        for training in objects:
            if training[3] == current_user.username and training[
                    2] == "training":
                training_id = training[1]

                res = requests.get(
                    f'{APISERVER}/api/training/{training_id}').content
                training = json.loads(res)

                trainings.append(training)
            else:
                if current_user.is_admin and training[2] == "training":

                    training_id = training[1]

                    res = requests.get(
                        f'{APISERVER}/api/training/{training_id}').content
                    training = json.loads(res)

                    trainings.append(training)

        return render_template("trainings.html",
                               title="Trainings",
                               trainings=trainings)
    else:
        return redirect(url_for('403'))
Example #32
0
def trainings(username, password):
    """Show your training list"""
    user = User.query.filter_by(username=username).first_or_404(
        description='Invalid username')

    if user.check_password(password):
        if user.enable == True:

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute('SELECT * FROM user_object_id')
            objects = cur.fetchall()
            db.close()

            trainings = []
            for training in objects:
                if training[3] == user.username and training[2] == "training":
                    training_id = training[1]

                    res = requests.get(
                        f'{APISERVER}/api/training/{training_id}').content
                    training = json.loads(res)

                    trainings.append(training)
                elif user.is_admin and training[2] == "training":
                    training_id = training[1]
                    res = requests.get(
                        f'{APISERVER}/api/training/{training_id}').content
                    training = json.loads(res)

                    trainings.append(training)
            click.echo(trainings)
        else:
            click.echo('You can\'t create training')
    else:
        click.echo('Invalid password')
Example #33
0
def newTraining():
    if current_user.enable:
        name = request.form['name']
        file = request.files['file']
        upload_file = os.environ.get("UPLOAD_FOLDER")

        file_path = os.path.join(upload_file, file.filename)

        file.save(file_path)

        files = {'file': open(file_path, 'rb')}

        res = requests.post(f'{APISERVER}/api/training/{name}', files=files)

        if res.status_code == 201:
            dates = json.loads(res.text)
            training_id = dates.get('id')

            db = mysql.connect(host=MYSQL_HOST,
                               user=MYSQL_USER,
                               password=MYSQL_PSSW,
                               database=MYSQL_DB)
            cur = db.cursor()
            cur.execute(
                'INSERT INTO user_object_id (object_id, object_type, user_name) VALUES (%s,%s,%s)',
                (
                    training_id,
                    "training",
                    current_user.username,
                ))
            db.commit()
            db.close()

            flash(f'Training created!')
        else:
            flash(res.status_code)
        return redirect(url_for('trainings'))
    else:
        return redirect(url_for('403'))
Example #34
0
def notebooks():
    if current_user.enable:

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute('SELECT * FROM user_object_id')
        objects = cur.fetchall()
        db.close()

        notebooks = []
        for notebook in objects:
            if notebook[3] == current_user.username and notebook[
                    2] == "notebook":
                notebook_id = notebook[1]

                res = requests.get(
                    f'{APISERVER}/api/notebook/{notebook_id}').content
                notebook = json.loads(res)

                notebooks.append(notebook)

            else:
                if current_user.is_admin and notebook[2] == "notebook":
                    notebook_id = notebook[1]

                    res = requests.get(
                        f'{APISERVER}/api/notebook/{notebook_id}').content
                    notebook = json.loads(res)

                    notebooks.append(notebook)

        return render_template("notebooks.html",
                               title="Notebooks",
                               notebooks=notebooks)
    else:
        return redirect(url_for('403'))
Example #35
0
def endpoints():
    if current_user.enable:

        db = mysql.connect(host=MYSQL_HOST,
                           user=MYSQL_USER,
                           password=MYSQL_PSSW,
                           database=MYSQL_DB)
        cur = db.cursor()
        cur.execute('SELECT * FROM user_object_id')
        objects = cur.fetchall()
        db.close()

        endpoints = []
        for endpoint in objects:
            if endpoint[3] == current_user.username and endpoint[
                    2] == "endpoint":
                endpoint_id = endpoint[1]

                res = requests.get(
                    f'{APISERVER}/api/endpoint/{endpoint_id}').content
                endpoint = json.loads(res)

                endpoints.append(endpoint)

            else:
                if current_user.is_admin and endpoint[2] == "endpoint":
                    endpoint_id = endpoint[1]

                    res = requests.get(
                        f'{APISERVER}/api/endpoint/{endpoint_id}').content
                    endpoint = json.loads(res)

                    endpoints.append(endpoint)
        return render_template("endpoints.html",
                               title="Endpoints",
                               endpoints=endpoints)
    else:
        return redirect(url_for('403'))
Example #36
0
def teardown_request(exception):
    """Commits again and closes the database again at the end of the request."""
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()
Example #37
0
from app import app, db
from app.models import *

db.connect()

for table in [ Track, User, Slot, SlotRequest, PlaylistTrack, Wish, RadioStation ]:
	db.create_table( table, safe = True )
	
db.close()
Example #38
0
File: db.py Project: stabora/nbsf
 def __del__(self):
     db.close()
Example #39
0
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
Example #40
0
def initialize():
    db.connect()
    db.create_tables([Match, MatchPlayer, Player], safe=True)
    db.close()