Beispiel #1
0
    def conexion(self):
        mysql = MySQL()
        control = Flask(__name__)

        control.config["MYSQL_DATABASE_USER"] = "wtec"
        control.config["MYSQL_DATABASE_PASSWORD"] = "wtec.s"
        control.config["MYSQL_DATABASE_DB"] = "wtec_webapp"
        control.config["MYSQL_DATABASE_HOST"] = "192.168.227.1"
        mysql.init_app(control)
        return mysql
Beispiel #2
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys

reload(sys)
sys.setdefaultencoding("utf8")

from flask import Flask, request, Response, g, session, url_for, json, jsonify
from flaskext.mysql import MySQL


app = Flask(__name__)
mysql = MySQL()

app.config["MYSQL_DATABASE_USER"] = "kbgiskbg"
app.config["MYSQL_DATABASE_PASSWORD"] = "mysql"
app.config["MYSQL_DATABASE_DB"] = "emotionDB"
app.secret_key = "emotionDB_secret_key"

mysql.init_app(app)


def connect_db():
    return mysql.connect()


def query_db(query, one=False):
    cursor = g.db.cursor()
    cursor.execute(query)

    data = []
from flask import Flask, render_template, json, request, redirect, session, jsonify

# from flask.ext.mysql import MySQL
# from werkzeug import generate_password_hash, check_password_hash

# mysql = MySQL()
app = Flask(__name__)
app.secret_key = "why would I tell you my secret key?"

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "jay"
app.config["MYSQL_DATABASE_PASSWORD"] = "jay"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
# mysql.init_app(app)


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


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


@app.route("/showAddWish")
def showAddWish():
    return render_template("addWish.html")
Beispiel #4
0

# create the application object
app = Flask(__name__)
# VARIABLE REQUIRED FOR ADMINISTRATOR MODULE
PAGE_LIMIT = 10


## set up connection to the database

mysql = MySQL()
db = SQLAlchemy(app)
app.config["SQLALCHEMY_DATABASE_URI"] = propertiesparser.getDatabaseSQLAlchemy()

app.secret_key = "F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT"
app.config["MYSQL_DATABASE_USER"] = propertiesparser.getDatabaseUserName()
app.config["MYSQL_DATABASE_PASSWORD"] = propertiesparser.getDatabasePassword()
app.config["MYSQL_DATABASE_DB"] = propertiesparser.getDatabaseName()
app.config["MYSQL_DATABASE_HOST"] = propertiesparser.getDatabaseHost()
mysql.init_app(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
role = ""

## section for the login and registration modules
@app.route("/login")
def login():
    session.pop("username", None)
    return render_template("/login/login.html", title="ENABLE INDIA - LOGIN")

Beispiel #5
0
from flask import Flask, jsonify, render_template, request, json
import MySQLdb

app = Flask(__name__)
app.debug = True
app.config["MYSQL_DATABASE_USER"] = "potts"
app.config["MYSQL_DATABASE_PASSWORD"] = "nicetry"
app.config["MYSQL_DATABASE_DB"] = "potts$Potts"
app.config["MYSQL_DATABASE_HOST"] = "potts.mysql.pythonanywhere-services.com"


class DB:
    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(
            host="potts.mysql.pythonanywhere-services.com", user="potts", passwd="nicetry", db="potts$Potts"
        )

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

    def query(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
        except (AttributeError, MySQLdb.OperationalError):
            self.connect()
            cursor = self.conn.cursor()
            cursor.execute(sql)
        return cursor.fetchall()
Beispiel #6
0
            cursor.callproc("sp_tasks_sp", (u_id))
            data = cursor.fetchall()
            print "Aditya"
            print data
            return "Aditya"
        else:
            print "NOT ADITYA"
            return "INVALID USER!"
    except Exception as e:
        return json.dumps({"error": str(e)})
    finally:
        cursor.close()
        conn.close()


if __name__ == "__main__":
    mysql = MySQL()

    mysql_config_file = "config.json"

    with open(mysql_config_file) as data_file:
        data = json.load(data_file)

        # MySQL configurations
        app.config["MYSQL_DATABASE_HOST"] = data["hostname"]
        app.config["MYSQL_DATABASE_USER"] = data["username"]
        app.config["MYSQL_DATABASE_PASSWORD"] = data["password"]
        app.config["MYSQL_DATABASE_DB"] = data["database"]

    mysql.init_app(app)
    app.run(debug=True)
Beispiel #7
0
from flask import url_for
from flaskext.mysql import MySQL
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, date, time, timedelta
import config


app = Flask(__name__)
app.config["DEBUG"] = True
app.config["PROPAGATE_EXCEPTIONS"] = True


mysql = MySQL()

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = config.DB_USER
app.config["MYSQL_DATABASE_PASSWORD"] = config.DB_PW
app.config["MYSQL_DATABASE_DB"] = config.DB_SCHEMA
app.config["MYSQL_DATABASE_HOST"] = config.DB_HOST
mysql.init_app(app)

app.secret_key = "I miss the comfort in being sad."


@app.route("/")
def main():
    if session.get("user"):
        return redirect("/userHome")
    else:
        return render_template("index.html")
Beispiel #8
0
from werkzeug import check_password_hash, generate_password_hash
from helpers import *
import config


app = Flask(__name__)
mysql = MySQL()

app.config["MYSQL_DATABASE_HOST"] = (
    os.environ["MYSQL_DATABASE_HOST"] if "MYSQL_DATABASE_HOST" in os.environ else config.MYSQL_DATABASE_HOST
)
app.config["MYSQL_DATABASE_PORT"] = (
    os.environ["MYSQL_DATABASE_PORT"] if "MYSQL_DATABASE_PORT" in os.environ else config.MYSQL_DATABASE_PORT
)
app.config["MYSQL_DATABASE_USER"] = (
    os.environ["MYSQL_DATABASE_USER"] if "MYSQL_DATABASE_USER" in os.environ else config.MYSQL_DATABASE_USER
)
app.config["MYSQL_DATABASE_PASSWORD"] = (
    os.environ["MYSQL_DATABASE_PASSWORD"] if "MYSQL_DATABASE_PASSWORD" in os.environ else config.MYSQL_DATABASE_PASSWORD
)
app.config["MYSQL_DATABASE_DB"] = (
    os.environ["MYSQL_DATABASE_DB"] if "MYSQL_DATABASE_DB" in os.environ else config.MYSQL_DATABASE_DB
)

mysql.init_app(app)

if "SECRET_KEY" in os.environ:
    app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
else:
    app.config["SECRET_KEY"] = os.urandom(24)
Beispiel #9
0
from flask import Flask, render_template, json, request
from requests.auth import HTTPBasicAuth
from flask.ext.mysql import MySQL
from sets import Set
import json
import sys
import requests

app = Flask(__name__)
# uncomment for debugging
app.debug = True
mysql = MySQL()

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "sql398426"
app.config["MYSQL_DATABASE_PASSWORD"] = "lM9!dV5!"
app.config["MYSQL_DATABASE_DB"] = "sql398426"
app.config["MYSQL_DATABASE_HOST"] = "sql3.freemysqlhosting.net"
mysql.init_app(app)


@app.route("/")
def main():
    rec = most_recent(10)
    freq = most_frequent(10)
    comb = Set(rec) | Set(freq)
    return render_template("index.html", comb=comb, freq=freq, rec=rec)


@app.errorhandler(404)
def page_not_found(e):
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 #11
0
from flask import Flask, render_template, request, json, session, redirect
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

mysql = MySQL()
app = Flask(__name__)
app.secret_key = "AAAAAAAAAAAA"

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "osho"
app.config["MYSQL_DATABASE_PASSWORD"] = "J6M767Dv36tdP8J"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)


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


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


@app.route("/showSignin")
def showSignin():
    if session.get("user"):
        return render_template("userHome.html")
    else:
Beispiel #12
0
from flask import Flask, request, url_for, redirect, Response
from flask.ext.mysql import MySQL
import requests, json, random, string
from flask.ext.cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
CORS(app, methods=["GET", "PROPFIND", "MKCOL", "MOVE", "COPY", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"])
mysql = MySQL()
# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "ismail"
app.config["MYSQL_DATABASE_PASSWORD"] = "webdav"
app.config["MYSQL_DATABASE_DB"] = "Webdav"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)


FILE = "sample.txt"
USERS = {
    "chikien": {
        "server": "apache2",
        "url": "http://localhost/webdav/",
        "permitted_files": ["/chikien/*", "/ismail/f1.jpeg"],
    },
    "wael": {"server": "nginx", "url": "http://localhost:6002/"},
    "ismail": {"server": "lighttpd", "url": "http://localhost:6002/"},
}


@app.route("/")
def hello_world():
Beispiel #13
0
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from flaskext.mysql import MySQL

app = Flask(__name__)

app.config["MYSQL_DATABASE_HOST"] = "localhost"
app.config["MYSQL_DATABASE_PORT"] = 3306
app.config["MYSQL_DATABASE_USER"] = "green_grocer"
app.config["MYSQL_DATABASE_PASSWORD"] = "password"
app.config["MYSQL_DATABASE_DB"] = "spaza"

mysql = MySQL(app)


@app.route("/")
def products():
    cur = mysql.get_db().cursor()
    cur.execute(
        """SELECT Name,SUM(Sales_price*Qty) AS TotalEarnings from Sales INNER JOIN Products ON Sales.Product_id = Products.Id GROUP BY Name ORDER BY TotalEarnings"""
    )
    products = [dict(TotalEarnings=row[1], Name=row[0]) for row in cur.fetchall()]
    """mysql.connection.commit()"""
    return render_template("menu.html", products=products)


if __name__ == "__main__":

    app.run(debug=True, port=int("8040"))
Beispiel #14
0
                matchings.append(matching)

        return matchings


mysql = MySQL()
app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "tomchm_bethany"
app.config["MYSQL_DATABASE_PASSWORD"] = "bethanyrhok2015"
app.config["MYSQL_DATABASE_DB"] = "tomchm_rhok"
app.config["MYSQL_DATABASE_HOST"] = "tomchm.com"
mysql.init_app(app)


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


def read_households(data):
    persons = []

    for household in data:
        household_id = household[0]
Beispiel #15
0
from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "trax"
app.config["MYSQL_DATABASE_PASSWORD"] = "trax456"
app.config["MYSQL_DATABASE_DB"] = "traxDB"
app.config["MYSQL_DATABASE_HOST"] = "162.243.253.200"

mysql.init_app(app)
api = Api(app)


class GetAllTrains(Resource):
    def get(self):
        try:
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.callproc("getAllTrains")
            data = cursor.fetchall()

            trainList = []
            for item in data:
                i = {"trainId": item[0], "trainName": item[1]}
                trainList.append(i)

            return {"StatusCode": "200", "data": trainList}
from flask import Flask, request, Response
from flaskext.mysql import MySQL
from flask.ext.cors import CORS
import json

mysql = MySQL()
app = Flask(__name__)
cors = CORS(app)

app.config["MYSQL_DATABASE_USER"] = "user"
app.config["MYSQL_DATABASE_PASSWORD"] = "pass"
app.config["MYSQL_DATABASE_DB"] = "todo"
app.config["MYSQL_DATABASE_HOST"] = "localhost"

mysql.init_app(app)


def log(msg):
    log_file = open("log.txt", "a")
    log_file.write(msg + "\n")
    log_file.close()


@app.route("/todo", methods=["GET", "POST", "OPTIONS"])
def todos():
    params = json.loads(json.dumps(request.json))

    con = mysql.connect()
    cursor = con.cursor()
    info = dict()
Beispiel #17
0
from flask import Flask, render_template, json, request
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__)
mysql = MySQL()

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "sppatel"
app.config["MYSQL_DATABASE_PASSWORD"] = "admin"
app.config["MYSQL_DATABASE_DB"] = "bucketlist"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)


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


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


@app.route("/signUp", methods=["POST", "GET"])
def signUp():
    try:
        # read the posted values from the UI
        _name = request.form["inputName"]
        _email = request.form["inputEmail"]
Beispiel #18
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"] = "root"
application.config["MYSQL_DATABASE_PASSWORD"] = "mysqlpw"
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 #19
0
from sparkquery import sparkQuery
from mysqlquery import mysqlQuery

import MySQLdb as mysql

import threading
import json

# init flask app
app = Flask(__name__)
app.config.from_object(__name__)

app.config["MYSQL_DATABASE_HOST"] = MYSQL_INFO["host"]
app.config["MYSQL_DATABASE_DB"] = MYSQL_INFO["db"]
app.config["MYSQL_DATABASE_USER"] = MYSQL_INFO["user"]
app.config["MYSQL_DATABASE_PASSWORD"] = MYSQL_INFO["passwd"]


def general_query(source="hive", timestart=0, timeend=0, tp=0, pt1=(0, 0), pt2=(0, 0), mmsi=[0], output="csv"):
    """general query function
		Args:
			source: 	data source, include 'hive', 'mysql', 'oracle'
			timestart:	start time of query range
			timeend:	end time of query range
			type:		space query type, 
						0: pt1 is upper left (lo,la) coordinate, pt2 is (vertical, horizontal) length
						1: pt1 is upper left (lo,la) coordinate, pt2 is lower right (lo,la) coordinate
						2: pt1 is the centor of the circle and pt2 is (R,0) where R is the redius
			pt1:		(lo,la) point
			pt2:		see 'type'
Beispiel #20
0
import collections
from flask.ext.mysql import MySQL

# from flask.mysql import MySQL
import os
import logging
from logging.handlers import RotatingFileHandler

mysql = MySQL()
# app = Flask(__name__,static_url_path='')
app = Flask(__name__)

cuenta = 0

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = os.environ.get("BDB_MYSQL_USER")
app.config["MYSQL_DATABASE_PASSWORD"] = os.environ.get("BDB_MYSQL_PASS")
app.config["MYSQL_DATABASE_DB"] = os.environ.get("BDB_MYSQL_DB")
app.config["MYSQL_DATABASE_HOST"] = os.environ.get("BDB_MYSQL_HOST")
mysql.init_app(app)


# Render templates


@app.route("/perfmon/")
@app.route("/perfmon/<cust>")
def perfmon(cust=None):

    kpi = "RegisteredPhones"
    domain = "/UK%"
Beispiel #21
0
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL
import os


mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = os.environ["MYSQL_USER"]
app.config["MYSQL_DATABASE_PASSWORD"] = os.environ["MYSQL_PASSWORD"]
app.config["MYSQL_DATABASE_DB"] = "ItemListDb"
app.config["MYSQL_DATABASE_HOST"] = os.environ["MYSQL_URL"]
app.config["MYSQL_DATABASE_PORT"] = 3306


mysql.init_app(app)

api = Api(app)


class AuthenticateUser(Resource):
    def post(self):
        try:
            # Parse the arguments

            parser = reqparse.RequestParser()
            parser.add_argument("email", type=str, help="Email address for Authentication")
            parser.add_argument("password", type=str, help="Password for Authentication")
Beispiel #22
0
            config_cache[key] = m.group(1)
        else:
            config_cache[key] = ""
    return config_cache[key]


app = Flask(__name__)

app.config["DEBUG"] = True
app.logger.setLevel(logging.DEBUG)
logfile = join(abspath(dirname(__file__)), "data/server.log")
loghandler = logging.FileHandler(logfile)
app.logger.addHandler(loghandler)

app.config["MYSQL_DATABASE_HOST"] = "localhost"
app.config["MYSQL_DATABASE_USER"] = config("MYSQL_USER")
app.config["MYSQL_DATABASE_PASSWORD"] = config("MYSQL_PASS")
app.config["MYSQL_DATABASE_DB"] = config("MYSQL_DB")
app.config["MIN_CONFIDENCE"] = float(config("CONFIDENCE_THRESHOLD"))
app.config["MAX_SPAM"] = float(config("SPAM_THRESHOLD"))
app.config["DOCS_PER_PAGE"] = 20

mysql = MySQL()
mysql.init_app(app)


def get_db():
    if not hasattr(g, "db"):
        g.db = mysql.connect()
    return g.db
Beispiel #23
0
#!/usr/bin/python
from flask import Flask, render_template, request, flash, Session, url_for, redirect
from flaskext.mysql import MySQL
from flask.ext.login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
import os

mysql = MySQL()
app = Flask(__name__)
app.config["MYSQL_DATABASE_USER"] = "admin"
app.config["MYSQL_DATABASE_PASSWORD"] = "admin"
app.config["MYSQL_DATABASE_DB"] = "ProjetSGBD"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)

app.config["SECRET_KEY"] = "secret"
app.config["IMAGE_FOLDER"] = "static/images/recettes"

login_manager = LoginManager()
login_manager.init_app(app)


class User(UserMixin):
    """docstring for User"""

    def __init__(self, login, id, active=True):
        self.login = login
        self.id = id
        self.active = active

        cursor = mysql.connect().cursor()
        query = "SELECT * FROM Eleve WHERE Id_eleve = " + str(id)
from __future__ import print_function
from flask import Flask
from flask import request, redirect, url_for, render_template, send_from_directory, session
from flask.ext.mysql import MySQL
from werkzeug import secure_filename
from mimetypes import MimeTypes
import os
import time
import logging
import boto3
from boto3.s3.transfer import S3Transfer
from config import *

image_uploader = Flask(__name__)
mysql = MySQL()
image_uploader.config["MYSQL_DATABASE_USER"] = DB_USER
image_uploader.config["MYSQL_DATABASE_PASSWORD"] = DB_PASS
image_uploader.config["MYSQL_DATABASE_DB"] = DB_NAME
image_uploader.config["MYSQL_DATABASE_HOST"] = DB_HOST
mysql.init_app(image_uploader)

#
# Help functions
#
def allowed(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in IMAGE_TYPES


def put_s3_objetct(image_name, storage_dir):
    mime = MimeTypes()
    s3 = boto3.client("s3", region_name=AWS_REGION)
Beispiel #25
0
## Configs
baseWebRoot = "http://192.168.1.20/xbmc/"
thumbRoot = "/mnt/data/xbmc/thumbs/"
resizeThumbs = True
resizedThumbRoot = "/var/www/xbmc/thumbs/"
## DB Config
db_host = "localhost"
db_user = "xbmc"
db_password = "xbmc"
db_name = "MyVideos75"


app = Flask(__name__)

app.config["MYSQL_DATABASE_HOST"] = db_host
app.config["MYSQL_DATABASE_USER"] = db_user
app.config["MYSQL_DATABASE_PASSWORD"] = db_password
app.config["MYSQL_DATABASE_DB"] = db_name
mysql = MySQL()
mysql.init_app(app)


## Routes
@app.route("/")
def home():
    navContext = {"main": "Home", "bread": [["/", "Home"]]}
    mediaCount = {"tveps": 0, "songs": 0}
    movies = getMovies()
    mediaCount["movies"] = len(movies)

    return render_template("home.html", navContext=navContext, mediaCount=mediaCount)
import time
import signal
import sys
from flask import Flask, render_template
from flask.ext.mysql import MySQL
from flask.ext.socketio import SocketIO, emit
from queries import make_bookings, view_bookings, update_schedule

app = Flask("ColumbiaShuttleServices")
app.config["DEBUG"] = True
app.config["secret"] = "css"
app.config["MYSQL_DATABASE_USER"] = "psp2133"
app.config["MYSQL_DATABASE_PASSWORD"] = "horcrux1"
app.config["MYSQL_DATABASE_DB"] = "cs4111"
app.config["MYSQL_DATABASE_HOST"] = "shuttle.cfs9lab4dyj4.us-west-2.rds.amazonaws.com"
app.config["MYSQL_DATABASE_PORT"] = 3306

socketio = SocketIO(app)
viewBookingsSession = None
makeBookingsSession = None
updateScheduleSession = None

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


class ViewBookings:
    qs = view_bookings()
    bookingid = None
Beispiel #27
0
from uuid import uuid4
from json import dumps
from base64 import b64encode
from datetime import datetime, timedelta
from hashlib import sha1
import time, os, json, base64, hmac, urllib


global app, mysql, mail, baseS3Url

app = Flask(__name__)

mysql = MySQL()
baseS3Url = "https://filshack.s3.amazonaws.com/"

app.config["MYSQL_DATABASE_USER"] = "b0c31b0e5f6108"
app.config["MYSQL_DATABASE_PASSWORD"] = "a28c9ca5243937f"
app.config["MYSQL_DATABASE_HOST"] = "us-cdbr-iron-east-03.cleardb.net"
app.config["MYSQL_DATABASE_DB"] = "heroku_d4e136b9b4dc6f5"
app.config["AWS_S3_BUCKET"] = "filmshack"
app.config["AWS_ACCESS_KEY_ID"] = "AKIAJMYLTY2I4EHYNUVA"
app.config["AWS_SECRET_ACCESS_KEY"] = "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"
app.config["SECRET_KEY"] = "SET T0 4NY SECRET KEY L1KE RAND0M H4SH"

"""
url = urlparse.urlparse(os.environ['DATABASE_URL'])
app.config['MYSQL_DATABASE_USER'] = url.username
app.config['MYSQL_DATABASE_PASSWORD'] = url.password
app.config['MYSQL_DATABASE_HOST'] = url.hostname
app.config['MYSQL_DATABASE_DB'] = "heroku_d4e136b9b4dc6f5"
app.config['SECRET_KEY'] = 'SET T0 4NY SECRET KEY L1KE RAND0M H4SH'
Beispiel #28
0
from flask import Flask, render_template, redirect, request, session
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)
app.config["MYSQL_DATABASE_USER"] = "serverstudy"
app.config["MYSQL_DATABASE_PASSWORD"] = "serverstudy!@#"
app.config["MYSQL_DATABASE_DB"] = "serverstudy"
app.config["MYSQL_DATABASE_HOST"] = "data.khuhacker.com"
app.config["MYSQL_CHARSET"] = "utf-8"
app.secret_key = "safdsfasffaasaf"
mysql.init_app(app)
con = mysql.connect()
cur = con.cursor()
cur.execute("SELECT * FROM hu")
data = cur.fetchall()


@app.route("/", methods=["POST", "GET"])
def basic():
    return render_template("index.html")


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


@app.route("/logincheck", methods=["POST"])
def check():
    inputID = request.form["id"]
Beispiel #29
0
from flask import Flask, render_template, json, request, redirect, session, jsonify, url_for
from flask.ext.mysql import MySQL
from flask.ext.triangle import Triangle
from werkzeug import generate_password_hash, check_password_hash
from werkzeug.wsgi import LimitedStream
import collections
import uuid
import os

mysql = MySQL()
app = Flask(__name__)
Triangle(app)
app.secret_key = "why would I tell you my secret key?"

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "root"
app.config["MYSQL_DATABASE_PASSWORD"] = "badag"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)

# Default setting
pageLimit = 3


class StreamConsumingMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        stream = LimitedStream(environ["wsgi.input"], int(environ["CONTENT_LENGTH"] or 0))
Beispiel #30
0
from flask import Flask, render_template, request, json
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "felix"
app.config["MYSQL_DATABASE_PASSWORD"] = "felix"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
mysql.init_app(app)


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


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


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

    try:

        # read the posted values from the UI