예제 #1
0
def addstudent():
    try:

        if request.method == "POST":
            cond = request.form["customRadio"]
            if (cond == 'addstudent'):
                name = request.form['name']
                roll = request.form['roll']
                year = request.form.get('acyear')
                branch = request.form.get('branch')
                c, conn = connection()
                try:
                    c.execute("INSERT INTO student VALUES (%s,%s, %s,%s)",
                              (roll, name, branch, year))
                    conn.commit()
                    conn.close()

                    flash(roll + ' Added Successfully')
                except Exception:
                    flash('Invalid Credentials')
            if (cond == 'viewstudent'):
                c, conn = connection()
                year = request.form.get('acyear')
                branch = request.form.get('branch')
                try:
                    c.execute(
                        "SELECT roll,name,branch,acyear FROM student WHERE acyear=%s AND branch=%s",
                        (
                            year,
                            branch,
                        ))
                    data = c.fetchall()
                    if data:
                        colname = [desc[0] for desc in c.description]
                        data.insert(0, colname)
                    return render_template('view.html',
                                           data=data,
                                           down=down,
                                           type=session['type'],
                                           year=yea,
                                           subj=subj)
                except Exception as e:
                    flash('Invalid Credentials')
            if (cond == 'deletestudent'):
                c, conn = connection()
                roll = request.form['roll']
                try:
                    c.execute("DELETE FROM student WHERE roll = ('%s')" %
                              (roll))
                    conn.commit()
                    conn.close()
                    flash(roll + ' Deleted Successfully')
                except Exception:
                    flash('Unable to find given details')
    except Exception as e:
        flash('Unable to connect Please try again')
    return render_template('home.html',
                           type=session['type'],
                           year=yea,
                           subj=subj)
예제 #2
0
def login():
    error = ''
    error1 = ''
    try:
        if request.method == "POST":
            username = request.form['username']
            password = request.form['password']
            conn, cur = connection()
            x = cur.execute("SELECT * FROM user WHERE username=(%s)",
                            (username, ))
            if int(x) == 0:
                error = 'User Not found'
            elif int(x) > 0:
                conn, cur = connection()
                cur.execute("SELECT password FROM user WHERE username=(%s)",
                            (username, ))
                record = cur.fetchone()
                for row in record:
                    if (password) == (row):
                        session['name'] = username
                        return redirect(url_for('main'))
                    else:
                        error1 = 'Wrong password'
        return render_template("login.html", error=error, error1=error1)

    except Exception as e:

        return render_template("login.html", error=error, error1=error1)
예제 #3
0
def add_specs(brand, model_name):
    if request.method == 'POST':
        model_name = request.form.get('model_name')
        brand = request.form.get('brand')
        print(brand)
        print(model_name)
        processor = request.form.get('processor')
        graphics = request.form.get('graphics')
        os = request.form.get('os')
        battery_cap = request.form.get('battery_cap')
        quick_charge = request.form.get('quick_charge')
        front_camera = request.form.get('front_camera')
        rear_camera = request.form.get('rear_camera')
        display_type = request.form.get('display_type')
        display_size = request.form.get('display_size')
        aspect_ratio = request.form.get('aspect_ratio')
        weight = request.form.get('weight')
        build = request.form.get('build')
        dimensions = request.form.get('dimensions')
        colours = request.form.get('colours').split(",")
        print(colours)

        # inserting colors
        for colour in colours:
            # create cursor
            cur, conn = connection()

            cur.execute(
                "INSERT INTO colours (model_name, colour) VALUES ('%s','%s')" %
                (model_name, colour))

            # commit
            conn.commit()

            # close connection
            cur.close()

        # create cursor
        cur, conn = connection()

        # inserting specs
        cur.execute(
            """INSERT INTO specifications(model_name, processor, graphics, os, battery_cap, quick_charge, front_camera, rear_camera, display_type, display_size, aspect_ratio,dimensions, weight, build) 
                    VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
            (model_name, processor, graphics, os, battery_cap, quick_charge,
             front_camera, rear_camera, display_type, display_size,
             aspect_ratio, dimensions, weight, build))

        # commit
        conn.commit()

        # close connection
        cur.close()

        flash('Specs are saved successfully...')
        return redirect(
            url_for('add_variants', brand=brand, model_name=model_name))

    return render_template('addSpecs.html', brand=brand, model_name=model_name)
예제 #4
0
def registration():
    try:
        if request.method == "POST" :
            if 'submit_button' in request.form:
                name  = request.form['name']
                clgname = request.form['clgname']
                email=request.form['email']
                branch = request.form['branch']
                paper_title=request.form['papertitle']
                x=mailverify(email)
                
                
                if x == 1:
                    c, conn = connection()
                    c.execute("SELECT MAX(id) FROM festusers")
                    id=c.fetchone()
                    c.execute("INSERT INTO festusers VALUES (%s,%s, %s,%s, %s, %s)",(id[0]+1,name,clgname,email,paper_title,branch))
                    conn.commit()                    
                    
                    
                    
                    z=send_mail(str(email),id[0]+1)
                    
                    c.close()
                    conn.close()
                    gc.collect()
                    flash("Successfully Registered !! Please check your email for further communication!!")
                    return render_template("resonance.html")
                else:
                    flash("Invalid email!!")
                    return render_template('register.html')
            return render_template("register.html")

    except Exception as e:
        return render_template("home.html", error = e) 
예제 #5
0
def lewis_t(text):
    try:
        print("db_result")
        c, conn = connection()
        c.execute("SELECT * FROM structures where element ='" + text + "'")
        db_result = c.fetchall()

        lwis = str(db_result).split("', '")
        lenth = len(lwis)
        xxx = ""

        for i in range(lenth):
            if i == 0:
                lwis[0] = lwis[0][3:]
            elif i == lenth - 1:
                size = len(lwis[i])
                lwis[i] = lwis[i][:size - 4]

        final_answer = ",".join(lwis)

        c.close()
        conn.close()
        gc.collect()
    except Exception as e:
        return (str(e))
    return final_answer
예제 #6
0
def login_page():
    error = None
    try:
        if request.method == 'POST':
            c, conn = connection()
            username = c.execute("SELECT * FROM users WHERE username=(%s)",
                                 (thwart(request.form['username']), ))
            if username == 0:
                #error=" Username doesn't exist"
                flash("Username doesn't exist")
                return render_template('login.html', error=error)

            data = c.fetchone()[2]

            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']
                return redirect(url_for('dashboard'))
            else:
                # error=" Incorrect Password"
                flash("Incorrect Password")
                return render_template('login.html', error=error)
            c.close()
            conn.close()
        gc.collect()
        return render_template('login.html', error=error)
    except Exception as e:
        return render_template("login.html", error=e)
예제 #7
0
def register():
    try:
        form = RegistrationForm(request.form)
        if request.method == 'POST' and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))
            c, conn = connection()
            x = c.execute("SELECT * from users where username=(%s)",
                          [thwart(username)])
            if int(x) > 0:
                flash("That username is already taken.Please choose another")
                return render_template('register.html', form=form)
            else:
                c.execute(
                    "INSERT INTO users (username,password,email) VALUES (%s,%s,%s)",
                    (thwart(username), thwart(password), thwart(email)))
                conn.commit()
                flash("Thanks for registering!!!")
                c.close()
                conn.close()
                gc.collect()
                return redirect('/')

        return render_template('register.html', form=form)
    except Exception as e:
        return (str(e))
예제 #8
0
def login():
    c,conn = connection()
   
    try:
        
        if request.method == "POST" :

            if 'adminsubmit' in request.form:
                c.execute("SELECT * FROM admin WHERE email = ('%s')" %request.form["adminmail"])
               
                data = c.fetchone()
              
                if sha256_crypt.verify(request.form['password'],data[1] ):
                    
                    
                    c.execute("SELECT * FROM festusers WHERE branch = %s",(data[2],))
                    colname=[desc[0] for desc in c.description]
                    tab_data=c.fetchall()
                    l=len(tab_data)

                    tab_data.insert(0,colname)
                    c.close()
                    session['logged_in'] = True
                    session['username'] = request.form['adminmail']
                    conn.commit()
                    conn.close()
                    gc.collect()
                    return render_template("home.html",data = tab_data,l=l)
    except Exception as e:
        return render_template("admin.html")
    return render_template("admin.html")
예제 #9
0
def add_variants(brand, model_name):
    if request.method == 'POST':
        model_name = request.form.get('model_name')
        brand = request.form.get('brand')
        print("inside variants")
        print(brand)
        print(model_name)
        variant = request.form.get('variant')
        price = request.form.get('price')

        # creating cursor
        cur, conn = connection()

        cur.execute(
            """INSERT INTO variants (model_name, variant, price) VALUES (%s,%s,%s)""",
            (model_name, variant, price))

        # commit
        conn.commit()

        # close cursor
        cur.close()

        flash("A new variant is added successfully...", 'success')
        return redirect(
            url_for('add_variants', brand=brand, model_name=model_name))

    return render_template('addVariants.html',
                           brand=brand,
                           model_name=model_name)
예제 #10
0
def user_registration():
    try:
        c, conn = connection()
        c.execute("SELECT * FROM users where email =%s",
                  (request.json['email'], ))
        data = c.fetchall()

        edata = str(data).replace("'", "").replace("(", "").replace(
            "),)", "").replace(" ", "").replace(")", "")

        if (len(edata) == 0):
            c.execute(
                "INSERT INTO users(email,password,f_name,l_name) VALUES (%s,%s,%s,%s)",
                (request.json['email'], request.json['password'],
                 request.json['f_name'], request.json['l_name']))
            conn.commit()

            c.close()
            conn.close()
            gc.collect()

            return "1"
        else:
            return "0"

    except Exception as e:
        return (str(e))
예제 #11
0
def home():
    c,conn = connection()
    query = "SELECT * FROM posts"
    c.execute(query)
    post = c.fetchall()
    print(type(post))
    print(post)

    last = math.ceil(len(post)/int(params['no_of_posts']))
    print(last)
    #[0: params['no_of_posts']]
    #posts = posts[]
    page = request.args.get('page')
    if(not str(page).isnumeric()):
        page = 1
    page= int(page)
    post = post[(page-1)*int(params['no_of_posts']): (page-1)*int(params['no_of_posts'])+ int(params['no_of_posts'])]
    #Pagination Logic
    #First
    if (page==1):
        prev = "#"
        next = "/?page="+ str(page+1)
    elif(page==last):
        prev = "/?page=" + str(page - 1)
        next = "#"
    else:
        prev = "/?page=" + str(page - 1)
        next = "/?page=" + str(page + 1)

    return render_template("index.html", params=params, post=post, prev=prev, next=next)
예제 #12
0
def login_page():
    '''The login page. If the user inputs a login&password, first check if the 
	username exists, if so check the password and send the user to the chat room
	after updating the session and active_users. Else, display "invalid credentials" 
	and render the template again. It's easy to flash different error messages for
	invalid username and invalid password, but that feels hacker-friendly. Easy to
	change anyway.'''
    try:
        if request.method == "POST":
            cursor, conn = connection()
            user_exists = cursor.execute(
                "SELECT * FROM users WHERE username = (%s)",
                [request.form["username"]])
            # first see if the username exists
            if int(user_exists) > 0:
                # puts together the namespace and the values from the db... safer than doing things like row[2] assuming order etc.
                user = dict(
                    zip(map(lambda x: x[0], cursor.description),
                        cursor.fetchone()))
                # see if the password also checks out
                if sha256_crypt.verify(request.form['password'],
                                       user['password']):
                    session['logged_in'] = True
                    session['name'] = user['username']
                    active_users['lobby'].add(session['name'])
                    flash("You are now logged in")
                    return redirect(url_for("chat"))

            else:
                flash('Invalid credentials, please try again.')
                return render_template("login.html")

        return render_template("login.html")
    except Exception as e:
        return render_template("500.html", error=e)
예제 #13
0
def login():

    error = ''

    try:
        c, conn = connection()
        if request.method == "POST":

            #request_data = request.form.to_dict(flat=False)
            username = request.form['username']

            data = c.execute("SELECT * FROM users WHERE username=(%s)",
                             (username, ))
            data = c.fetchone()[2]

            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("You are now logged in")
                return redirect(url_for("dashboard"))

            else:
                error = "Invaild credentials, try again."

        gc.collect()

        return render_template("login.html", error=error)

    except Exception as e:
        #flash(e)
        error = "Invaild credentials, try again."
        return render_template('login.html', error=error)
예제 #14
0
def user_signup():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        password = sha256_crypt.encrypt(str(request.form.get('password')))
        # password = form.password.data

        print(name)
        print(email)
        print(password)

        # creating cursor
        cur, conn = connection()

        # check if email exists
        result = cur.execute("""SELECT * FROM users WHERE email=%s""",
                             (email, ))

        if result > 0:
            flash("user already exist use another email", 'danger')
            return redirect(url_for("home"))

        cur.execute(
            """INSERT INTO users(name, email, password) VALUES(%s, %s, %s)""",
            (name, email, password))

        # commit
        conn.commit()

        # close connection
        cur.close()

        flash('You are now registered and you can log in', 'success')

        return redirect(url_for('home'))
예제 #15
0
def upload_img(brand, model_name):

    if request.method == 'POST':
        model_name = request.form.get('model_name')
        brand = request.form.get('brand')
        f = request.files.getlist('img_file')
        print(f)

        for img in f:
            img_url = img.filename
            print(img_url)
            img.save(
                os.path.join(app.config['UPLOAD_FOLDER'],
                             secure_filename(img.filename)))
            # create cursor
            cur, conn = connection()

            cur.execute(
                "INSERT INTO images (model_name, img_url) VALUES ('%s','%s')" %
                (model_name, img_url))

            # commit
            conn.commit()

            # close connection
            cur.close()

        print(brand)
        print(model_name)

        flash('Image uploaded successfully...', 'success')
        return redirect(
            url_for('add_specs', brand=brand, model_name=model_name))

    return render_template('uploader.html', brand=brand, model_name=model_name)
예제 #16
0
def dashboard():
    c,conn = connection()

    if ('user' in session and session['user']==params['admin_user']):
        query = "SELECT * FROM posts"
        c.execute(query)
        post = c.fetchall()
        print(post)
        print(type(post))

        return render_template('admin_pannel.html', params=params, post=post)

    if request.method == 'POST':
        username = request.form.get('uname')
        password = request.form.get('pass')
        if (username==params['admin_user'] and password==params['admin_password']):
            #set session variable
            session['user']= username
            query = "SELECT * FROM posts"
            c.execute(query)
            post = c.fetchall()
            print(post)
            print(type(post))
           
            return render_template('admin_pannel.html', post=post, params=params)

    
    return render_template('login.html', params=params)
예제 #17
0
def add_gadget():
    if request.method == 'POST':
        model_name = request.form.get('model_name')
        print(model_name)
        brand = request.form.get('brand')
        print(brand)
        price = request.form.get('price')

        # create cursor
        cur, conn = connection()

        cur.execute(
            "INSERT INTO mobile (model_name, brand, price) VALUES ('%s', '%s','%s')"
            % (model_name, brand, price))

        # commit
        conn.commit()

        # close connection
        cur.close()
        flash('Gadget added successfully...', 'success')
        return redirect(
            url_for('upload_img', brand=brand, model_name=model_name))

    return render_template('addGadget.html')
예제 #18
0
def login_page():
	'''The login page. If the user inputs a login&password, first check if the 
	username exists, if so check the password and send the user to the chat room
	after updating the session and active_users. Else, display "invalid credentials" 
	and render the template again. It's easy to flash different error messages for
	invalid username and invalid password, but that feels hacker-friendly. Easy to
	change anyway.'''
	try:
		if request.method == "POST":
			cursor,conn = connection()
			user_exists = cursor.execute("SELECT * FROM users WHERE username = (%s)", [request.form["username"]])
			# first see if the username exists
			if int(user_exists) > 0:
				# puts together the namespace and the values from the db... safer than doing things like row[2] assuming order etc.
				user = dict(zip(map(lambda x:x[0], cursor.description), cursor.fetchone()))
				# see if the password also checks out
				if sha256_crypt.verify(request.form['password'], user['password']):	
					session['logged_in'] = True
					session['name'] = user['username']
					active_users['lobby'].add(session['name'])
					flash("You are now logged in")
					return redirect(url_for("chat"))
				
			else:
				flash('Invalid credentials, please try again.')
				return render_template("login.html") 
				
		return render_template("login.html") 		
	except Exception as e:
		return render_template("500.html", error = e)
예제 #19
0
def post_reviews(brand, model_name):
    if request.method == 'POST':
        print(brand)
        print(model_name)

        rating = request.form.get('rating')
        title = request.form.get('title')
        comment = request.form.get('comment')
        print(rating)
        # create cursor
        cur, conn = connection()

        cur.execute(
            """INSERT INTO reviews (model_name, email, rating, title, comment) VALUES (%s,%s,%s,%s,%s)""",
            (model_name, session['username'], rating, title, comment))

        # commit
        conn.commit()

        #  close connection
        cur.close()
        return redirect(
            url_for('view_details', brand=brand, model_name=model_name))

    return render_template('add_review.html',
                           brand=brand,
                           model_name=model_name)
예제 #20
0
def upload():
    try:
        c, conn = connection()
        s = ''
        if request.method == "POST":
            for i in st[2:]:
                for j in i:
                    marks = request.form[j[0]]
                    s = 'UPDATE student SET ' + st[1].replace(
                        ' ', '') + '=%s WHERE roll=%s'
                    print('marks     ', marks, j[0])
                    c.execute(s, (marks, j[0]))
                    conn.commit()
            conn.close()
            flash('Successfully Uploaded')

        return render_template('home.html',
                               type=session['type'],
                               year=yea,
                               subj=subj)
    except Exception as e:
        flash('Invalid Credentials')
    return render_template('home.html',
                           type=session['type'],
                           year=yea,
                           subj=subj)
예제 #21
0
def login():
    c, conn = connection()

    try:

        if request.method == "POST":
            if 'submit' in request.form:
                c.execute("SELECT * FROM users WHERE id = ('%s')" %
                          request.form["id"])

                data = c.fetchone()
                if sha256_crypt.verify(request.form['password'], data[1]):
                    session.permanent = True
                    session['logged_in'] = True
                    session['username'] = request.form["id"]
                    session['type'] = data[2]
                    conn.commit()
                    conn.close()
                    gc.collect()
                    return render_template("home.html",
                                           type=session['type'],
                                           year=yea,
                                           subj=subj)
    except Exception as e:
        flash('Invalid Credentials')
        session.clear()
        return render_template("login.html")
    session.clear()
    return render_template("login.html")
예제 #22
0
def delete(id):
    c, conn = connection()
    c.execute("DELETE FROM todolist WHERE id=(%s)", (thwart(id), ))
    conn.commit()
    c.close()
    conn.close()
    flash("Task deleted!!!")
    return redirect(url_for('dashboard'))
예제 #23
0
def delete(Sno):
    if ('user' in session and session['user']==params['admin_user']):
        c,conn = connection()
        query = "DELETE FROM posts where sno = '%s'" %(Sno,)
        print(query)
        c.execute(query)
        conn.commit()
        return redirect('/dashboard')
예제 #24
0
def sql(id):
    if request.method == 'DELETE':
        cur, conn = connection()
        cur.execute("DELETE FROM log where log_id ='" + id + "'")
        conn.commit()
        cur.close()
        data = {'message': 'deleted', 'success': True}
        return jsonify(data)
예제 #25
0
def download():
    c, conn = connection()
    with conn:
        with c:
            v = []
            v = [list(item) for item in view]
            return excel.make_response_from_array(v,
                                                  "csv",
                                                  file_name="mid_marks")
예제 #26
0
def download():
    c,conn=connection()
    with conn:
        with c:
           
            c.execute("SELECT * FROM festusers WHERE branch = %s",(session['username'],))
            colname=[desc[0] for desc in c.description]
            tab_data=c.fetchall()
            tab_data.insert(0,colname)
            return excel.make_response_from_array(tab_data, "csv",file_name="registered_candidates")
예제 #27
0
def posts(post_slug):
    print(post_slug)
    c,conn = connection()
    query = "SELECT * FROM posts where slug = '%s'" %(post_slug,)
    c.execute(query)
    post = c.fetchone()
    print(post)
    print(type(post))

    return render_template('post.html', post=post, params=params)
예제 #28
0
def section_data():
    conn, cur = connection()
    cur.execute('SELECT section FROM section')

    row_headers = [x[0]
                   for x in cur.description]  #this will extract row headers
    rv = cur.fetchall()
    json_data = []
    for result in rv:
        json_data.append(dict(zip(row_headers, result)))
    return (json.dumps(json_data))
예제 #29
0
def homepage():
    if 'logged_in' in session:
        c,conn = connection()
    
        c.execute("SELECT * FROM festusers WHERE branch = %s",(session['username'],))
        colname=[desc[0] for desc in c.description]
        tab_data=c.fetchall()
        l=len(tab_data)
        tab_data.insert(0,colname)
        return render_template("home.html",data=tab_data,l=l)
    return render_template("home.html")
예제 #30
0
def user():
    try:

        if request.method == "POST":
            cond = request.form["customRadio1"]
            id = request.form["id"]
            password = sha256_crypt.encrypt(request.form["password"])
            typ = request.form.get('type')
            email = request.form["email"]
            if (cond == 'adduser'):
                c, conn = connection()
                x = mailverify(email)
                if (x == 1):
                    c.execute("INSERT INTO users VALUES (%s,%s, %s,%s)",
                              (id, password, typ, email))
                    conn.commit()
                    conn.close()
                    flash('Succeccfully added new user')
                    return render_template("home.html",
                                           type=session['type'],
                                           year=yea,
                                           subj=subj)
                else:
                    flash('Invalid email')
            if (cond == 'deluser'):
                c, conn = connection()
                c.execute("DELETE FROM users WHERE id=('%s')" % id)
                conn.commit()
                conn.close()
                flash('Succeccfully deleted user')
                return render_template("home.html",
                                       type=session['type'],
                                       year=yea,
                                       subj=subj)

    except Exception as e:
        flash('Invalid Credentials')
    return render_template("home.html",
                           type=session['type'],
                           year=yea,
                           subj=subj)
예제 #31
0
def user_profile():

    cur, conn = connection()

    # get user by username
    cur.execute("""SELECT * FROM users WHERE email= %s""",
                (session['username'], ))

    # fetch result
    data = cur.fetchone()

    return render_template('user_profile.html', data=data)
예제 #32
0
def profile_page():
	'''Connect to the users database to get the registered time.
	Connect to the chat logs database to get the recent chat logs of the user'''
	try:
		cursor,conn = connection()
		cursor.execute("SELECT * FROM users WHERE username = (%s)", [session['name']])
		user = dict(zip(map(lambda x:x[0], cursor.description), cursor.fetchone()))
		user["registered_time_displayform"] = user["registered_time"].strftime('%Y-%m-%d')
		cursor.execute("SELECT * FROM chatlog WHERE (receiver LIKE %s OR sender = %s) ORDER BY messageid DESC LIMIT 20;", 							["%"+session['name']+"%", 
						 session['name']
						])
		namespace = map(lambda x:x[0], cursor.description)
		user['chatlog'] = cursor.fetchall()
		return render_template('profile.html',user = user)
	except Exception as e:
		return render_template("500.html", error = e)	
예제 #33
0
def sent(message):
	'''New chat message gets sent to everybody in the room. Also if there are more than 
	one logged in user in the room, log the message'''
	room = session.get('room')
	emit('message', {'msg': session.get('name') + ':' + message['msg']}, room=room)

	#log the message only if the user is not the only logged in user in the room
	if len(active_users[session['room']]) > 1:
		# is it too costly to open/close a connection every time?
		ChatCursor,ChatConn = connection()
		ChatCursor.execute("INSERT INTO chatlog (sender,receiver,room,message) VALUES (%s, %s, %s, %s)", 
							[session['name'], 
							 str(list( active_users[session['room']] - set([session['name']]) )), 
							 room, 
							 message['msg'] 
							])
		ChatConn.commit()
		ChatCursor.close()
		ChatConn.close()
		gc.collect()
예제 #34
0
def registration_page():
	'''With validated username and password fields from the form, check if 
	the username already exists. After registering update session and active_users
	and send the user to the chat page.'''
	try:
		form = RegistrationForm(request.form)
		# form.validate checks for the length of the username and password, and two password fields 
		# being equal to each other.
		if request.method == "POST" and form.validate():
			username = str(form.username.data)
			passwd =  sha256_crypt.encrypt((str(form.password.data)))
			cursor,conn = connection()
			#check if the user exists
			user_exists = cursor.execute("SELECT * FROM users WHERE username = (%s)", [username])
			if int(user_exists) > 0:
				flash("Username is already taken, please pick another one.")
				return render_template('register.html',form = form)
			
			else:
				if username.startswith('Guest_'):
					flash("Guest_* usernames are for guests, you deserve better.")				
					return render_template('register.html',form = form)
				
				cursor.execute("INSERT INTO users (username,password) VALUES (%s, %s)", [username, passwd])
				conn.commit()			
				cursor.close()
				conn.close()
				gc.collect()
				
				session['logged_in'] = True
				session['name'] = username
				flash("Thanks for registering!")
				active_users['lobby'].add(session['name'])
				return redirect(url_for('chat'))
		else:
			return render_template('register.html', form = form)
		
	except Exception as e:
		return render_template("500.html", error = e)	
예제 #35
0
파일: functions.py 프로젝트: ranorr/Dogs
from dbconnection import connection

c, conn = connection()


def create_person_table():
    """Create preson table"""
    c.execute("CREATE TABLE person (Id INT PRIMARY KEY, firstName VARCHAR(25), lastName VARCHAR(25))")
    c.close()


def enter_new_person():
    id = input("id number?: ")
    firstName = input("First Name?: ")
    lastName = input("Last Name?: ")
    c.execute("INSERT INTO person (Id, firstName, lastName) VALUES (%s, %s, %s)", (id, firstName, lastName))
    conn.commit()
    print_table()


def delete_person_by_id(id):
    try:
        sql = "DELETE FROM person WHERE Id = %s"
        c.execute(sql, id)
        conn.commit()
        print_table()
    except Exception:
        print ("Something wrong happened")


def print_person_by_id(id):