class Repository: instance = None @classmethod def getInstance(cls, db_user='******', db_password='******', db_database='accountbook'): if cls.instance is None: cls.instance = cls(db_user, db_password, db_database) return cls.instance def __init__(self, db_user, db_password, db_database): self.db_user = db_user self.db_password = db_password self.db_database = db_database self.db_source = MySQL() def selectQuery(self, query, args, **kwargs): conn = self.db_source.connect() cursor = conn.cursor() cursor.execute(query, args) results = [] #columns 컬럼명을 리스트로 생성 columns = [d[0] for d in cursor.description] # 결과 키 값 쌍을 results에 추가 if ('header' in kwargs): results.append(dict(zip(columns, columns))) for row in cursor: results.append(dict(zip(columns, row))) cursor.close() conn.close() return results def executeQuery(self, query, args): conn = self.db_source.connect() cursor = conn.cursor() cursor.execute(query, args) conn.commit() cursor.close() conn.close() return 'success' def findOne(self, obj): return self.selectQuery( QueryBuilder().select(obj.select()).table( type(obj).__name__).where(obj.filter()).build(), ())
def create_connection(): mysql = MySQL() app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '' app.config['MYSQL_DATABASE_DB'] = 'virball' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) con = mysql.connect() return con
def set_connection(app): mysql = MySQL() # MySQL configurations with open("project/credentials.txt", "r") as credentials_file: credentials = credentials_file.read().splitlines() app.config['MYSQL_DATABASE_USER'] = credentials[0] app.config['MYSQL_DATABASE_PASSWORD'] = credentials[1] app.config['MYSQL_DATABASE_DB'] = credentials[2] app.config['MYSQL_DATABASE_HOST'] = credentials[3] mysql.init_app(app) global conn conn = mysql.connect()
def test_search(self): _startdate = '2017-03-23' _starttime = '01:00 PM' _type = 'G' mysql = MySQL() # MySQL configurations app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'lrrs' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) conn = mysql.connect() cursor = conn.cursor() cursor.callproc('sp_searchrooms', args=(_type, _starttime, _startdate)) assert cursor.rowcount == 1
def connect(): """connect user to DataBase on host""" host = "psotty.mysql.pythonanywhere-services.com" user = "******" pswd = "" database = "psotty$fitness" mysql = MySQL() # MySQL configurations app.config['MYSQL_DATABASE_USER'] = user app.config['MYSQL_DATABASE_PASSWORD'] = pswd app.config['MYSQL_DATABASE_DB'] = database app.config['MYSQL_DATABASE_HOST'] = host mysql.init_app(app) db = mysql.connect() return db
from flask import request from app.api import outApi, user, common from flask.ext.mysql import MySQL from flask_cors import * # from flask import make_response import traceback import json mysql = MySQL() app = Flask(__name__) CORS(app, supports_credentials=True) app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'secondhand' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) conn = mysql.connect() api = restful.Api(app) @app.before_request def my_before_request(): g.db = conn # print('before request', request.headers) @app.after_request def my_after_request(self): try: print('after request') except: traceback.print_exc()
from flask import Flask from flask.ext.mysql import MySQL app = Flask(__name__) app.debug = True mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'tp_db' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) conn = mysql.connect() conn.autocommit(True) cursor = conn.cursor() from app import User, Forum, Thread, Post, General
"mongocluster-shard-00-01-5qypc.mongodb.net:27017," "mongocluster-shard-00-02-5qypc.mongodb.net:27017/test?ssl=true&replicaSet=mongocluster-shard-0&authSource=admin" ) actors_db = mongo_client.actors app = Flask(__name__) mysql = MySQL() # MySQL configurations app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'news' app.config[ 'MYSQL_DATABASE_HOST'] = 'mydbfeedmenews.cffkuryafwgu.us-east-1.rds.amazonaws.com' mysql.init_app(app) cursor = mysql.connect().cursor() male_actors = actors_db.male female_actors = actors_db.female @app.route('/') def index(): return render_template('index.html') @app.route('/result', methods=['POST']) def search(): # firstLike = request.values.get("firstLike") firstLike = request.form['firstLike'] # secondLike = request.values.get("secondLike")
import flask.views from flask import render_template from flask import request, make_response,send_from_directory from werkzeug import secure_filename from flask.ext.httpauth import HTTPBasicAuth from flask import jsonify , json app = flask.Flask(__name__,static_url_path='') print app.static_url_path from flask.ext.mysql import MySQL mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'forum' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) cursor = mysql.connect().cursor() @app.route('/') @app.route('/login',methods=['GET']) def index(): return render_template('login.html') @app.route('/login', methods=['POST']) def login(): user = request.form['email'] password = request.form['pass'] return authenticate(user,password) def authenticate(username, password): cursor.execute("SELECT * from user") print 'authenticate'
class Database(object): """Handles communication with the mysql database""" def __init__(self, app): self.mysql = MySQL() self.mysql.init_app(app) self.con = self.mysql.connect() self.cur = self.con.cursor() def GetCredit(self): """Get the total credits added Returns: Total credits added, in seconds """ self.cur.execute('select sum(seconds) from credit;') rv = self.cur.fetchall()[0][0] return rv and int(rv) or 0 def GetUsage(self): """Get the total internet usage according to the database Returns: Total usage in seconds """ self.cur.execute('select sum(duration) from record;') rv = self.cur.fetchall()[0][0] return rv and int(rv) or 0 def GetState(self): """Get the current internet state, and when that state was set A state change is written to the 'state' table when the Internet is enabled. It is removed when the Internet is disabled. So if there is a state record, we know that the Internet was enabled at some point. Returns: tuple: State (DISABLED or ENABLED) Time of last state change (0 if disabled) """ self.cur.execute('select * from state;') rv = self.cur.fetchall() if not rv: return DISABLED, 0 state, dt = rv[0] return state, dt def GetUsed(self): """Return the duration of internet that is used but not recorded yet Returns: Duration in seconds since the Internet was started """ state, dt = self.GetState() if not state: return 0, 0 return 1, math.floor((datetime.now() - dt).total_seconds()) def RecordEnableTime(self): """Record that we have started a new internet session""" self.cur.execute('delete from state;') self.cur.execute( 'insert into state (enabled, start) values (true, now());') self.con.commit() def RecordSession(self): """Record that the internet session has ended""" state, start = self.GetState() if state == DISABLED: # We did not write a record at the start of the session, so don't # know when it began print 'Missing record in "state" table' return cmd = ( "insert into record (start, end, duration) values ('%s', now(), %d);" % (start.strftime('%Y-%m-%d %H:%M:%S'), (datetime.now() - start).total_seconds())) self.cur.execute(cmd) self.cur.execute('delete from state;') self.con.commit() def GetRemaining(self): """Get the remaining internet time in seconds This totals all credits, subtracts all usage and also subtracts any pending usage (the time since the Internet was started). Returns: Remaining time in seconds """ credit = self.GetCredit() debit = self.GetUsage() db_state, used = self.GetUsed() return credit - debit - used
from flask.ext.mysql import MySQL import spaza_shop app = Flask(__name__) mysql = MySQL() app.config["DEBUG"] = True # MySQL configurations app.config["MYSQL_DATABASE_USER"] = "******" app.config["MYSQL_DATABASE_PASSWORD"] = "******" app.config["MYSQL_DATABASE_DB"] = "spaza_shop" app.config["MYSQL_DATABASE_HOST"] = "localhost" mysql.init_app(app) connection = mysql.connect() cursor = connection.cursor() # url_for('static', filename='main_page.css') # url_for('static', filename='bootstrap.min.css') # url_for('static', filename='bootstrap.min.js') # url_for('static', filename='jquery.js') @app.route("/popular_category/") def popular_category(): sales = spaza_shop.get_sales() most_pop_cat = spaza_shop.get_most_pop_cat(sales) cursor.execute( "SELECT cat_name, SUM(no_sold) AS no_sold FROM sales_history INNER JOIN categories ON category_name=categories.cat_name GROUP BY cat_name ORDER BY no_sold DESC"
from flask import Flask from flask.ext.mysql import MySQL app = Flask(__name__) mysql = MySQL() app.config.from_object('config') # database connection and test mysql.init_app(app) connection = mysql.connect() cursor = connection.cursor() cursor.execute("select * from UserData") data = cursor.fetchone() print(data) # using mysql: # cursor.execute("query") # cursor.callproc("stored procedure", ) # https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-callproc.html # in your own modules, 'from main import cursor' at the top. import userstasksview import grouptasksview import messageview import friendview import groupmemberview