def startdb(inapp):
    mysql = MySQL()
    inapp.config['MYSQL_DATABASE_USER'] = '******'
    inapp.config['MYSQL_DATABASE_PASSWORD'] = '******'
    inapp.config['MYSQL_DATABASE_DB'] = 'EmpData'
    inapp.config['MYSQL_DATABASE_HOST'] = 'localhost'
    mysql.init_app(inapp)
Beispiel #2
0
class DataBase:

    def __init__(self):
        self.mysql = MySQL()
        self.mysql.init_app(app)

    def get_mysql(self):
        return self.mysql
Beispiel #3
0
 def conexion(self):
     mysql = MySQL()
     control = Flask(__name__)
     control.config['MYSQL_DATABASE_USER'] = '******'
     control.config['MYSQL_DATABASE_PASSWORD'] = '******'
     control.config['MYSQL_DATABASE_DB'] = 'wtec_webapp'
     control.config['MYSQL_DATABASE_HOST'] = '192.168.227.135'
     mysql.init_app(control)
     return mysql
Beispiel #4
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()
Beispiel #5
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
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
Beispiel #7
0
    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
Beispiel #8
0
    def init(self, app):
        self.mysql = MySQL()
        params = self.get_database_params()
        app.config['MYSQL_DATABASE_USER'] = params['MYSQL_DATABASE_USER']
        app.config['MYSQL_DATABASE_PASSWORD'] = params['MYSQL_DATABASE_PASSWORD']
        app.config['MYSQL_DATABASE_DB'] = params['MYSQL_DATABASE_DB']
        app.config['MYSQL_DATABASE_HOST'] = params['MYSQL_DATABASE_HOST']
        app.config['MYSQL_DATABASE_PORT'] = params['MYSQL_DATABASE_PORT']

        self.mysql.init_app(app)
Beispiel #9
0
from flask import Flask, render_template, request, json, redirect, session, flash
from flaskext.mysql import MySQL
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)

app.secret_key = 'why would I tell you my secret key?'
mysql = MySQL()  #       #       #       #       #       #       #       #
app.config[
    'MYSQL_DATABASE_USER'] = '******'  #   Create my MySQL Object named mysql                  #
app.config[
    'MYSQL_DATABASE_PASSWORD'] = '******'  #                                                       #
app.config[
    'MYSQL_DATABASE_DB'] = 'what'  #   MySQL configurations (Todo move to config.file)     #
app.config[
    'MYSQL_DATABASE_HOST'] = 'localhost'  #                                                       #
mysql.init_app(app)  #           Start MySQL Application inside Flask        #
#       #       #       #       #       #       #       #

#       #       #       #       Function endpoints Frontpage      #       #       #       #      #       #       #       #


#When user hits signup DO::
@app.route('/test')
def test():
    return render_template('test.html')


@app.route('/')
def index():
    return render_template('test.html')
Beispiel #10
0
from flask import Flask
from random import randint
from flaskext.mysql import MySQL

mysql = MySQL()
application = Flask(__name__)
application.debug = True


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


@application.route('/')
def hello_world():
    return 'Hello World!'


@application.route('/test')
def test():
    # print str(randint(1, 100))
    return str(randint(1, 100))


@application.route("/dbtest")
def dbtest():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT * from testtable")
Beispiel #11
0
from flask import current_app
from flaskext.mysql import MySQL


mysql_mod = MySQL()
mysql_mod.init_app(current_app)
mysql = mysql_mod.connect()
from flask import Flask
from flask_socketio import SocketIO
from flask_session import Session
from flask_mail import Mail
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor  #For using dictionary cursor
import os
from flask_cors import CORS, cross_origin

socketio = SocketIO()

mysql = MySQL(cursorclass=DictCursor)
# mysql = MySQL()
mail = Mail()


def create_app(debug=False):
    """Create an application."""
    app = Flask(__name__)
    CORS(app, origins='http://localhost:5000')

    app.config['FILEDIR'] = 'app/static/_files/'
    app.config['CDN_URL'] = 'http://d1cpyz6yyb1kha.cloudfront.net'
    app.config['SECRET_KEY'] = 'gjr39dkjn344_!67#'
    app.config['MYSQL_DATABASE_USER'] = '******'
    app.config['MYSQL_DATABASE_PASSWORD'] = '******'
    app.config['MYSQL_DATABASE_DB'] = 'Chatapp'
    app.config[
        'MYSQL_DATABASE_HOST'] = 'anychat.cvjaewaab6rt.us-east-1.rds.amazonaws.com'
    app.config['MYSQL_DATABASE_CHARSET'] = 'utf8mb4'
    app.config.from_pyfile('config.cfg')
from flask import Flask, render_template, request, url_for, redirect
from flaskext.mysql import MySQL
from os import path, makedirs
from werkzeug.utils import secure_filename
from database import *

app = Flask(__name__)
bd = MySQL()
bd.init_app(app)

upload_dir = ('static')
makedirs(upload_dir, exist_ok=True)
# verificar se o funcionário está logado type 1 = gerente / type 0 = vendedor
login_type = None
login_name = None


@app.route('/')
def home(erro=None):
    conn = bd.connect()
    cursor = conn.cursor()
    vips = show_vips(cursor)
    cursor.close()
    conn.close()
    return render_template('index.html')


@app.route('/cadastro_carro')
def insercao(erro=None):
    if login_type:
        return render_template('inserir.html', erro=erro, logado=login_type)
from flask import Flask,session,render_template,request,jsonify, redirect,url_for
import main

#importing package to connect flask to mysql database
from flaskext.mysql import MySQL	


#flask app
nlpsql = Flask(__name__)
nlpsql.secret_key = 'nlpsql key'


mysql = MySQL(nlpsql)

#Database Configuration
nlpsql.config['MYSQL_DATABASE_USER'] = '******'
nlpsql.config['MYSQL_DATABASE_PASSWORD'] = '******'
nlpsql.config['MYSQL_DATABASE_DB'] = 'nlpproj'
nlpsql.config['MYSQL_DATABASE_HOST'] = 'localhost'

#start flask app
mysql.init_app(nlpsql)

#route for home
@nlpsql.route('/')
def home():
	if 'error' in session:	
		error=session['error']
		session.pop('error',None)
	else:	
		error=''
Beispiel #15
0
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")

Beispiel #16
0
from flaskext.mysql import MySQL
from flaskext.mysql import pymysql
mysql = MySQL(cursorclass=pymysql.cursors.DictCursor)
Beispiel #17
0
def create_app(test_config=None):
	# create and configure the app
	app = Flask(__name__, instance_relative_config=True)
	app.config['MYSQL_DATABASE_HOST'] = 'localhost'
	app.config['MYSQL_DATABASE_USER'] = '******'
	app.config['MYSQL_DATABASE_PASSWORD'] = '******'
	app.config['MYSQL_DATABASE_DB'] = 'tododb'
	mysql = MySQL(app)
	mysql.init_app(app)
	
	# ensure the instance folder exists
	try:
		os.makedirs(app.instance_path)
	except OSError:
		pass
	
	
	#MODEL STRATS HERE

	def get_from_db(name):
		conn=mysql.connect()
		cur=conn.cursor()
		cur.execute("SELECT work FROM todolisttable WHERE name = %s",(name))
		data=cur.fetchall()
		data1=[A[0] for A in data]
		conn.commit()
		if len(data1) == 0 :
			return None
		return data1


	def get_todos_by_name(name):
		try:
			return get_from_db(name)
		except:
			return None
	
	def add_in_list(name,work):
		conn=mysql.connect()
		cur = conn.cursor()
		cur.execute("INSERT INTO todolisttable(name, work) VALUES (%s, %s)", (name, work))
		conn.commit()
		#mysql.connection.commit()
		#cur.close()
		return 

	def verify_before_add(name,work):
		return add_in_list(name,work)

	#MODELS ENDS HERE
	
	#...............................................................................................................#


	#CONTROLLER STARTS HERE
	

	@app.route('/add_todo')
	def add_todo():
		name=request.args.get('name')
		work=request.args.get('work')
		verify_before_add(name,work)
		return 'ADDED SUCCESFULLY'


	# a simple page that list my todos
	@app.route('/todos')
	def todos():
		name = request.args.get('name')
		dolist = get_todos_by_name(name)
		if dolist!=None :
			return render_template('todo_view.html',worklist = dolist)
		else :
			return render_template('404.html'),404
	#...................................................................................................................#		

	return app
Beispiel #18
0
# -*- coding: utf-8 -*-
from flask import Flask, render_template
#importamos librería de sqlalchemy
#from flask_sqlalchemy import SQLAlchemy
from flaskext.mysql import MySQL

app = Flask(__name__)

mysql = MySQL()
#establecemos cadena de conexión con la base de datos
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'trips'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
#Postgressql configuration
#app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://127.0.0.1:5432/blog"

#creamos una instancia de la base de datos
#db = SQLAlchemy(app)
cursor = mysql.get_db().cursor()


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(45), nullable=False)
    email = db.Column(db.String(255), nullable=False, unique=True)


class Post(db.Model):
Beispiel #19
0
from flask import Flask
from flask_restful import Api
from flaskext.mysql import MySQL
import config
from api_get_user import GetUser
from api_register import RegisterUser

mysql = MySQL()
app = Flask(__name__)
api = Api(app)
mysql.init_app(config.db_config(app))

api.add_resource(GetUser, '/get_user', resource_class_kwargs={'mysql': mysql})
api.add_resource(RegisterUser,
                 '/register_user',
                 resource_class_kwargs={'mysql': mysql})

if __name__ == '__main__':
    app.run(debug=True)
import os
import sys

# Import flask and template operators & SQLAlchemy
from flask import Flask, render_template
from flaskext.mysql import MySQL

# Define the WSGI application object & Configurations
weblogin = Flask(__name__)
weblogin.config.from_object('config')

# Database
mysql = MySQL()
mysql.init_app(weblogin)


# Configure Secret Key
def install_secret_key(weblogin, filename='secret_key'):
    # Configure the SECRET_KEY from a file
    # in the instance directory.

    # If the file does not exist, print instructions
    # to create it from a shell with a random key,
    # then exit.
    filename = os.path.join(weblogin.instance_path, filename)
    try:
        weblogin.config['SECRET_KEY'] = open(filename, 'rb').read()
    except IOError:
        print('Error: No secret key. Create it with:')
        full_path = os.path.dirname(filename)
        if not os.path.isdir(full_path):
Beispiel #21
0
def create_app():
    mysql = MySQL()
    app = Flask(__name__)
    app.secret_key = 'webtechproject'
    app_data = {
        "name": "Disease Identification Using Images",
        "description": "Flask application for WT-2 Project",
        "author": "Harsh Garg, Gaurav Peswani, Hardik Mahipal Surana",
        "html_title": "Home",
        "project_name": "Disease Identification Using Images",
        "keywords": "flask, webapp, machine learning"
    }

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

    photos = UploadSet('photos', IMAGES)
    app.config['UPLOADED_PHOTOS_DEST'] = './static/'
    configure_uploads(app, photos)

    @app.route('/')
    def index():
        return render_template('index.html', app_data=app_data)

    @app.route("/login", methods=["GET", "POST"])
    def login():
        if (request.method == "GET"):

            return render_template("login.html")

        elif (request.method == "POST"):

            POST_USERNAME = str(request.form["username"])
            POST_PASSWORD = str(request.form["password"])

            print(POST_USERNAME)
            print(POST_PASSWORD)

            session["username"] = POST_USERNAME

            query = "SELECT name from register where username='******'"
            print("query is ", query)
            conn = mysql.connect()
            cursor = conn.cursor()
            res = cursor.execute(query)
            data = cursor.fetchall()
            print("data for details of user is ", data)
            nameOfUser = data[0][0]
            session["nameOfUser"] = nameOfUser

            print("session['username'] is ", session["username"])
            # Make DB query to see if User with 'email' and 'acc_type'
            # has the same password as in the DB.
            result = models.loginCheck(mysql, POST_USERNAME, POST_PASSWORD)
            # if (result=="Error"):
            #     flash("Error")
            print("result is ", result)

            if (result == True):
                return redirect(url_for("classify_tomato"))
            else:
                flash('wrong password!')
                return redirect(url_for("login"))
        else:
            flash("Error")

    @app.route('/b1')
    def b1():
        return render_template('b1.html', app_data=app_data)

    # # getting our trained model from a file we created earlier
    model = pickle.load(open("./model/model.pkl", "rb"), encoding='utf-8')

    @app.route("/register", methods=["GET", "POST"])
    def register_user():
        if (request.method == "GET"):
            # print("nameList is ",nameList)
            # print("emailList is ",emailList)
            # print("usernamesList is ",usernamesList)
            # print("passwordList is ",passwordList)
            return render_template("register.html", title="Patient")

        elif (request.method == "POST"):
            newUserDict = {
                "name": str(request.form["name"]),
                "email": str(request.form["email"]),
                "username": str(request.form["username"]),
                "password": str(request.form["password"]),
            }

            if not models.isExistingUser(mysql, newUserDict["username"]):
                # nameList.append(newUserDict["name"])
                # emailList.append(newUserDict["email"])
                # usernamesList.append(newUserDict["username"])
                # passwordList.append(newUserDict["password"])
                res = models.insertNewUser(mysql, newUserDict)
                if (res == True):

                    return redirect(url_for("login"))
                else:
                    return redirect(url_for("register"))
            else:

                return redirect(url_for("login"))

    @app.route('/predict', methods=['POST'])
    def predict():
        #grabbing a set of wine features from the request's body
        feature_array = json.loads(request.data)['feature_array']
        # feature_array = request.get_json()['feature_array']

        #our model rates the wine based on the input array
        prediction = model.predict([feature_array]).tolist()

        #preparing a response object and storing the model's predictions
        response = {}
        response['predictions'] = prediction

        #sending our response object back as json
        return jsonify(response)

    # getting our trained model from a file we created earlier
    # model = pickle.load(open("./model/data/model_info/alexnet_trained_model.pkl","rb"), encoding='utf-8')

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

        if request.method == 'POST' and 'photo' in request.files:
            filename = photos.save(request.files['photo'])
            result = predict_disease('./static/' + filename)
            return render_template('result.html', app_data={"result": result})

        return render_template('upload.html',
                               app_data=app_data,
                               name=session["nameOfUser"])

    @app.route('/logout', methods=["GET", "POST"])
    def logout():
        print("Inside logout")
        if (request.method == "GET"
                and request.args.get("logout", "", type=int) == 1):
            try:
                session.pop("username")
            except KeyError:
                pass
            try:
                session.pop("nameOfUser")
            except:
                pass

            return redirect(url_for("login"))

        return render_template("login.html")

    # @app.route('/getDetailsOfUser', methods=['GET','POST'])
    # def getDetailsOfUser():
    #     if(request.method == 'GET'):
    #         # res = models.getDetailsOfUser(mysql,session["username"])
    #         query = "SELECT name from register where username='******'"
    #         print("query is ",query)
    #         conn = mysql.connect()
    #         cursor = conn.cursor()
    #         res = cursor.execute(query)
    #         data = cursor.fetchall()
    #         print("data for details of user is ",data)
    #         nameOfUser = data[0][0]

    #         return render_template("register.html",title="Patient")

    @app.route('/fetch_multistage', methods=['GET'])
    def fetch_multistage():
        print(request.files)
        FILES_LOC = "/home/harshgarg/Desktop/7thSem/WebTech-Project/WT-2/code/flaskr/static/text_for_msd/"
        if request.method == 'GET':
            if request.args.get("image", "", type=int) == 1:
                FILE_NAME = "images.json"
            elif request.args.get("link", "", type=int) == 1:
                FILE_NAME = "links.json"
            else:
                FILE_NAME = "content.json"
            file_ = open(FILES_LOC + FILE_NAME, 'r')
            res = file_.read()
            # print(res, type(res))
            return res
        return "Invalid fetch"

    return app
Beispiel #22
0
from flask import Flask, render_template, request, redirect, jsonify
from flaskext.mysql import MySQL
from flask_restful import Resource, Api, reqparse

#add postman chrome extension to check the requests

#create flask app
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'demoapplication'
app.config['MYSQL_PORT'] = '3306'
app.config['MYSQL_HOST'] = 'localhost'

mysql = MySQL(app)
api = Api(app)
conn = mysql.connect()
cur = conn.cursor()


#---------------------------------------------------------------------------------------------------------------------
class GetUser(Resource):
    def get(self, uid):
        cur.execute("SELECT uid,fname,lname,bdate FROM user WHERE uid=" + uid)
        rv = cur.fetchone()
        if str(rv) == "None":
            return jsonify({"status": "Not found"})
        else:
            return jsonify({
                'uid': rv[0],
                'fname': rv[1],
Beispiel #23
0
 def __init__(self):
     self.mysql = MySQL()
     self.mysql.init_app(app)
     self.connection = self.mysql.connect()
     self.connection.autocommit(True)
import requests
import json
from flask import Flask, render_template, jsonify, request
from flaskext.mysql import MySQL
import pymysql
import pymysql.cursors

app = Flask(__name__)
app.config["MYSQL_DATABASE_USER"] = "******"
app.config["MYSQL_DATABASE_DB"] = "vacunas"

mysql = MySQL(app)
mysql.connect_args["autocommit"] = True
mysql.connect_args["cursorclass"] = pymysql.cursors.DictCursor


@app.route('/')
def paciente():
    cursor = mysql.get_db().cursor()
    sql = "SELECT * FROM paciente"
    cursor.execute(sql)

    pacientes_ = cursor.fetchall()
    return render_template("pacientes.html", paciente=pacientes_)


@app.route('/vacunas')
def vacunas():
    cursor = mysql.get_db().cursor()
    sql = "SELECT * FROM vacuna"
    cursor.execute(sql)
Beispiel #25
0
from ioSpaces.MyCustomNamespace import sio, MyCustomNamespace
from flaskext.mysql import MySQL
import pymysql
from configs.database import dbConfig


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'))
Beispiel #26
0
from flask import Flask, request, send_file;
from flaskext.mysql import MySQL;
import json;
import os;

UPLOAD_FOLDER = "/User/Taejun/Documents/nexta/image"

app = Flask(__name__);
mysql = MySQL();

app.config['MYSQL_DATABASE_USER'] = '******';
app.config['MYSQL_DATABASE_PASSWORD'] = '******';
app.config['MYSQL_DATABASE_DB'] = 'nextagram';

mysql.init_app(app);

@app.route("/")
def helloWrold():
	return "helloWrold";

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

	cursor = mysql.connect().cursor();
	cursor.execute("select * from next_android_nextagram")

	result = []
	columns = tuple( [d[0] for d in cursor.description] )

	for row in cursor:
		result.append(dict(zip(columns, row)))
Beispiel #27
0
from flask import request
from flask import jsonify
from flask import make_response
from flaskext.mysql import MySQL
from werkzeug.security import check_password_hash
import os

app = Flask(__name__)

app.config['SECRET_KEY'] = os.urandom(11)
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'blogstate'

mysql = MySQL()
mysql.init_app(app)

cur = mysql.connect().cursor()


@app.route('/')
@app.route('/api')
def index():
    return 'HTTP default response'


@app.route('/api/login', methods=['POST'])
def login():
    """
    :param: u: Username
Beispiel #28
0
# -*- coding:utf-8 -*-
from flask import Flask, request, render_template, url_for, session, jsonify, redirect, json, make_response
from flaskext.mysql import MySQL
from flask_sslify import *
import lepl.apps.rfc3696
import json
import os
from passlib.hash import pbkdf2_sha256
from jinja2 import utils
from datetime import datetime

tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
email_validator = lepl.apps.rfc3696.Email()
mysql = MySQL()
app = Flask(__name__, template_folder=tmp_dir)
sslify = SSLify(app)
app.config.from_pyfile('my.cfg')
mysql.init_app(app)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'


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


@app.route("/register", methods=['POST'])
def register():
    from flask import request
    if request.method == 'POST':
        name = str(utils.escape(request.json['name']))
Beispiel #29
0
import os

# settingup the app
app = Flask(__name__)

# config
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = os.urandom(24)

# MYSQL configurations
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'green_renter_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

flaskmysql = MySQL()
flaskmysql.init_app(app)


def connect_db(flaskmysql):
    """from werkzeug.security import generate_password_hash, check_password_hash
    connecting to the database
    :param flaskmysql:
    :return:
    """
    con = flaskmysql.connect()
    return con


def get_db(flaskmysql):
    if not hasattr(g, 'mysql_db'):
Beispiel #30
0
 def __init__(self):
     self.mysql = MySQL()
     self.mysql.init_app(app)
Beispiel #31
0
def config(app):
    with open("./hertzmedia.config") as config:
        for line in config:
            configName = line[0:line.index("=")].strip()
            config = line[line.index("=") + 1:len(line)].strip()
            if (config.startswith("(int)")):
                config = config[5:]
                app.config[configName] = int(config)
            else:
                app.config[configName] = config


config(app)

db = MySQL()

db.init_app(app)

# requestParser setup
postParser = reqparse.RequestParser()
postParser.add_argument("title",
                        type=str,
                        help="the title 20 letters max",
                        required=True)
postParser.add_argument("text",
                        type=str,
                        help="the posted text",
                        required=True)
postParser.add_argument("file", type=str, help="optional file", required=False)
allowUserParser = reqparse.RequestParser()
Beispiel #32
0
import sys
from flaskext.mysql import MySQL
sys.path.insert(0, "../")
from app import app

mysql = MySQL(app)

db = mysql.connect()

cursor = db.cursor()

manifest = sys.argv[1]
sp = sys.argv[2]
sp_list = sp.split(",")
mylines = []
with open(manifest) as f:
    for line in f:
        row = line.strip().split(',')
        mylines.append(row)

count = 0
for SNP in mylines:
    try:
        SNPid = str(SNP[0])
        #Chromosome = str(SNP[1])
        #Coordination = str(SNP[2])
        Reference = str(SNP[1])
        Strand = str(SNP[2])
        SourceSeq = str(SNP[3])
        SNPArray_idSNPArray = int(SNP[4])
        sp_count = 5
def create_app(configfile='config.cfg'):
    app = Flask(__name__)
    AppConfig(app, configfile)
    app.debug = app.config['DEBUG']
    mysql = MySQL()
    pb = Pushbullet(app.config['PUSHBULLET']['apiKey'])
    app.config['MYSQL_DATABASE_HOST'] = app.config['MYSQL']['host']
    app.config['MYSQL_DATABASE_USER'] = app.config['MYSQL']['user']
    app.config['MYSQL_DATABASE_PASSWORD'] = app.config['MYSQL']['password']
    app.config['MYSQL_DATABASE_DB'] = app.config['MYSQL']['database']
    mysql.init_app(app)
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    pins = app.config['PINS']
    for pin in pins:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)

    def get_credentials():
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir, 'flask-calendar.json')

        store = oauth2client.file.Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(app.config['GMAIL']['client_secret_file'], 'https://www.googleapis.com/auth/calendar')
            flow.user_agent = 'Raspberry Flask Calendar'
            flags = tools.argparser.parse_args(args=[])
            credentials = tools.run_flow(flow, store, flags)
            print('Storing credentials to ' + credential_path)
        return credentials

    def bytes2human(n):
        symbols = (' Ko', ' Mo', ' Go', ' To', ' Po', ' Eo', ' Zo', ' Yo')
        prefix = {}
        for i, s in enumerate(symbols):
            prefix[s] = 1 << (i + 1) * 10
        for s in reversed(symbols):
            if n >= prefix[s]:
                value = float(n) / prefix[s]
                return '%.1f%s' % (value, s)
        return "%sB" % n

    def getRevision():
      revision = "ERROR"
      try:
        f = open('/proc/cpuinfo', 'r')
        for line in f:
          if line[0:8] == 'Revision':
            revision = line[11:15]
            full_revision = line[11:17]
        f.close()
      except:
        revision = "ERROR"
      if revision[0] == "a" or revision[0] == "9":
        revision = full_revision
      return revision

    def revToModel():
      rev = getRevision()
      model = [
        "0002", ["Model B Rev 1.0", "256MB"],
        "0003", ["Model B Rev 1.0 (no fuses,D14)", "256MB"],
        "0004", ["Model B Rev 2.0 (mounting holes,Sony)", "256MB"],
        "0005", ["Model B Rev 2.0 (mounting holes,Qisda)", "256MB"],
        "0006", ["Model B Rev 2.0 (mounting holes,Egoman)", "256MB"],
        "0007", ["Model A (Egoman)", "256MB"],
        "0008", ["Model A (Sony)", "256MB"],
        "0009", ["Model A (Qisda)", "256MB"],
        "000d", ["Model B Rev 2.0 (mounting holes,Egoman)", "512MB"],
        "000e", ["Model B Rev 2.0 (mounting holes,Sony)", "512MB"],
        "000f", ["Model B Rev 2.0 (mounting holes,Qisda)", "512MB"],
        "0010", ["Model B+", "512MB"],
        "0011", ["Compute Module", "512MB"],
        "0012", ["Model A+", "256MB"],
        "0014", ["Compute Module", "512MB"],
        "900092", ["PiZero", "512MB"],
        "a01041", ["Model 2B (Sony)", "1GB"],
        "a21041", ["Model 2B (Embest)", "1GB"]
      ]
      ix = model.index(rev)
      board, memory = model[ix+1]
      return (rev, board, memory)

    def get_ip_address(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,
            struct.pack('256s', ifname[:15])
        )[20:24])

    def datetimeformat(value, format='%H:%M'):
        return value.strftime(format)

    def timestampformat(value, format='%Y-%m-%d %H:%M:%S'):
        return datetime.fromtimestamp(int(value)).strftime(format)

    def tempformat(value):
        return value.replace("temp=", "").replace("'C\n", "")

    def dhtformat(value):
        return int(value)

    def duration(value):
        return datetime.fromtimestamp(int(value)).strftime('%M:%S')

    def currentDuration(value):
        tmp = value.split(':')
        duration = datetime.fromtimestamp(int(tmp[0])).strftime('%M:%S')
        return duration

    def timeAgo(time=False):
        now = datetime.now()
        if type(time) is int:
            diff = now - datetime.fromtimestamp(time)
        elif isinstance(time, datetime):
            diff = now - time
        elif not time:
            diff = now - now
        second_diff = diff.seconds
        day_diff = diff.days

        if day_diff < 0:
            return ''

        if day_diff == 0:
            if second_diff < 10:
                return "just now"
            if second_diff < 60:
                return str(second_diff) + " seconds ago"
            if second_diff < 120:
                return "a minute ago"
            if second_diff < 3600:
                return str(second_diff / 60) + " minutes ago"
            if second_diff < 7200:
                return "an hour ago"
            if second_diff < 86400:
                return str(second_diff / 3600) + " hours ago"
        if day_diff == 1:
            return "Yesterday"
        if day_diff < 7:
            return str(day_diff) + " days ago"
        if day_diff < 31:
            return str(day_diff / 7) + " weeks ago"
        if day_diff < 365:
            return str(day_diff / 30) + " months ago"
        return str(day_diff / 365) + " years ago"

    app.jinja_env.filters['datetimeformat'] = datetimeformat
    app.jinja_env.filters['timestampformat'] = timestampformat
    app.jinja_env.filters['tempformat'] = tempformat
    app.jinja_env.filters['dhtformat'] = dhtformat
    app.jinja_env.filters['duration'] = duration
    app.jinja_env.filters['timeAgo'] = timeAgo
    app.jinja_env.filters['currentDuration'] = currentDuration

    @app.route('/')
    def index():
        cursor = mysql.connect().cursor()
        cursor.execute("SELECT * FROM (SELECT * FROM sensors ORDER BY id DESC limit 8) AS sensors ORDER BY id ASC")
        sensors = cursor.fetchall()

        for pin in pins:
            pins[pin]['state'] = GPIO.input(pin)

        jsonWeather = urllib2.urlopen('http://api.openweathermap.org/data/2.5/forecast/daily?q=' + app.config['WEATHER']['city'] + '&units=' + app.config['WEATHER']['units'] + '&lang=' + app.config['WEATHER']['lang'] + '&appid=' + app.config['WEATHER']['apikey'] + '&cnt=6&mode=json')
        weather = json.load(jsonWeather)

        templateData = {
            'sensors': sensors,
            'pins': pins,
            'weather': weather
        }
        return render_template('index.html', **templateData)

    @app.route('/sensor')
    def sensor():
        cursor = mysql.connect().cursor()
        cursor.execute("SELECT * FROM (SELECT * FROM sensors ORDER BY id DESC limit 24) AS sensors ORDER BY id ASC")
        sensors = cursor.fetchall()
        templateData = {
            'sensors': sensors,
            'realtime': dht.read_retry(dht.DHT22, app.config['DHT22_PIN'])
        }
        return render_template('sensor.html', **templateData)

    @app.route('/switch')
    def switch():

        for pin in pins:
            pins[pin]['state'] = GPIO.input(pin)

        templateData = {
            'pins': pins
        }
        return render_template('switch.html', **templateData)

    @app.route('/switch/<master>')
    def master(master):
        if master == 'on':
            for pin in pins:
                GPIO.output(pin, GPIO.HIGH)

        if master == 'off':
            for pin in pins:
                GPIO.output(pin, GPIO.LOW)

        if master == 'toggle':
            for pin in pins:
                GPIO.output(pin, not GPIO.input(pin))

        if master == 'reset':
            for pin in pins:
                GPIO.output(pin, GPIO.LOW)
                time.sleep(5)
                GPIO.output(pin, GPIO.HIGH)

        return redirect(url_for('switch'))

    @app.route('/switch/<changePin>/<action>')
    def action(changePin, action):
        changePin = int(changePin)

        if action == 'on':
            GPIO.output(changePin, GPIO.HIGH)

        if action == 'off':
            GPIO.output(changePin, GPIO.LOW)

        if action == 'toggle':
            GPIO.output(changePin, not GPIO.input(changePin))

        if action == 'reset':
            GPIO.output(changePin, GPIO.LOW)
            time.sleep(5)
            GPIO.output(changePin, GPIO.HIGH)

        return redirect(url_for('switch'))

    @app.route('/calendar')
    def calendar():
        credentials = get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('calendar', 'v3', http=http)
        events = service.events().list(singleEvents=True, calendarId=app.config['GMAIL']['calendar_id']).execute()
        today = datetime.today()
        now = today.strftime('%Y-%m-%d')

        templateData = {
            'now': now,
            'agenda': events['items']
        }

        return render_template('calendar.html', **templateData)

    @app.route('/calendar/add', methods=['POST'])
    def add():
        if request.method == 'POST':
            credentials = get_credentials()
            http = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http)

            start = ""+request.form['StartDate']+"T"+request.form['StartTime']+":00+01:00"
            end = ""+request.form['EndDate']+"T"+request.form['EndTime']+":00+01:00"

            event = {
                "summary": request.form['Summary'],
                "description": request.form['Description'],
                "start": {
                    "dateTime": start,
                    "timeZone": "Europe/Paris"
                },
                "end": {
                    "dateTime": end,
                    "timeZone": "Europe/Paris"
                }
            }
            service.events().insert(calendarId=app.config['GMAIL']['calendar_id'], body=event).execute()
        return redirect(url_for('calendar'))

    @app.route('/calendar/delete/<idevent>')
    def delete(idevent):
        credentials = get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('calendar', 'v3', http=http)
        service.events().delete(calendarId=app.config['GMAIL']['calendar_id'], eventId=idevent).execute()

        return redirect(url_for('calendar'))

    @app.route('/feed')
    def feed():
        templateData = {
            'rspy': feedparser.parse(app.config['FEEDS']['feed_1']),
            'rpypod': feedparser.parse(app.config['FEEDS']['feed_2'])
        }

        return render_template('feed.html', **templateData)

    @app.route('/player')
    def player():
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        splitTemp = client.status()['time']
        split = splitTemp.split(':')

        templateData = {
            'variable': (int(split[0]) * 100) / int(split[1]),
            'status': client.status(),
            'current': client.currentsong(),
            'playlist': client.playlistinfo()
        }

        return render_template('player.html', **templateData)

    @app.route('/player/<player_action>')
    def player_action(player_action):
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None

        if player_action == 'backward':
            client.previous()
        elif player_action == 'forward':
            client.next()
        elif player_action == 'play':
            client.play()
        elif player_action == 'pause':
            client.pause()

        return redirect(url_for('player'))

    @app.route('/player/play/<play_id>')
    def play_id(play_id):
        client = MPDClient()
        client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
        client.timeout = None
        client.idletimeout = None
        client.playid(play_id)
        return redirect(url_for('player'))

    @app.route('/message')
    def message():
        templateData = {
            'my_adress': app.config['PUSHBULLET']['mail'],
            'contacts': pb.contacts,
            'logs': pb.get_pushes()
        }
        return render_template('message.html', **templateData)

    @app.route('/message/send', methods=['POST'])
    def send_push():
        if request.method == 'POST':
            pb.push_note('[Notification Rpi]', request.form['Content'], email=request.form['Contact'])

        return redirect(url_for('message'))

    @app.route('/message/delete/<iden>')
    def delete_push(iden):
        pb.delete_push(iden)
        return redirect(url_for('message'))

    @app.route('/message/dismissed/<iden>')
    def dismissed_push(iden):
        pb.dismiss_push(iden)
        return redirect(url_for('message'))

    @app.route('/camera')
    def camera():

        return render_template('camera.html')

    @app.route('/system')
    def system():
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')

        cursor = mysql.connect().cursor()
        cursor.execute("SELECT * FROM (SELECT * FROM cpu ORDER BY id DESC limit 24) AS cpu ORDER BY id ASC")
        cpu_graph = cursor.fetchall()

        templateData = {
            'cpu_graph': cpu_graph,
            'uname': os.uname(),
            'ip': get_ip_address(app.config['INTERNET']),
            'raspberry': revToModel(),
            'uptime': str(datetime.now() - datetime.fromtimestamp(psutil.boot_time())).split('.')[0],
            'cpu': str(psutil.cpu_percent()),
            'cpu_temp': os.popen('/opt/vc/bin/vcgencmd measure_temp').readline(),
            'mem_percent': memory.percent,
            'mem_used': bytes2human(memory.used),
            'mem_total': bytes2human(memory.total),
            'disk_used': bytes2human(disk.used),
            'disk_total': bytes2human(disk.total),
            'disk_percent': disk.percent
        }
        return render_template('system.html', **templateData)

    @app.route('/network')
    def network():
        ping_cur = mysql.connect().cursor()
        ping_cur.execute("SELECT * FROM (SELECT * FROM ping ORDER BY id DESC limit 5) AS ping ORDER BY id ASC")
        ping = ping_cur.fetchall()

        templateData = {
            'ping': ping
        }
        return render_template('network.html', **templateData)

    return app
Beispiel #34
0
from flask import Flask, request, Response, jsonify
from flaskext.mysql import MySQL

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()
Beispiel #35
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)
from flask import Flask
from flaskext.mysql import MySQL
dir_app = Flask(__name__)
dir_mysql = MySQL()
dir_app.config['MYSQL_DATABASE_USER'] = '******'
dir_app.config['MYSQL_DATABASE_PASSWORD'] = '******'
dir_app.config['MYSQL_DATABASE_DB'] = 'directory'
dir_app.config['MYSQL_DATABASE_HOST'] = 'colab-sbx-245.oit.duke.edu'
dir_mysql.init_app(dir_app)

cal_app = Flask(__name__)
cal_mysql = MySQL()
cal_app.config['MYSQL_DATABASE_USER'] = '******'
cal_app.config['MYSQL_DATABASE_PASSWORD'] = '******'
cal_app.config['MYSQL_DATABASE_DB'] = 'calendar'
cal_app.config['MYSQL_DATABASE_HOST'] = 'colab-sbx-245.oit.duke.edu'
cal_mysql.init_app(cal_app)

Beispiel #37
0
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = DEBUG
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = 3306
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = None
app.config['MYSQL_DATABASE_DB'] = 'musicrack'
app.config['MYSQL_DATABASE_CHARSET'] = 'utf8'
app.config['SESSION_TIMEOUT'] = datetime.timedelta(7)
app.config['CACHE_CONFIG'] = {
	'CACHE_TYPE': 'simple',
	'CACHE_DEFAULT_TIMEOUT': 600
}
app.config['SECRET_KEY'] = 'rT4EgGRZ4uSrjPeU_ND9FwAdLD7EtAZw'

# DB Initialize
db = MySQL()
db.init_app(app)

# Cache Initialize
cache = Cache(config=app.config['CACHE_CONFIG'])
cache.init_app(app)

# Register session API
app.register_blueprint(v_session, url_prefix='/session')
# Register directory API
app.register_blueprint(v_files, url_prefix='/files')

@app.route('/')
def index():
	return render_template('/index.html')
	
Beispiel #38
0
import sys
sys.path.append("..")

from flask import redirect, url_for
from flaskext.mysql import MySQL

mysql = MySQL()

appHandler.config['MYSQL_DATABASE_USER'] = '******'
appHandler.config['MYSQL_DATABASE_PASSWORD'] = '******'
appHandler.config['MYSQL_DATABASE_DB'] = 'kups'
appHandler.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(appHandler)

class LoginController:

    def authenticate(self,form):
        
        username = form['username']
        password = form['password']

        cursor = mysql.connect().cursor
        cursor.execute("select * from users where username='******' and password='******'")
         data = cursor.fetchone();
         if data is None :
             return "Username or Password is Wrong"
         else :
            return 'Login Successful'

        
Beispiel #39
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']
Beispiel #40
0
class DBSetup(object):
    def __init__(self, config={}):
        self.config = config

    def init(self, app):
        self.mysql = MySQL()
        params = self.get_database_params()
        app.config['MYSQL_DATABASE_USER'] = params['MYSQL_DATABASE_USER']
        app.config['MYSQL_DATABASE_PASSWORD'] = params['MYSQL_DATABASE_PASSWORD']
        app.config['MYSQL_DATABASE_DB'] = params['MYSQL_DATABASE_DB']
        app.config['MYSQL_DATABASE_HOST'] = params['MYSQL_DATABASE_HOST']
        app.config['MYSQL_DATABASE_PORT'] = params['MYSQL_DATABASE_PORT']

        self.mysql.init_app(app)

    def db(self):
        return self.mysql

    def get_database_params(self):
        ret = {}
        if os.environ.get('mysql_database_user') and os.environ.get('mysql_database_password') and \
            os.environ.get('mysql_database_db') and os.environ.get('mysql_database_host') and \
            os.environ.get('mysql_database_port'):
            ret['MYSQL_DATABASE_USER'] = os.environ.get('mysql_database_user')
            ret['MYSQL_DATABASE_PASSWORD'] = os.environ.get('mysql_database_password')
            ret['MYSQL_DATABASE_DB'] = os.environ.get('mysql_database_db')
            ret['MYSQL_DATABASE_HOST'] = os.environ.get('mysql_database_host')
            ret['MYSQL_DATABASE_PORT'] = int(os.environ.get('mysql_database_port'))
        else:
            env = sqlpie.DBSetup.environment()

            if env in self.config['db']:
                ret['MYSQL_DATABASE_USER'] = self.config['db'][env]['mysql_database_user']
                ret['MYSQL_DATABASE_PASSWORD'] = self.config['db'][env]['mysql_database_password']
                ret['MYSQL_DATABASE_DB'] = self.config['db'][env]['mysql_database_db']
                ret['MYSQL_DATABASE_HOST'] = self.config['db'][env]['mysql_database_host']
                ret['MYSQL_DATABASE_PORT'] = int(self.config['db'][env]['mysql_database_port'])
            else:
                ret['MYSQL_DATABASE_USER'] = None
                ret['MYSQL_DATABASE_PASSWORD'] = None
                ret['MYSQL_DATABASE_DB'] = None
                ret['MYSQL_DATABASE_HOST'] = None
                ret['MYSQL_DATABASE_PORT'] = None
        return ret

    @staticmethod
    def environment():
        env = "development"
        if os.environ.get('sqlpie_env'):
            env = os.environ.get('sqlpie_env').lower()
        return env

    @staticmethod
    def reset_database():
        sqlpie.Bucket.reset()
        sqlpie.Document.reset()
        sqlpie.Content.reset()
        sqlpie.Term.reset()
        sqlpie.ContentKey.reset()
        sqlpie.ContentTerm.reset()
        sqlpie.RankingIDF.reset()
        sqlpie.RankingTF.reset()
        sqlpie.Observation.reset()
        sqlpie.Predicate.reset()
        sqlpie.Cache.reset()
        sqlpie.Model.reset()
        sqlpie.ModelClassifier.reset()

    @staticmethod
    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
Beispiel #41
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()
Beispiel #42
0
#from flask_mysqldb import MySQL
from aks import app
from aks.posts import posts
#import MySQLdb
from aks.forms import RegisterForm, LoginForm, MyForm
from aks.models import User, Todo, Patient
import mysql.connector
# same like this below
#from aks.forms import *
#from aks.models import *

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


@app.route('/')
def hello():
    return '<h1>Welcome to my site </h1>'


@app.route('/table', methods=['GET', 'POST'])
def table():
    #con = mysql.connect(USER="******",password="",HOST="localhost",DATABASE="dolphin")
    con = mysql.connect()
    m = con.cursor()
    q = "SELECT * FROM remedy"
    m.execute(q)
    rez = m.fetchall()
Beispiel #43
0
#guest2.py
#pip install flask-mysql
from flask import Flask, render_template, request, redirect
from flaskext.mysql import MySQL
import pymysql

mysql = MySQL(cursorclass=pymysql.cursors.DictCursor)
app = Flask(__name__)

app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

app.config.from_object(__name__)

mysql.init_app(app)


@app.route('/')
def index():
    print('/ 경로로 요청됨!')
    return render_template('index.html')


@app.route('/write', methods=['GET', 'POST'])
def write():
    if request.method == 'POST':
        #넘어온 값들을 받아서 guest 테이블에 INSERT한다.
        writer = request.form['writer']
        title = request.form['title']
Beispiel #44
0
from flask import render_template, flash, redirect, request, session
from flaskext.mysql import MySQL
from app import myApp
from .forms import LoginForm, RegisterForm, EventForm

#can use variable parts to url with <variable_name> or convertor with <convertor:varname>
# can use int, float, and path as convertor (path accepts slashes)
# urls endind in / will work both with and without slash, without slash, it has to match

mysql = MySQL()
myApp.config['MYSQL_DATABASE_USER'] = '******'
myApp.config['MYSQL_DATABASE_PASSWORD'] = '******'
myApp.config['MYSQL_DATABASE_DB'] = 'watchWithMe'
myApp.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(myApp)


@myApp.route('/')
@myApp.route('/index')
def index():   
    db = mysql.connect()
    cursor = db.cursor()

    if 'userName' in session:
        cursor.execute("SELECT First, PID FROM Person WHERE Username=%s", [session['userName']])
        result = cursor.fetchone()
        name = "%s" % result[0]
        PID = "%s" % result[1]

        cursor.execute("""SELECT Name, Time, date, Title, Genre, e.EID
                        FROM Event as e, Media as m, EventHasMedia as ehm, Attend as a, Media_2 as mtwo
Beispiel #45
0
from typing import List, Dict
import mysql.connector
import simplejson as json
# import str as str
from flask import Flask, Response, request, redirect
from flask import render_template

app = Flask(__name__, template_folder='templates')

from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor

mysql = MySQL(cursorclass=DictCursor)

app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1'
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_PORT'] = 3306
app.config['MYSQL_DATABASE_DB'] = 'heightWidth'
mysql.init_app(app)


@app.route('/', methods=['GET'])
def index():
    user = {'username': '******'}
    cursor = mysql.get_db().cursor()
    cursor.execute('SELECT * FROM hw_100')
    result = cursor.fetchall()
    return render_template('index.html',
                           title='Home',
                           user=user,
Beispiel #46
0
def init_db(app):
    db = MySQL()
    db.init_app(app)
    db_handler = connect_db(db)
    db_handler.ensure_tables()
    return db_handler
Beispiel #47
0
from flask import Flask, render_template, request, json, session, redirect, url_for, escape, flash
from hashlib import md5
from flaskext.mysql import MySQL
import os

application = Flask(__name__)
mysql = MySQL()

# MySQL configurations
application.config['MYSQL_DATABASE_USER'] = '******'
application.config['MYSQL_DATABASE_PASSWORD'] = '******'
application.config['MYSQL_DATABASE_DB'] = 'qa_course'
application.config['MYSQL_DATABASE_HOST'] = '52.2.195.57'
application.secret_key = 'FEF9B%399-!8EF6- 4B16-[9BD4-092B1<85D632D'
mysql.init_app(application)


class ServerError(Exception):
    pass


@application.errorhandler(404)
def page_not_found(e):
    # return render_template('index.html'), 404
    return render_template('WIP.html'), 404


@application.route("/index")
@application.route("/")
def index():
    if 'username' in session:
Beispiel #48
0
def init_db(app, run_db):
    if run_db:
        mysql = MySQL()
        database_setup.add_config_params(app)
        mysql.init_app(app)
Beispiel #49
0
from flask import Flask, redirect, url_for, request, render_template
from flaskext.mysql import MySQL

mysql = MySQL()


app = Flask(__name__)

file = {}


def init_db(user, password, database, host):
	app.config['MYSQL_DATABASE_USER'] = user
	app.config['MYSQL_DATABASE_PASSWORD'] = password
	app.config['MYSQL_DATABASE_DB'] = database
	app.config['MYSQL_DATABASE_HOST'] = host
	mysql.init_app(app)
	
def init_index():
	cursor = mysql.connect().cursor()
	cursor.execute("select file_id, name from files")
	results = cursor.fetchall()
	for row in results:
		file[row[0]] = row[1]


@app.route('/')
def homepage():
	return render_template('login.html')
	
Beispiel #50
0
#-*- coding: utf-8 -*-
from distutils.archive_util import make_tarball

__author__ = 'adrian'
from flaskext.mysql import MySQL
import flask
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
from flask import Flask, jsonify, request
from flaskext.mysql import MySQL
import datetime
from ReplaceDB import handleHourly, clientSummary, localSummary
from RetrieveDB import dailyAll, daily, weekly, monthly, yearly, localAreaSummary
from pymysql.cursors import DictCursor
import json
import ast

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'analytics'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL(app, cursorclass=DictCursor)
db = mysql.connect()


@app.route('/getreport', methods=['GET', 'POST'])
def getreport():  #from client
    req = request.json
    print str(req), type(req), "\n"

    if "duration" not in req:
        print "duration not in req"
        return jsonify({
            'StatusCode':
            '400',
Beispiel #52
0
# Load default config and override config from an environment variable
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()
Beispiel #53
0
from flask import Flask, render_template, jsonify, request
from flaskext.mysql import MySQL

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

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


@app.route('/')
def index():
    user = ""

    return render_template('index.html', user=user)


@app.route('/getTask')
def getTask():
    x = request.args.get('id', 0, type=str)
    cursor.execute("SELECT * from Tasks WHERE id=%s", x)
    task = cursor.fetchone()
    return jsonify(task)


@app.route('/getSubTasks')
Beispiel #54
0
from flask import Flask
from flaskext.mysql import MySQL
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
mysql = MySQL()
mysql.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
from app import views
Beispiel #55
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'] = 'sisventas'  #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 cliente ")  #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 producto ")  #se hace la consulta
reportt = con.fetchall(
)  #funcion que hace que extrae todo desde la base de datos
print reportt