예제 #1
0
 def __init__(self):
     # MySQL configurations
     mysql = MySQL()
     app.config['MYSQL_DATABASE_USER'] = '******'
     app.config['MYSQL_DATABASE_PASSWORD'] = '******'
     app.config['MYSQL_DATABASE_DB'] = 'qh_logistics'
     app.config['MYSQL_DATABASE_HOST'] = 'localhost'
     mysql.init_app(app)
     self.conn = mysql.connect()
예제 #2
0
	def startConnection(self):
		mysql = MySQL()
		# MySQL configurations
		self.app.config['MYSQL_DATABASE_USER'] = self.username
		self.app.config['MYSQL_DATABASE_PASSWORD'] = self.password
		self.app.config['MYSQL_DATABASE_DB'] = self.dbname
		self.app.config['MYSQL_DATABASE_HOST'] = self.host
		mysql.init_app(self.app)
		Dbconn = mysql.connect()
		return Dbconn
예제 #3
0
class DataBase():

    # 커넥션 맺자
    def __init__(self):
        self.mysql = MySQL()
        self.mysql.init_app(app)
        self.connection = self.mysql.connect()
        self.connection.autocommit(True)

    # 쿼리 실행
    def execute(self, query):
        cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute(query)

        return cursor
예제 #4
0
파일: setup.py 프로젝트: lessaworld/SQLpie
    def create_database(app, sqlpie_config):
        config_mysql = MySQL()
        env = sqlpie.DBSetup.environment()
        curr_db_config = sqlpie_config['db'][env]['mysql_database_db']
        app.config['MYSQL_DATABASE_DB'] = "mysql"
        app.config['MYSQL_DATABASE_PASSWORD'] = sqlpie_config['db'][env]['mysql_database_password']
        app.config['MYSQL_DATABASE_USER'] = sqlpie_config['db'][env]['mysql_database_user']
        app.config['MYSQL_DATABASE_HOST'] = sqlpie_config['db'][env]['mysql_database_host']
        app.config['MYSQL_DATABASE_PORT'] = sqlpie_config['db'][env]['mysql_database_port']
        config_mysql.init_app(app)

        try:
            local_conn = config_mysql.connect()
            local_cursor = local_conn.cursor()
            drop_db_sql_command = "DROP DATABASE IF EXISTS SQLpie_%s; " % (env);
            local_cursor.execute(drop_db_sql_command)
            local_cursor.close()

            local_cursor = local_conn.cursor()
            create_db_sql_command = "CREATE DATABASE SQLpie_%s; " % (env);
            use_db_sql_command = "USE SQLpie_%s; " % (env);
            f = open("sqlpie/db/sql/schema.sql","r")
            schema = f.read()
            sql_commands = create_db_sql_command + use_db_sql_command + schema
            local_cursor.execute(sql_commands)
            local_cursor.close()

            local_cursor = local_conn.cursor()
            f = open("sqlpie/db/sql/seed.sql","r")
            seed_commands = f.read()
            sql_commands = use_db_sql_command + seed_commands
            local_cursor.execute(seed_commands)
            local_conn.commit()
            print "Successfully created SQLpie_%s database on %s server." % (env, sqlpie_config['db'][env]['mysql_database_host'])
        except Exception as e:
            print "[Error] creating SQLpie_%s database on %s server." % (env, sqlpie_config['db'][env]['mysql_database_host'])
            if sqlpie.Util.is_debug():
                traceback.print_tb(sys.exc_info()[2])
        finally:
            try:
                local_cursor.close()
                local_conn.close()
            except:
                pass

        app.config['MYSQL_DATABASE_DB']    = curr_db_config
예제 #5
0
파일: desafio.py 프로젝트: Danilo/desafio
            if err.args[0] == 1146:
                try:
                    create_table = ("CREATE TABLE Users "
                    "(facebookId BIGINT NOT NULL, first_name VARCHAR(50), last_name VARCHAR(50), name VARCHAR(100), PRIMARY KEY(facebookId))")
                    cursor.execute(create_table)
                    cursor.execute(add_user)
                    connector.commit()
                    cursor.close()
                    connector.close()
                    return 'HTTP 201\n'
                except connector.Error, err:
                    return ("MySQL Error: {}\n".format(err))
            else:
                return ("MySQL Error: {}\n".format(err))
    elif request.method == 'GET':
        connector = mysql.connect()
        cursor = connector.cursor()
        query = ("SELECT * FROM Users LIMIT %s") % request.args.get('limit', '')

        try:
            cursor.execute(query)
            return "HTTP 200\n%s\n" % (json.dumps(cursor.fetchall(), indent=2))
        except connector.Error, err:
            return ("MySQL Error: {}\n".format(err))

@app.route('/person/<facebookId>/', methods=['DELETE'])
def deletion(facebookId):

    if request.method == 'DELETE':
        connector = mysql.connect()
        cursor = connector.cursor()
예제 #6
0
from flask import Flask
from config import Config
from flaskext.mysql import MySQL
import os

app = Flask(__name__)
app.config.from_object(Config)

MySQL = MySQL()
MySQL.init_app(app)

# Database config
app.config['MYSQL_DATABASE_HOST'] = os.getenv('MYSQL_DATABASE_HOST')
app.config['MYSQL_DATABASE_PORT'] = int(os.getenv('MYSQL_DATABASE_PORT'))
app.config['MYSQL_DATABASE_USER'] = os.getenv('MYSQL_DATABASE_USER')
app.config['MYSQL_DATABASE_PASSWORD'] = os.getenv('MYSQL_DATABASE_PASSWORD')
app.config['MYSQL_DATABASE_DB'] = os.getenv('MYSQL_DATABASE_DB')
conn = MySQL.connect()

from app import routes
    def post(self):
        try:
            # Parse the arguments
            #Take arguments from the form.
            parser = reqparse.RequestParser()
            parser.add_argument('customer_id',
                                type=str,
                                help='Customers unique id')
            parser.add_argument('personal_id',
                                type=str,
                                help='Pesonal id of the customer')
            parser.add_argument('amount', type=str, help='Aisey hi ')
            parser.add_argument(
                'interest',
                type=str,
                help='Interest of the user viz. car,house,etc.')
            parser.add_argument('years', type=str, help='Kitnay saal kay liye')
            parser.add_argument('verification',
                                type=str,
                                help='Verified or not')
            parser.add_argument('purpose',
                                type=str,
                                help='Car lena gaadi lena?')
            args = parser.parse_args()
            customer_id = args['customer_id']
            personal_id = args['personal_id']
            amount = args['amount']
            amount = float(amount)
            print("lll" + str(amount))
            interest = args['interest']
            purpose = interest
            duration = args['years']
            #duration=36
            verification = args['verification']
            #Argument taking part done.
            print("till here-2")
            #MySQL connectivity and execute query.
            mysql1 = MySQL()
            app.config['MYSQL_DATABASE_USER'] = '******'
            app.config['MYSQL_DATABASE_PASSWORD'] = ''
            app.config['MYSQL_DATABASE_DB'] = 'techm_db'
            app.config['MYSQL_DATABASE_HOST'] = 'localhost'
            app.config['MYSQL_DATABASE_PORT'] = 3306
            mysql1.init_app(app)
            conn = mysql1.connect()
            cursor = conn.cursor()
            cursor.execute("Select * from cust_banking where ind={}".format(
                str(customer_id)))
            row1 = cursor.fetchall()
            cursor.execute("Select * from cust_personal where ind={}".format(
                str(personal_id)))
            row2 = cursor.fetchall()
            #MySQL connectivity and query done.
            print("till here-1")
            #Seperate the tuple returned from the query in required fields.All the names of variables are in accordance with csv
            dti = row1[0][1]
            delinq_2yrs = row1[0][2]
            inq_last_6mths = row1[0][3]
            open_acc = row1[0][4]
            total_acc = row1[0][5]
            revol_bal = row1[0][6]
            revol_util = row1[0][7]
            fico_range_high = row1[0][8]
            fico_range_low = row1[0][9]
            fico_average = row1[0][10]

            emp_length = row2[0][1]
            annual_inc = row2[0][2]
            pub_rec = row2[0][3]
            home_ownership = row2[0][4]

            #calculate remaining values
            print("till here0")

            installment = float(amount) / float(duration)
            print("till here1")
            emp_len = -1
            if emp_length == "< 1 year":
                emp_len = 0
            elif emp_length == "1 year":
                emp_len = 1
            elif emp_length == "2 years":
                emp_len = 2
            elif emp_length == "3 years":
                emp_len = 3
            elif emp_length == "4 years":
                emp_len = 4
            elif emp_length == "5 years":
                emp_len = 5
            elif emp_length == "6 years":
                emp_len = 6
            elif emp_length == "7 years":
                emp_len = 7
            elif emp_length == "8 years":
                emp_len = 8
            elif emp_length == "9 years":
                emp_len = 9
            elif emp_length == "10+ years":
                emp_len = 10
            else:
                emp_len = -1

            verification_1 = 0
            verification_2 = 0
            verification_3 = 0
            if verification == 1:
                verification_1 = 1
            elif verification == 2:
                verification_2 = 1
            elif verification == 3:
                verification_3 = 1

            purpose_1 = 0
            purpose_2 = 0
            purpose_3 = 0
            purpose_4 = 0
            purpose_5 = 0
            purpose_6 = 0
            purpose_7 = 0
            purpose_8 = 0
            purpose_9 = 0
            purpose_10 = 0
            purpose_11 = 0
            purpose_12 = 0
            purpose_13 = 0
            purpose_14 = 0
            if purpose == "1":
                purpose_1 = 1
            elif purpose == "2":
                purpose_2 = 1
            elif purpose == "3":
                purpose_3 = 1
            elif purpose == "4":
                purpose_4 = 1
            elif purpose == "5":
                purpose_5 = 1
            elif purpose == "6":
                purpose_6 = 1
            elif purpose == "7":
                purpose_7 = 1
            elif purpose == "8":
                purpose_8 = 1
            elif purpose == "9":
                purpose_9 = 1
            elif purpose == "10":
                purpose_10 = 1
            elif purpose == "11":
                purpose_11 = 1
            elif purpose == "12":
                purpose_12 = 1
            elif purpose == "13":
                purpose_13 = 1
            elif purpose == "14":
                purpose_14 = 1

            print("till here2")
            home_ownership_1 = 0
            home_ownership_2 = 0
            home_ownership_3 = 0
            home_ownership_4 = 0
            home_ownership_5 = 0
            if home_ownership == "MORTGAGE":
                home_ownership_1 = 1
            elif home_ownership == "NONE":
                home_ownership_2 = 1
            elif home_ownership == "OTHER":
                home_ownership_3 = 1
            elif home_ownership == "OWN":
                home_ownership_4 = 1
            elif home_ownership == "RENT":
                home_ownership_5 = 1

            duration_36 = 0
            duration_60 = 0
            if duration == 36:
                duration_36 = 1
            else:
                duration_60 = 1

            revol_util = revol_util[:len(revol_util) - 1]
            revol_util = float(revol_util)
            print(revol_util)
            print("till here3")
            model = load_model('my_model_loan.h5')
            x = np.vstack([[
                float(amount),
                float(installment),
                float(emp_len),
                float(annual_inc),
                float(dti),
                float(delinq_2yrs),
                float(inq_last_6mths),
                float(open_acc),
                float(pub_rec),
                float(revol_bal),
                float(revol_util),
                float(total_acc),
                float(fico_average),
                float(home_ownership_1),
                float(home_ownership_2),
                float(home_ownership_3),
                float(home_ownership_4),
                float(home_ownership_5),
                float(verification_1),
                float(verification_2),
                float(verification_3),
                float(purpose_1),
                float(purpose_2),
                float(purpose_3),
                float(purpose_4),
                float(purpose_5),
                float(purpose_6),
                float(purpose_7),
                float(purpose_8),
                float(purpose_9),
                float(purpose_10),
                float(purpose_11),
                float(purpose_12),
                float(purpose_13),
                float(purpose_14),
                float(duration_36),
                float(duration_60)
            ]])
            #x=np.vstack([[7200.0, 233.65, 5, 80000.0, 8.96, 0.0, 2.0, 6.0, 0.0, 3565.0,70.0, 1ss8.0, 707.0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0,0,0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]])
            y = model.predict(x)
            p = 2
            for i in range(0, len(y)):
                p = g(y[i])
            msg = ""
            if p == 1:
                msg = "Loan accepted Congratulations"
            else:
                msg = "Rejected"
            #If you receive this message then everything worked well and you are good to go.
            return {'message': msg}

        except Exception as e:
            return {'error': str(e)}
예제 #8
0
from datetime import timedelta, datetime
import random, string
from forms import loginForm

mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.secret_key = ''.join(
    random.choice(string.ascii_letters + string.digits)
    for _ in range(int(32)))
mysql.init_app(app)

db = mysql.connect()


@app.route('/', methods=["GET", "POST"])
def login():
    form = loginForm()

    if request.method == 'POST':
        if (form.validate() == False):
            flash('All fields are required.')
            return render_template('landing.html', **locals())
        else:
            name = request.form.get("name", "")
            return render_template('return.html', **locals())
    elif (request.method == 'GET'):
        return render_template('landing.html', **locals())
예제 #9
0
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

#Set up database connection
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'finance'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
connectionDB = mysql.connect()
cursor = connectionDB.cursor()

# API key for searching quote information
"""
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")
    """


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    cash = user_request.request_cash(session["user_id"], cursor=cursor)
    # get user quote info list
예제 #10
0
def create_app():
    app = flask.Flask(__name__)
    app.config["DEBUG"] = True

    CORS(app)
    bcrypt = Bcrypt(app)
    mysql = MySQL()

    # config mysql connection
    app.config['MYSQL_DATABASE_USER'] = configDB.name
    app.config['MYSQL_DATABASE_PASSWORD'] = configDB.passw
    app.config['MYSQL_DATABASE_DB'] = configDB.db
    app.config['MYSQL_DATABASE_HOST'] = configDB.host

    mysql.init_app(app)

    conn = mysql.connect()
    pointer = conn.cursor()

    # config flask_mail
    mail = Mail(app)
    app.config['MAIL_SERVER'] = configMail.mail_server
    app.config['MAIL_PORT'] = configMail.mail_port
    app.config['MAIL_USERNAME'] = configMail.username
    app.config['MAIL_PASSWORD'] = configMail.password
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True
    mail = Mail(app)

    @app.route('/', methods=['GET'])
    def home():
        return "Hello, flask app works ! - Thainq"

    @app.route('/register', methods=['POST'])
    def register():
        req = request.get_json()
        # handle body request
        if not req["username"] or len(req["username"]) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_REQUIRED
                }), 400)
        if not req["password"] or len(req["password"]) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.PASSWORD_REQUIRED
                }), 400)
        if not req["email"] or len(req["email"]) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.EMAIL_REQUIRED
                }), 400)

        name = req["username"]
        pw = req["password"]
        email = req['email']

        # check isExist username & email
        if len(allRepos.select_id_by_username(name)) > 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.ACOUNT_EXIST
                }), 400)
        if len(allRepos.select_id_by_email(email)) > 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.EMAIL_EXIST
                }), 400)

        pw_hashed = bcrypt.generate_password_hash(
            req["password"]).decode('utf-8').encode('ascii', 'ignore')

        record_for_inserting = (name, pw_hashed, email)
        allRepos.insert_for_register(record_for_inserting)

        msg = Message('Your account info',
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = "username: "******" pass: "******"username")
        pw = req.get("password")
        if not name or not pw or (not name and not pw):
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_PASSWORD_REQUIRED
                }), 400)
        # check user exist
        if allRepos.select_user_by_username(name).rowcount == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_NOT_FOUND
                }), 404)
        # check db
        cursor = allRepos.select_password_by_username(name)
        passInDb = cursor.fetchone()
        success = bcrypt.check_password_hash(passInDb[0], pw)
        if success:
            return make_response(
                jsonify({
                    'code': 200,
                    'message': message.LOGIN_SUCCESS
                }), 200)
        return make_response(
            jsonify({
                'code': 400,
                'message': message.WRONG_PASSWORD
            }), 400)

    @app.route('/forgotPass', methods=['POST'])
    def forgotPass():
        req = request.get_json()
        name = req.get("username")
        email = req.get("email")

        # handle body request
        if not name and not email:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.ALL_FIELDS_REQUIRED
                }), 400)
        if not name or len(name) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_REQUIRED
                }), 400)
        if not email or len(email) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.EMAIL_REQUIRED
                }), 400)
        # check username existed
        if allRepos.select_password_by_username(name).rowcount == 0:
            return make_response(
                jsonify({
                    'code': 404,
                    'message': message.USERNAME_NOT_FOUND
                }), 404)
        # check email === username
        cursor = allRepos.select_email_by_username(name)
        fetchDB = cursor.fetchone()
        current = fetchDB[0].encode('ascii', 'ignore')
        if email != current:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_EMAIL_WRONG
                }), 400)
        # make new password for user
        new_pass = generateRandomPass.generatePassword(8)
        hashed_new_pass = bcrypt.generate_password_hash(new_pass)
        allRepos.update_password(hashed_new_pass, email)
        # handle mailing
        msg = Message('Password changed! ',
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = "Your new password is: " + new_pass
        mail.send(msg)
        return make_response(
            jsonify({
                'code': 200,
                'message': message.SEND_NEW_PASS
            }), 200)

    @app.route('/changePass', methods=['POST'])
    def changePass():
        req = request.get_json()
        name = req.get("username")
        pw = req.get("password")
        new_pw = req.get("newpassword")

        # handle body request
        if not name and not pw and not new_pw:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.ALL_FIELDS_REQUIRED
                }), 400)
        if not name or len(name) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.USERNAME_REQUIRED
                }), 400)
        if not pw or len(pw) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.PASSWORD_REQUIRED
                }), 400)
        if not new_pw or len(new_pw) == 0:
            return make_response(
                jsonify({
                    'code': 400,
                    'message': message.NEW_PASSWORD_REQUIRED
                }), 400)

        passInDb = allRepos.select_password_by_username(name).fetchone()
        success = bcrypt.check_password_hash(passInDb[0], pw)
        if not success:
            return make_response(
                jsonify({
                    'stt': 400,
                    'message': message.WRONG_USERNAME_PASSWORD
                }), 400)
        if pw == new_pw:
            return make_response(
                jsonify({
                    'stt': 400,
                    'message': message.OLD_NEW_PASSWORD_DIFFERENT
                }), 400)
        hashed_new_pass = bcrypt.generate_password_hash(new_pw)
        allRepos.update_password_by_username(hashed_new_pass, name)
        return make_response(
            jsonify({
                'code': 200,
                'message': message.CHANGE_PASSWORD_SUCCESS
            }), 200)

    @app.route('/delete_for_testing', methods=['POST'])
    def delete():
        req = request.get_json()
        name = req["username"]
        pointer.execute("delete from user where username = %s", name)
        conn.commit()
        return make_response(
            jsonify({
                'code': 200,
                'message': request.get_json()
            }), 200)

    return app
예제 #11
0
from flask import Flask
import json
from flaskext.mysql import MySQL 


MS = MySQL() 

#connect to the DB
db1 = MS.connect("localhost","root","barry1")
cursor = db1.cursor()
sql = 'CREATE DATABASE IF NOT EXISTS how_lit_db'
cursor.execute(sql)


# create table
cursor.execute("SET sql_notes = 0; ")
cursor.execute("create table IF NOT EXISTS Artist Rankings (Artist varchar(70),Rank varchar(20));")
cursor.execute("SET sql_notes = 1; ")

#insert data
cursor.execute("insert into test (Artist,Rank) values('The Weeknd','100')")

# Commit changes in the database
db.commit()

# disconnect from server
db.close()
예제 #12
0
class DBGateway:
    def __init__(self, app):
        self.mysql = MySQL()

        # MySQL configurations
        app.config['MYSQL_DATABASE_USER'] = db_user
        app.config['MYSQL_DATABASE_PASSWORD'] = db_password
        app.config['MYSQL_DATABASE_DB'] = db_name
        app.config['MYSQL_DATABASE_HOST'] = db_host
        self.mysql.init_app(app)

        self.conn = self.mysql.connect()
        self.cursor = self.conn.cursor()

        self.class_to_table = {
            "BOOK": "prints",
            "MAGAZINE": "prints",
            "MOVIE": "medias",
            "MUSIC": "medias"
        }

    def get_all(self, Class, email=None, dictionary=None):
        res = []
        if dictionary:
            fields = ''
            for key, value in dictionary.items():
                if value.isdigit():
                    fields = fields + " AND " + key + '=' + value
                else:
                    fields = fields + " AND " + key + '=' + "\'" + value + "\'"
            if Class.__name__.upper() == "BOOK" or Class.__name__.upper(
            ) == "MAGAZINE":
                type = 'prints'
            else:
                type = 'medias'

            query = "SELECT * FROM %s INNER JOIN items ON itemId = id WHERE items.itemType = '%s' %s;" % (
                type, Class.__name__.upper(), fields)

        elif email:
            query = "SELECT * FROM library.items INNER JOIN loans ON items.id = loans.itemId WHERE items.itemType = '%s' AND loans.clientId = '%s';" % (
                Class.__name__.upper(), email)
        else:
            query = "SELECT * FROM library.items WHERE items.itemType = '%s';" % Class.__name__.upper(
            )

        print("QUERY:   " + query)
        self.cursor.execute(query)
        ids = [res[0] for res in self.cursor.fetchall()]
        if len(ids) == 0:
            return []
        ids_str = self.arr_to_mysqlarr(ids)
        query = "SELECT * FROM library.%s WHERE itemId IN %s;" % (
            self.class_to_table[Class.__name__.upper()], ids_str)
        print(query)
        self.cursor.execute(query)
        # print(self.cursor.fetchall())
        data = self.cursor.fetchall()
        args = [d[0] for d in self.cursor.description]
        for record in data:
            kwargs = {}
            for i in range(len(args)):
                kwargs[args[i]] = record[i]
            item = Class(**kwargs)
            res.append(item)
        return res

    def arr_to_mysqlarr(self, arr):
        return "(" + str(arr)[1:len(str(arr)) - 1] + ")"

    def insert_item(self, item):
        """INSERT INTO prints (itemId,title,publisher,year_published,language,isbn_10,isbn_13) -- Magazines
        VALUES
        (16,'Design News','UBM','1946','English','9000119407','987-9000119407');
        """
        vals = [val for key, val in item.__dict__.items()]
        vals = vals[:-1]
        item_query = "INSERT INTO items (loanable, itemType) VALUES ('%s', '%s')" % (
            'N' if type(item).__name__.upper() == 'MAGAZINE' else 'Y',
            type(item).__name__.upper())
        print(item_query)
        self.cursor.execute(item_query)
        vals[0] = self.cursor.lastrowid
        for i in range(len(vals)):
            if i == 0:
                continue
            if vals[i].isdigit() and len(vals[i]) < 10:
                vals[i] = int(vals[i])

        fields = [key for key, val in item.__dict__.items()]
        fields.remove("object_class")
        fields[0] = "itemId"
        fields = self.arr_to_mysqlarr(fields).replace("'", "")
        vals = self.arr_to_mysqlarr(vals)
        query = "INSERT INTO %s %s VALUES %s;" % (
            self.class_to_table[type(item).__name__.upper()], fields, vals)
        print(query)
        self.cursor.execute(query)
        self.conn.commit()

    def remove_item(self, id):
        self.cursor.execute("DELETE FROM items WHERE id = %s" % id)
        self.conn.commit()

    def process_return(self, id):
        self.cursor.execute("DELETE FROM loans WHERE itemId = %s" % id)
        self.conn.commit()

    def verify_login(self, user, password):
        h = hashlib.md5(bytes(password, "utf-8"))
        pwd = h.hexdigest()
        self.cursor.execute(
            "SELECT * FROM library.users WHERE email = '%s' AND pswd = '%s'" %
            (user, pwd))
        self.cursor.fetchall()
        return self.cursor.rowcount != 0

    def verify_admin(self, email):
        self.cursor.execute(
            "SELECT * FROM users WHERE email = '%s' AND privilegeLevel = 'ADMIN'"
            % email)
        self.cursor.fetchall()
        return self.cursor.rowcount != 0

    def register_user(self, request):
        fname = request.form['firstname']
        lname = request.form['lastname']
        address_1 = request.form['address-1']
        address_2 = request.form['address-2']
        city = request.form['city']
        state = request.form['state']
        postal = request.form['postal']
        country = request.form['country']
        email = request.form['email']
        password = request.form['psw']
        psw_repeat = request.form['psw-repeat']
        phone = request.form['phone']

        if password != psw_repeat:
            return "Passwords do not match"
        h = hashlib.md5(bytes(password, "utf-8"))
        pwd = h.hexdigest()
        self.cursor.execute(
            "INSERT INTO library.users (firstName, lastName, address, email, phone, pswd) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')"
            % (fname, lname, address_1 + ' ' + address_2 + ' ' + city + ' ' +
               state + ' ' + postal + ' ' + country, email, str(phone), pwd))
        self.conn.commit()
        return "registration successful"

    def register_user_admin(self, request):
        fname = request.form['firstname']
        lname = request.form['lastname']
        address_1 = request.form['address-1']
        address_2 = request.form['address-2']
        city = request.form['city']
        state = request.form['state']
        postal = request.form['postal']
        country = request.form['country']
        email = request.form['email']
        password = request.form['psw']
        psw_repeat = request.form['psw-repeat']
        phone = request.form['phone']
        typeuser = '******'
        if password != psw_repeat:
            return "Passwords do not match"
        h = hashlib.md5(bytes(password, "utf-8"))
        pwd = h.hexdigest()
        self.cursor.execute(
            "INSERT INTO library.users (firstName, lastName, address, email, phone, pswd, privilegeLevel) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')"
            % (fname, lname, address_1 + ' ' + address_2 + ' ' +
               city + ' ' + state + ' ' + postal + ' ' + country, email,
               str(phone), pwd, typeuser))
        self.conn.commit()
        return "registration successful"

    def get_loans_for_user(self, c, email):
        return self.get_all(c, email)

    def get_item_by_id(self, id):
        query = "SELECT itemType FROM library.items WHERE id=%s" % (
            id)  #get itemType

        self.cursor.execute(query)
        itemType = self.cursor.fetchone()

        if 'BOOK' in itemType:
            query = "SELECT * FROM library.prints WHERE itemId=%s" % (id)
            self.cursor.execute(query)
            t = self.cursor.fetchone()

            item = Book(t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8])
            print()

            return item

        elif 'MAGAZINE' in itemType:
            query = "SELECT * FROM library.prints WHERE itemId=%s" % (id)
            self.cursor.execute(query)
            t = self.cursor.fetchone()

            item = Magazine(t[1], t[4], t[5], t[6], t[7], t[8])
            return item

        elif 'MUSIC' in itemType:
            query = "SELECT * FROM library.medias WHERE itemId=%s" % (id)
            self.cursor.execute(query)
            t = self.cursor.fetchone()

            item = Music(t[1], t[2], t[3], t[4], t[5], t[6])
            return item

        elif 'MOVIE' in itemType:
            query = "SELECT * FROM library.medias WHERE itemId=%s" % (id)
            self.cursor.execute(query)
            t = self.cursor.fetchone()

            item = Movie(t[2], t[3], t[7], t[8], t[9], t[10], t[11], t[12],
                         t[13])
            return item

        else:
            print('Error retrieving itemType.')
            return False

        return item

    def loan_item(self, user, itemID):
        self.cursor.execute(
            "SELECT loanable FROM items WHERE id= %s AND loanable='Y'" %
            itemID)
        self.cursor.fetchall()
        if self.cursor.rowcount == 0:
            return False
        try:
            self.cursor.execute(
                "INSERT INTO library.loans (clientId, itemId, loan_date) VALUES ('%s', '%s', '%s')"
                %
                (user, itemID, datetime.datetime.today().strftime('%Y-%m-%d')))
            self.conn.commit()
        except:
            return False
        return True

    def edit_item(self, item_type, fields, item_id):
        if item_type == 'Book':
            query = "UPDATE library.prints SET title='%s', author='%s', num_pages='%s', publisher='%s', year_published=%s, language='%s', isbn_10=%s, isbn_13='%s' WHERE itemId=%s;" % (
                fields['Title'], fields['Author'], fields['Pages'],
                fields['Publisher'], fields['Year'], fields['Language'],
                fields['ISBN_10'], fields['ISBN_13'], item_id)
            print(query)
            self.cursor.execute(query)
            self.conn.commit()
            return True
        if item_type == 'Magazine':
            query = "UPDATE library.prints SET title='%s', publisher='%s', year_published=%s, language='%s', isbn_10=%s, isbn_13='%s' WHERE itemId=%s;" % (
                fields['Title'], fields['Publisher'], fields['Year'],
                fields['Language'], fields['ISBN_10'], fields['ISBN_13'],
                item_id)
            self.cursor.execute(query)
            self.conn.commit()
            return True
        if item_type == 'Movie':
            query = "UPDATE library.medias SET title='%s', release_date='%s', director='%s', producer='%s', actors='%s', languages='%s', subtitles='%s', dubbed='%s', runtime=%s WHERE itemId=%s;" % (
                fields['Title'], fields['ReleaseDate'], fields['Director'],
                fields['Producers'], fields['Actors'], fields['Languages'],
                fields['Subtitles'], fields['Dubbed'], fields['Run Time'],
                item_id)
            self.cursor.execute(query)
            self.conn.commit()
            return True
        if item_type == 'Music':
            query = "UPDATE library.medias SET mediaType='%s', title='%s', release_date='%s', artist='%s', label='%s', asin='%s' WHERE itemId=%s;" % (
                fields['Type'], fields['Title'], fields['ReleaseDate'],
                fields['Artist'], fields['Label'], fields['ASIN'], item_id)
            self.cursor.execute(query)
            self.conn.commit()
            return True
예제 #13
0
파일: app.py 프로젝트: GpAston/DockRM
from flask import Flask, render_template, request
import requests
from flaskext.mysql import MySQL
import hashlib

monApp = Flask(__name__)
monApp.config.from_object( 'config' )

mysql = MySQL()
mysql.init_app( monApp )
connector = mysql.connect()
cursor = connector.cursor()
mavar = ({
    "nom":"pagies",
    "prenom":"leo",
    "afficher":"oui"
},{
    "nom":"leman",
    "prenom":"maxence",
    "afficher":"non"
})

def hash_fonct(passwords):
    var1 = hashlib.sha512(passwords.encode( "utf-8" ))
    hashcode = var1.hexdigest()
    return(hashcode)

@monApp.route( "/" )
def fhello():
    return render_template("index.html", datas=mavar)
예제 #14
0
''' Using Flask framework '''
from flask import Flask, render_template, request, redirect
from flaskext.mysql import MySQL

APP = Flask(__name__)
APP.config["DEBUG"] = True  # Only include this while you are testing your app
MYSQL = MySQL(APP)

# MySQL configurations
APP.config['MYSQL_DATABASE_USER'] = '******'
APP.config['MYSQL_DATABASE_PASSWORD'] = '******'
APP.config['MYSQL_DATABASE_DB'] = 'Vanmo'
APP.config['MYSQL_DATABASE_HOST'] = '209.2.220.201'
MYSQL.init_app(APP)

CONN = MYSQL.connect()
CURSOR = CONN.cursor()


@APP.route("/")
def home():
    ''' load landing page '''
    #cursor.execute("SELECT VERSION()")
    #data = cursor.fetchone()
    #return "Database version : %s " % data
    return render_template("index.html")


@APP.route("/login", methods=['POST', 'GET'])
def login():
    ''' check database to verify user data and login if allowed '''
예제 #15
0

sio = socketio.Server(async_mode = 'eventlet')
app = Flask(__name__)
app.wsgi_app = socketio.Middleware(sio, app.wsgi_app)
app.config['SECRET_KEY'] = 'secret!'
app.config['JSON_SORT_KEYS'] = False

for key,val in dbConfig.items():
    app.config[key] = val

mysql = MySQL( cursorclass = pymysql.cursors.DictCursor )
mysql.init_app(app)


mysql.connect()
mysql_cursor = mysql.get_db().cursor()

@app.route("/")
def hello():
    from model.UserModel import UserModel
    dbmodel = UserModel(app)
    data = dbmodel.user_list()
    return jsonify({'code': 200, 'message': '', 'data': data})
    # return render_template('index.html')

sio.register_namespace(MyCustomNamespace('/test'))
sio.register_namespace(MyCustomNamespace('/buyGrab'))

if __name__ == '__main__':
    # deploy as an eventlet WSGI server
예제 #16
0
from flask import Flask, json
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'start_for_x'

mysql.init_app(app)

# Insert into table
conn = mysql.connect()
cursor = conn.cursor()

data = json.loads(open('news.json').read())

for line in data:
    startup_name = line['company']
    news = line['news']
    for new in news:
        try:
            cursor.execute('''INSERT INTO startup_news (link, title, startup_name) VALUES (%s, %s, %s)''',
                   (new['link'], new['title'], startup_name))
            conn.commit()
        except:
            print new['link']
예제 #17
0
def get_connect():
    mysql = MySQL(app)
    mysql.init_app(app)
    cursor = mysql.connect().cursor()
    cursor.execute("show databases;")
    print cursor.fetchall()
예제 #18
0
파일: app.py 프로젝트: alexarirok/Flask101
from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
#from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__)
alex = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'Bucketlist'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
alex.init_app(app)

conn = alex.connect()
cursor = conn.cursor()
cursor.callproc('sp_createUser', ("name", "email", "password"))

data = cursor.fetchall()

if len(data) is 0:
    conn.commit()
    return json.dumps({'message': 'User created successfully !'})
else:
    return json.dumps({'error': str(data[0])})


@app.route("/")
def main():
    return render_template("index.html")

예제 #19
0
from flask import current_app
from flaskext.mysql import MySQL


mysql_mod = MySQL()
mysql_mod.init_app(current_app)
mysql = mysql_mod.connect()
예제 #20
0
from flask import Flask, url_for, request, json, jsonify
from flaskext.mysql import MySQL
from geopy.geocoders import Nominatim, GoogleV3
import time, random
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyMarkup, Update, CallbackQuery
import requests, telegram
app = Flask(__name__)
mysql = MySQL(app)
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'project'
app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1'
mysql.init_app(app)
mysql.connect().autocommit(True)
token = "289036724:AAHY09oWw0Ohn8-uu7-5Ah0tiY8yWfhPLgQ"
bot = telegram.Bot(token)


@app.route('/289036724:AAHY09oWw0Ohn8-uu7-5Ah0tiY8yWfhPLgQ/webhook',
           methods=['get', 'post'])
def token():
    content = request.json
    #	kgp="Kharagpur"
    db = mysql.connect()
    cursor = db.cursor()
    print content
    if "callback_query" in content:
        chat_id = str(content['callback_query']['message']['chat']['id'])

    elif 'location' in content['message']:  #.index(['location']) is not None:
        chat_id = content['message']['chat']['id']
예제 #21
0
# coding:utf-8
'''
Created on 19/1/2015

@author: PC30
'''

from flaskext.mysql import MySQL  #importar mysql
from flask import Flask  #esta se importa manualmente

mysql = MySQL()  #llamando a mysql
app = Flask(__name__)  #instanciando a flask
app.config['MYSQL_DATABASE_USER'] = '******'  #nombre de usuario
app.config['MYSQL_DATABASE_PASSWORD'] = '******'  #contrase�a de ususario
app.config['MYSQL_DATABASE_DB'] = 'ventas'  #nombre de la base de datos
app.config['MYSQL_DATABASE_HOST'] = 'localhost'  #servidor donde se encuantra
mysql.init_app(app)

con = mysql.connect().cursor()  #se hace la coneccion IMPORTANTE!!!
con.execute(" select * from personas ")  #se hace la consulta
report = con.fetchall(
)  #funcion que hace que extrae todo desde la base de datos
print report

con = mysql.connect().cursor()  #se hace la coneccion IMPORTANTE!!!
con.execute(" select * from trabajador ")  #se hace la consulta
reportt = con.fetchall(
)  #funcion que hace que extrae todo desde la base de datos
print reportt
예제 #22
0
'''

from flask import Flask, render_template, request
from flaskext.mysql import MySQL

app = Flask(__name__)

db = MySQL()

app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'sakila'
app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1'
db.init_app(app)

conn = db.connect()
cursor = conn.cursor()
query = 'Select title from film where film_id < 5;'


#Extracts data from a cursor
def extractData(cursor):
    data = []
    for item in cursor:
        data.append(item)
    return data


cursor.execute(query)
data = extractData(cursor)
예제 #23
0
def start_database():
    db = MySQL()
    db.init_app(app)
    conn = db.connect()
    conn.autocommit(1)
    return conn
예제 #24
0
class Database():
    def __init__(self, app):
        self.mysql = MySQL()
        app.config['MYSQL_DATABASE_USER'] = '******'
        app.config['MYSQL_DATABASE_PASSWORD'] = '******'
        app.config['MYSQL_DATABASE_DB'] = 'project'
        app.config['MYSQL_DATABASE_HOST'] = 'localhost'
        self.mysql.init_app(app)
        conn = self.mysql.connect()
        self.cursor = conn.cursor

    def get_data(self, sql, params=None):
        conn = self.mysql.connect()
        cursor = conn.cursor()
        # print("getting data")
        try:
            # print(sql)
            cursor.execute(sql, params)
        except Exception as e:
            print(e)
            return False

        result = cursor.fetchall()
        data = []
        for row in result:
            data.append(list(row))
        cursor.close()
        conn.close()

        return data

    def set_data(self, sql, params=None):
        conn = self.mysql.connect()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, params)
            conn.commit()
        except Exception as e:
            print(e)
            return False

        cursor.close()
        conn.close()

    def get_dates(self):
        days = []
        data = self.get_data(
            "SELECT cast(A.measurementTime as date) FROM feeder as F left join amount A on A.amountID=F.amountID;"
        )
        for i in range(0, len(data)):
            date = data[i][0]
            if (date != None):
                dayOfWeek = calendar.day_name[date.weekday()]
                monthOfYear = calendar.month_name[date.month]
                day = ("{0},&nbsp{1}&nbsp{2}&nbsp{3}".format(
                    dayOfWeek, date.day, monthOfYear, date.year))
                if (day not in days):
                    days.append(day)
        return days

    def get_hours(self, params=None):
        hours = []
        sql = "SELECT TIME(A.measurementTime) FROM feeder as F left join amount A on A.amountID=F.amountID WHERE cast(A.measurementTime as date) like %(date)s;"
        data = self.get_data(sql, {'date': params})
        for i in range(0, len(data)):
            if (data[i][0] != None):
                time = self.timedelta2hour(data[i][0])
                hours.append(str(datetime.time(time[0], time[1]))[0:5])
        return hours

    def timedelta2hour(self, timedelta):
        hours, min_sec = divmod(timedelta.seconds, 3600)
        minutes, seconds = divmod(min_sec, 60)
        return [hours, minutes]

    def get_weights(self, params=None):
        weights = []
        sql = "SELECT A.foodAmount FROM feeder as F left join amount A on A.amountID=F.amountID WHERE cast(A.measurementTime as date) like %(date)s;"
        data = self.get_data(sql, {'date': params})
        for i in range(0, len(data)):
            if (data[i][0] != None):
                weights.append(str(data[i][0]))
        return weights
예제 #25
0
class MSQLConn:
    def __init__(self, app):
        self.mysql = MySQL(app)
        app.config['MYSQL_DATABASE_USER'] = '******'
        app.config['MYSQL_DATABASE_PASSWORD'] = '******'
        app.config['MYSQL_DATABASE_DB'] = 'ChatDB'
        app.config['MYSQL_DATABASE_HOST'] = 'localhost'
        self.mysql.init_app(app)
        self.conn = self.mysql.connect()

    def __del__(self):
        if self.conn is not None:
            self.conn.close()

    def have_room_with_title(self, title):
        cursor = self.conn.cursor()
        try:
            query = "SELECT * FROM rooms WHERE name = %s"
            cursor.execute(query, (title, ))
            return len(cursor.fetchall()) > 0
        finally:
            cursor.close()

    def create_room(self, title):
        cursor = self.conn.cursor()
        try:
            query = "INSERT INTO rooms (name) VALUES (%s)"
            result = cursor.execute(query, (title, ))
            if result:
                self.conn.commit()
            return result
        finally:
            cursor.close()

    def get_rooms(self):
        result = []
        cursor = self.conn.cursor()
        try:
            query = "SELECT * FROM rooms"
            cursor.execute(query)
            data = cursor.fetchall()
        finally:
            cursor.close()

        for room in data:
            room_dict = {
                'Title': room[1],
            }
            result.append(room_dict)
        return result

    def have_user_with_email(self, email):
        cursor = self.conn.cursor()
        try:
            query = "SELECT * FROM users WHERE login = %s"
            cursor.execute(query, (email, ))
            return len(cursor.fetchall()) > 0
        finally:
            cursor.close()

    def have_user_with_name(self, name):
        cursor = self.conn.cursor()
        try:
            query = "SELECT * FROM users WHERE name = %s"
            cursor.execute(query, (name, ))
            return len(cursor.fetchall()) > 0
        finally:
            cursor.close()

    def add_new_user(self, user):
        cursor = self.conn.cursor()
        try:
            query = "INSERT INTO users (name, login, password) VALUES (%s, %s, %s)"
            result = cursor.execute(
                query,
                (user.name, user.login, generate_password_hash(user.password)))
            if result:
                self.conn.commit()
            return result
        finally:
            cursor.close()

    def get_user_with_login(self, login):
        cursor = self.conn.cursor()
        try:
            query = "SELECT * FROM users WHERE login = %s"
            cursor.execute(query, (login, ))
            tmp_user = cursor.fetchone()
            if len(tmp_user) > 0:
                return SimpleUser(tmp_user[0], tmp_user[1], tmp_user[2],
                                  tmp_user[3])
        finally:
            cursor.close()
# Import Flask modules
from flask import Flask, jsonify, abort, request, make_response
from flaskext.mysql import MySQL

# Create an object named app
app = Flask(__name__)

# Configure sqlite database
app.config['MYSQL_DATABASE_HOST'] = 'database'
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'bookstore_db'
app.config['MYSQL_DATABASE_PORT'] = 3306
mysql = MySQL()
mysql.init_app(app)
connection = mysql.connect()
connection.autocommit(True)
cursor = connection.cursor()


# Write a function named `init_bookstore_db` which initilazes the bookstore db
# Create books table within sqlite db and populate with sample data
# Execute the code below only once.
def init_bookstore_db():
    drop_table = 'DROP TABLE IF EXISTS bookstore_db.books;'
    books_table = """
    CREATE TABLE bookstore_db.books(
    book_id INT NOT NULL AUTO_INCREMENT,
    title VARCHAR(100) NOT NULL,
    author VARCHAR(100),
    is_sold BOOLEAN NOT NULL DEFAULT 0,
예제 #27
0
class database:
    def __init__(self, app, config):
        self.mysql = MySQL()

        app.config['MYSQL_DATABASE_USER'] = config.db_username
        app.config['MYSQL_DATABASE_PASSWORD'] = config.db_pass
        app.config['MYSQL_DATABASE_DB'] = config.db_name
        app.config['MYSQL_DATABASE_HOST'] = config.db_host

        self.mysql.init_app(app)
        self.conn = None

    def mysql_connect(self):
        self.conn = self.mysql.connect()
        return self.conn.cursor()

    def mysql_finalize(self):
        self.conn.commit()
        self.conn.close()

    def get_user_id(self, username):
        cursor = self.mysql_connect()
        try:
            cmd = "select id_user from users where login = %s"
            cursor.execute(cmd, (username))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))

    def user_register(self, username, email, password):
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `users`( `login`, `pass`, `email`) VALUES (%s,%s,%s)"
            cursor.execute(cmd, (username, password, email))
            return True
        except:
            return False
        finally:
            self.mysql_finalize()

    def check_if_username_is_free(self, username):
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT id_user FROM `users` WHERE login = %s"
            cursor.execute(cmd, (username))
            return cursor.fetchone() is None
        except:
            return False
        finally:
            self.mysql_finalize()

    def get_user_data(self, user_id):
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT id_user, login, email FROM `users` WHERE id_user = %s"
            cursor.execute(cmd, (user_id))
            return cursor.fetchall()
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def get_user_privileges(self, user_id):
        cursor = self.mysql_connect()
        try:
            cmd = "select role from `users` where id_user = %s"
            cursor.execute(cmd, (user_id))
            return cursor.fetchone()[0]
        except:
            return False
        finally:
            self.mysql_finalize()

    def delete_account(self, user_id):
        # sql delete account
        cursor = self.mysql_connect()
        try:
            cmd = "DELETE FROM `users` WHERE id_user = %s"
            cursor.execute(cmd, (user_id))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def get_survey_list(self):
        # zwraca wszystkie aktywne do wypelnienia ankiety
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT id_survey, survey_description, datetime FROM `survey` where active = 1"
            cursor.execute(cmd)
            return cursor.fetchall()
        except:
            return False
        finally:
            self.mysql_finalize()

    def get_specific_question_name(self, id_question):
        cursor = self.mysql_connect()
        try:
            cmd = "select * from `questionbase` where id_question = %s"
            cursor.execute(cmd, (id_question))
            return cursor.fetchall()[0]
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def get_specific_survey_id(self, name):
        cursor = self.mysql_connect()
        try:
            cmd = "select id_survey from `survey` where survey_description = %s"
            cursor.execute(cmd, (name))
            return cursor.fetchall()[0][0]
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    # works
    def get_specific_survey(self, survey_id):
        # jw zwraca cala ankiete  z pytaniami do wypelnienia z mozliwymi odpowiedziami
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT * FROM `survey` " \
                  "JOIN surveytemplate ON survey.id_survey = surveytemplate.id_survey " \
                  "JOIN questionbase ON surveytemplate.id_question = questionbase.id_question " \
                  "JOIN possibleanswers ON questionbase.id_question = possibleanswers.id_question " \
                  "WHERE survey.id_survey = %s"
            cursor.execute(cmd, (survey_id))
            return cursor.fetchall()
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def add_question_to_questionbase(self, question_description,
                                     id_question_type):
        # dodaje pytanie do bazy pytan wraz z typem pytania (1 jednokrotny wybor, 2 wielokrotny wybor)
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `questionbase`(`question_description`, `id_questiontype`) VALUES (%s, %s)"
            cursor.execute(cmd, (question_description, id_question_type))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))

    # works
    def get_all_question_in_questionbase(self):
        # zwraca tylko dostepne pytania (te ktore moga byc uzyte w tworzeniu ankiety)
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT * FROM `questionbase` where active = 1"
            cursor.execute(cmd)
            return cursor.fetchall()
        except:
            return False

    def get_question_from_questionbase_by_tag(self, tag_description):
        # listuje pytania po tagacah
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT * FROM questiontags JOIN tags ON questiontags.id_tag = tags.id_tag JOIN questionbase ON questiontags.id_question = questionbase.id_question WHERE tag_description = %s"
            cursor.execute(cmd, (tag_description, ))
            return cursor.fetchone()
        except:
            # do something
            return

    # works
    def get_possible_answers(self, id_question):
        # zwraca mozliwe odpowiedzi dla pytania
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT `id_answer`, `id_question`, `answerdescription` FROM `possibleanswers` WHERE id_question = %s and active = 1"
            cursor.execute(cmd, (id_question))
            return cursor.fetchall()
        except:
            return False

    def add_possible_answers(self, id_question, answerdescription):
        # dodaje mozliwe odpowiedzi do pytania
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `possibleanswers`(`id_question`, `answerdescription`) VALUES (%s, %s)"
            cursor.execute(cmd, (id_question, answerdescription))
            return cursor.fetchone()
        except:
            # do something
            return redirect(url_for('msg_page'))

    def delete_possible_answer(self, id_answer):
        # admin oznacza mozliwa odpowiedz jako nieaktywna (actve = 0)
        cursor = self.mysql_connect()
        try:
            cmd = "UPDATE `possibleanswers` SET active = 0 where id_answer = %s"
            cursor.execute(cmd, (id_answer))
            return cursor.fetchone()
        except:
            # do something
            return redirect(url_for('msg_page'))

    # works
    def get_user_password(self, user_id):
        cursor = self.mysql_connect()
        cmd = "SELECT `pass` FROM `users` WHERE id_user = %s"
        try:
            cursor.execute(cmd, (user_id))
            return cursor.fetchone()[0]
        except:
            return False
        finally:
            self.mysql_finalize()

    def get_survey_owner(self, survey_id):
        # zwraca wlasciciela ankiety, to zwraca tworce szablonu a nie usera ktory wypelnil ankiete
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT  `id_user` FROM `survey` WHERE id_survey = %s"
            cursor.execute(cmd, (survey_id))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))

    def get_survey_respondent(self, completedsurvey_id):
        # zwraca usera ktory wypelnil ankiete (respondenta)
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT  `id_user` FROM `completedsurvey` WHERE id_completedsurvey = %s"
            cursor.execute(cmd, (completedsurvey_id))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))

    def get_question_owner(self, survey_id):
        return False

    def is_user_have_any_questions(self, user_id):
        return False

    def is_user_have_any_surveys(self, user_id):
        # zwraca liczbe ankiet (wzorccow) usera
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT  * FROM `survey` WHERE id_user = %s"
            cursor.execute(cmd, (user_id))
            return cursor.fetchone()
        except:
            return False

    def is_user_have_any_completed_surveys(self, user_id):
        # zwraca liczbe ankiet wypelnionych przez usera
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT  count(id_completedsurvey) AS NumberOfCompletedSurveys FROM `completedsurvey` WHERE id_user = = %s"
            cursor.execute(cmd, (user_id))
            return cursor.fetchone()
        except:
            return False

    def get_completedanswers_in_completedsurvey(self, completedsurvey_id):
        # zwraca, id szablonu, id pytan, id odpoodpowiedzi dla wypelnionej ankiety
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT * FROM `completedanswers` WHERE id_completedsurvey = %s"
            cursor.execute(cmd, (completedsurvey_id))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))

    def get_completed_surveys(self, user_id):
        # zwraca wypelnione ankiety przez uzytownika (lista completedsurvey.id_completedsurvey, survey.id_survey, survey.survey_description, completedsurvey.datetime, completedsurvey.id_user)
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT completedsurvey.id_completedsurvey, survey.id_survey, survey.survey_description, completedsurvey.datetime, completedsurvey.id_user FROM `survey` left Join `completedsurvey` ON survey.id_survey = completedsurvey.id_survey WHERE completedsurvey.id_user = %s"
            cursor.execute(cmd, (user_id))
            completed_surveys = cursor.fetchall()
            return completed_surveys
        except:
            return redirect(url_for('msg_page'))

    def delete_question(self, question_id):
        # admin usuwa pytanie z bazy (tak naprawde wylaczymy pytanie active na '0', baza jest na ta chwile jednoczesnie slownikiem, wiec wywalenie rekordu usunie go z wypelnionych juz ankiet)
        cursor = self.mysql_connect()
        try:
            cmd = "UPDATE `questionbase` SET `active` = 0 WHERE id_question = %s"
            cursor.execute(cmd, question_id)
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def get_question_from_questionbase_by_id(self, question_id):
        cursor = self.mysql_connect()
        try:
            cmd = "SELECT * FROM `questionbase` where id_question = %s and active = 1"
            cursor.execute(cmd, (question_id))
            return cursor.fetchall()
        except:
            return False

    def get_correct_answer_for_specific_question(self, question_id):
        pass

    def add_completed_survey(self, id_survey, id_user):
        # wypelniona ankiete (uzupelnia tabele completedsurvey) add_completed_survey i add_completed_answers_for_completed_survey nalezy wywolac w momencie submit ( w podanej kolejnosci)# add_completed_answers_for_completed_survey nalezy wywolac dla kazdej dodwanej odpowiedzi #add_completed_survey dla ankiety trzeba wykonac tylko raz na samym poczatku po submit
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `completedsurvey`(`id_survey`, `id_user`) VALUES (%s, %s)"
            cursor.execute(cmd, (id_survey, id_user))
            return cursor.fetchone()
        except:
            # do something
            return redirect(url_for('msg_page'))

    def add_completed_answers_for_completed_survey(self, id_surveytemplate,
                                                   id_question, id_answer):
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `completedanswers` (id_surveytemplate, id_question, id_answer, id_completedsurvey) VALUES (%s, %s, %s, (SELECT MAX(id_completedsurvey) from `completedsurvey` ))"
            cursor.execute(cmd, (id_surveytemplate, id_question, id_answer))
            return cursor.fetchone()
        except:
            # do something
            return redirect(url_for('msg_page'))

    def add_survey(self, id_user, survey_description):
        # tworzy nowa ankiete bez pytan sam "kontener"
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `survey`(`id_user`, `survey_description`) VALUES (%s, %s)"
            cursor.execute(cmd, (id_user, survey_description))
            return cursor.fetchone()
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def add_surveytemplate(self, id_survey, id_question):
        # dodaje pytania do szablonu utworzonej ankiety (tej ktora zostala utworzona za pomoca add_survey)
        cursor = self.mysql_connect()
        try:
            cmd = "INSERT INTO `surveytemplate`(`id_survey`, `id_question`) VALUES (%s, %s)"
            cursor.execute(cmd, (id_survey, id_question))
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def delete_survey(self, id):
        cursor = self.mysql_connect()
        try:
            cmd = "delete from `surveytemplate` where id_survey = %s"
            cursor.execute(cmd, (id))
            cmd = "delete from `survey` where id_survey = %s"
            cursor.execute(cmd, (id))
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()

    def disable_survey(self, id):
        cursor = self.mysql_connect()
        try:
            cmd = "update `survey` set active = 0 where id_survey = %s"
            cursor.execute(cmd, (id))
        except:
            return redirect(url_for('msg_page'))
        finally:
            self.mysql_finalize()
예제 #28
0
UPLOAD_FOLDER = 'D:/python/flask/homelessnessing/uploads'
okay_ext = set(['wav'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

mysql = MySQL()

app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'basiclogin'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

conn = mysql.connect()

#DONE
#Check if there's an extension, and if it's valid
def file_okay(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in okay_ext

#DONE
#Check with the database if an email/password entry exists
def verify_acc(email, password):
	
	cursor = conn.cursor()
	args = [email, password]
	cursor.callproc('getacc', args)

	res = cursor.fetchall()
예제 #29
0
from flask import Flask, render_template, request, redirect, session
from flaskext.mysql import MySQL
from socket import gethostname
app = Flask(__name__)

mysql = MySQL()

#configurations
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'orsaydb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

conn = mysql.connect()  #connection variable

cursor = conn.cursor()


@app.route('/', methods=['GET', 'POST'])
def home():

    if request.method == 'POST':  #accepts post request from the home route
        return redirect('/products')

    result = cursor.execute("SELECT DISTINCT category FROM product_table;")
    #fetching all categories from database
    if result > 0:
        categories = cursor.fetchall()
        return render_template('home.html', categories=categories)
        #rendering home.html and sending the list of unique categories to it
예제 #30
0
mysql = MySQL()
app  = Flask(__name__)

DB = "smartdoor"
HOST = "10.129.23.101"
USER = "******"
PSWD = "door!@#"

app.config['MYSQL_DATABASE_USER'] = USER
app.config['MYSQL_DATABASE_PASSWORD'] = PSWD
app.config['MYSQL_DATABASE_DB'] = DB
app.config['MYSQL_DATABASE_HOST'] = HOST
mysql.init_app(app)

con = mysql.connect() # database connection
cur = con.cursor() #dataset cursor handle

def update_presence_info(name):
	'''
		update whether user is present in the room or not
		1 - present
		0 - not present
	'''
	print "updating presence information"
	sql = "select ispresent from presence_data where name='%s'" %name
	print sql
	cur.execute(sql)
	res = cur.fetchone()
	print res
	presence_status = res[0] 
예제 #31
0
from forms import AddIncidentForm
import time
from Queries import Queries
from flask_table import Table, Col
from tables import ResourcesInUse, ResourcesInUse_Item, ResourcesInUseWithDistance, ResourcesInUseWithDistance_Item, GenerateReport_Table, GenerateReport_Item, ResourceStatus_ResourcesInUse, GeneResourceStatus_ResourcesInUse_Item, ResourceStatus_ResourcesRequestedByMe, GeneResourceStatus_ResourcesRequestedByMe_Item, ResourceStatus_ResourceRequestsReceivedByMe, ResourceStatus_ResourceRequestsReceivedByMe_Item, ResourceStatus_RepairsScheduledAndInProgress, ResourceStatus_RepairsScheduledAndInProgress_Item, ResourcesInUseStatus_Item, ResourcesInUseStatus

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'team49'
app.config['MYSQL_DATABASE_HOST'] = 'team49.db.9939976.hostedresource.com'

mysql.init_app(app)
cursor = mysql.connect().cursor()

# set the secret key.  keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'


@app.route("/")
def root():
    return redirect(url_for('login'))


@app.route("/action", methods=['GET', 'POST'])
def parseAction():
    if request.method == "POST":
        print "**************************swwsaw"
        _type = request.args.get('type')
예제 #32
0
from flask import Flask, jsonify, render_template, url_for, redirect
import jinja2
from flask_sql import app
from flaskext.mysql import MySQL

mysql = MySQL()

db_configs = {'MYSQL_DATABASE_USER':'******', 'MYSQL_DATABASE_PASSWORD': '******', 'MYSQL_DATABASE_DB': 'matt', 'MYSQL_DATABASE_HOST': 'localhost'}

for i, j in db_configs.items():
    app.config[i] = j

mysql.init_app(app)
#print app.config

conn = mysql.connect()
cursor = mysql.connect().cursor()

cursor.execute("SELECT first, last from people")
data = cursor.fetchall()

l_dicts = []
h = [u'first', u'last']
for i in data:
    strings = [j.encode('utf8') for j in i]
    a = dict(zip(h, i))
    a['first'] = "<a href=/people/"+a['first']+">"+a['first']+"</a>"
    l_dicts.append(a)
예제 #33
0
class TasksDistributorDB:
    def __init__(self, app):
        self.mysql = MySQL()
        self.mysql.init_app(app)

    def get_all_rows(self, table):
        try:
            connection = self.mysql.connect()
            cursor = connection.cursor()

            query = "SELECT * FROM {}".format(table)
            cursor.execute(query)
            return cursor.fetchall()
        except connector.Error as error:
            print(error)
            return []
        finally:
            cursor.close()
            connection.close()

    def create_task(self, project_id, executor_id, story_point):
        try:
            connection = self.mysql.connect()
            cursor = connection.cursor()

            projects = self.get_all_rows('Projects')
            tasks = self.get_all_rows('Tasks')
            tasks_in_project = [t for t in tasks if str(t[1]) == project_id]
            new_task = len(tasks_in_project) + 1

            query = """
				INSERT INTO Tasks (
					project_id, executor_id, name, 
					description, story_point
				) 
				VALUES (%s, %s, %s, %s, %s)
			"""
            dbargs = (
                project_id,
                executor_id,
                'Task {}'.format(new_task),
                "It is task's description {}".format(new_task),
                story_point,
            )
            cursor.execute(query, dbargs)
            connection.commit()

            return cursor.lastrowid
        except connector.Error as error:
            print(error)
            return -1
        finally:
            cursor.close()
            connection.close()

    def find_executor_id(self, project_id):
        try:
            connection = self.mysql.connect()
            cursor = connection.cursor()

            query = """
				SELECT mins.executor_id, SUM(mins.story_point) as min FROM (
					SELECT available_executors.executor_id, story_point FROM Tasks 
					RIGHT OUTER JOIN (
						SELECT executor_id FROM ExecutorsProjects 
						WHERE project_id = %s
					) as available_executors 
					ON Tasks.executor_id = available_executors.executor_id
				) as mins 
				GROUP BY mins.executor_id ORDER BY min ASC LIMIT 1;
			"""
            dbargs = (project_id, )
            cursor.execute(query, dbargs)
            db_executor = cursor.fetchall()
            return db_executor[0][0]
        except connector.Error as error:
            print(error)
            return -1
        finally:
            cursor.close()
            connection.close()
예제 #34
0
from libgral import ObtenerFecha, FechaHora
import sys
from flask import session

db = None
cursor = None
mysql = MySQL()

try:
    app = flask.Flask(__name__)
    app.config['MYSQL_DATABASE_USER'] = '******'
    app.config['MYSQL_DATABASE_PASSWORD'] = '******'
    app.config['MYSQL_DATABASE_DB'] = 'kernotek'
    app.config['MYSQL_DATABASE_HOST'] = 'localhost'
    mysql.init_app(app)
    db = mysql.connect()
    cursor = db.cursor()
except:
    print "ERROR NO SE PUEDE ACCESAR A LA BASE DE DATOS \nREVISAR CONFIGURACION"
    sys.exit(0)


def makeConnection():
    global db 
    global cursor
    db = mysql.connect()
    cursor = db.cursor()


def closeConnection():
    global db
예제 #35
0
from flask import Flask,flash, redirect, render_template, request, session, abort, url_for, jsonify
from flaskext.mysql import MySQL
from flask_api import FlaskAPI

import numpy as np


mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'team1305'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)
connect = mysql.connect()

cursor_user =connect.cursor()
cursor_user.execute("SELECT * from users")
data_user = cursor_user.fetchall()
# print data_user
cursor_monan = connect.cursor()
cursor_monan.execute("SELECT * from monan")
data_monan = cursor_monan.fetchall()
# print data_monan
cursor_buaan = connect.cursor()
cursor_buaan.execute("SELECT * from buaan")
data_buaan = cursor_buaan.fetchall()


@app.route('/api_get/',methods=['GET'])
예제 #36
0
파일: PinGT.py 프로젝트: vemal911/Pin-GT
app.config.update(dict(
    DEBUG=True,
    SECRET_KEY='development key',
    USERNAME='******',
    PASSWORD='******',
    MYSQL_DATABASE_HOST='localhost',
    MYSQL_DATABASE_PORT=3306,
    MYSQL_DATABASE_USER='******',
    MYSQL_DATABASE_PASSWORD='',
    MYSQL_DATABASE_DB='PIN'
))

app.config.from_object(__name__)
db = MySQL()
db.init_app(app)
conn = db.connect()

def get_cursor():
    """Connects to the specific database."""
    return conn.cursor()

def commit():
    conn.commit()

def init_db():
    with app.open_resource('schema.sql', mode='r') as f:
        get_cursor().executescript(f.read())
    commit()

@app.route('/')
def show_entries():
예제 #37
0
from flask_api import status
from os import system

app = Flask(__name__)
mySql = MySQL()

config = {}
execfile("settings.conf", config)

app.config['MYSQL_DATABASE_USER'] = config['user']
app.config['MYSQL_DATABASE_PASSWORD'] = config['password']
app.config['MYSQL_DATABASE_DB'] = config['database']
app.config['MYSQL_DATABASE_HOST'] = config['host']
mySql.init_app(app)

conn = mySql.connect()

@app.route("/led", methods=['POST'])
def led():
    print(request)
    _message = request.json['message']
    try:
        cursor = conn.cursor()
        cursor.execute("insert into Messages(message) values (%s)", _message)
        conn.commit()
        system('python ledbadge.py effect=left speed=5 "'+_message+'"')
        cursor.close()
    except conn.IntegrityError:
        return jsonify({'status': 'Failed'}), status.HTTP_500_INTERNAL_SERVER_ERROR
    return jsonify({'status': 'ok'})