Пример #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
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
Пример #3
0
from flask import Flask, render_template, request
from flaskext.mysql import MySQL
import os
import time
from decimal import Decimal

# Getting date/time
localtime = time.strftime("%d/%m/%Y %H:%M:%S")
currentdate = time.strftime("%Y-%m-%d")

mysql = MySQL()
app = Flask(__name__)
app.config["MYSQL_DATABASE_USER"] = "cogtrader"
app.config["MYSQL_DATABASE_PASSWORD"] = "explain123"
app.config["MYSQL_DATABASE_DB"] = "cogtrader"
app.config["MYSQL_DATABASE_HOST"] = "134.168.21.74"
mysql.init_app(app)
cursor = mysql.connect().cursor()

# On Bluemix, get the port number from the environment variable VCAP_APP_PORT
# When running this app on the local machine, default the port to 8080
port = int(os.getenv("VCAP_APP_PORT", 8080))


y_trend = None
cur_trend = None
deal_class = None
cur_osci_trend = None


def lastLowest(paperid):
Пример #4
0
from flask import Flask
from flask_restful import Resource, Api
from flask.ext.mysql import MySQL
from random import randint
import json

mysql = MySQL()

# Initialize Flask app
app = Flask(__name__)

# MySQL Config
app.config["MYSQL_DATABASE_USER"] = ""
app.config["MYSQL_DATABASE_PASSWORD"] = ""
app.config["MYSQL_DATABASE_DB"] = ""
app.config["MYSQL_DATABASE_HOST"] = ""

mysql.init_app(app)

api = Api(app)


class Quote(Resource):
    def get(self):
        try:

            # Connect to database
            conn = mysql.connect()
            cursor = conn.cursor()

            # Count rows
Пример #5
0
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")


@app.route("/logout")
def Logout():
    session.pop("username", None)
Пример #6
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()
Пример #7
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")
Пример #8
0
from config import MYSQL_INFO

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
Пример #9
0

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]
        first_name = household[1]
        last_name = household[2]
        address = household[3]
Пример #10
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}
Пример #11
0
url = urlparse.urlparse("mysql://admin7YSeANi:ShMwe1xM2sV4@127.12.232.130:3306")

user = (url.username,)
pass1 = (url.password,)
host = (url.hostname,)
port = url.port


app.config["MYSQL_DATABASE_PORT"] = 3306
# host1=os.getenv('OPENSHIFT_MYSQL_DB_HOST')
app.config["MYSQL_DATABASE_USER"] = "admin7YSeANi"
app.config["MYSQL_DATABASE_PASSWORD"] = "ShMwe1xM2sV4"
app.config["MYSQL_DATABASE_DB"] = "projectdb_schema"

# app.config['MYSQL_DATABASE_HOST'] = 'ex-std-node455.prod.rhcloud.com'
app.config["MYSQL_DATABASE_HOST"] = "127.12.232.130"


mysql.init_app(app)
# mainpage
@app.route("/")
def main():
    return render_template("index.html")


# mainpage duplicate
@app.route("/home")
def home():
    return render_template("index.html")

Пример #12
0
import logging
from flask import Flask, render_template, json, request, redirect, session
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
import uuid
import os

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

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "root"
app.config["MYSQL_DATABASE_PASSWORD"] = "root"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = "127.0.0.1"
app.config["MYSQL_DATABASE_PORT"] = 8889
app.config["UPLOAD_FOLDER"] = "static/Uploads"
mysql.init_app(app)

# pagination limit
pageLimit = 2

# gereral fxn to call a sql stored procedure
def callProcedure(proc, dataTuple, isSelect):
    try:
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.callproc(proc, dataTuple)
        data = cursor.fetchall()
        cursor.nextset()
Пример #13
0
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__, static_url_path="")
auth = HTTPBasicAuth()

try:
    mysql = MySQL()

    info = open("../log_mysql.txt", "r")
    lines = info.readlines()
    # MySQL configurations
    app.config["MYSQL_DATABASE_USER"] = lines[4]
    app.config["MYSQL_DATABASE_PASSWORD"] = lines[5]
    app.config["MYSQL_DATABASE_DB"] = lines[6]
    app.config["MYSQL_DATABASE_HOST"] = lines[7]
    mysql.init_app(app)

except IOError:
    print "Not connected with a MySQL Charm"


@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({"error": "Bad request"}), 400)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({"error": "Not found"}), 404)
Пример #14
0
from flask import Flask, render_template, json, request, redirect, session
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
import uuid, os

app = Flask(__name__)

mysql = MySQL()

# MySQL configurations
docker_host = "mysql"
localhost = "127.0.0.1"
app.config["MYSQL_DATABASE_USER"] = "root"
app.config["MYSQL_DATABASE_PASSWORD"] = "sql"
app.config["MYSQL_DATABASE_DB"] = "BucketList"
app.config["MYSQL_DATABASE_HOST"] = docker_host
mysql.init_app(app)
app.secret_key = "thiskeyissosecret"
pageLimit = 5
app.config["UPLOAD_FOLDER"] = "static/Uploads"


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


@app.route("/showSignUp")
def showSignUp():
    return render_template("signup.html")
Пример #15
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"]
Пример #16
0
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
Пример #17
0
from flask.ext.mysql import MySQL
import os
from functools import update_wrapper
from flask import Flask, request, jsonify, session, url_for, redirect, render_template, g, flash, make_response
from data import *
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)
Пример #18
0
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):
    return render_template("404.html"), 404
Пример #19
0
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")


@app.route("/signUp", methods=["GET"])
def show_sign_up():
Пример #20
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")
Пример #21
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)
Пример #22
0
# 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%"

    # All Good, let's call MySQL
    conn = mysql.connect()
Пример #23
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)
Пример #24
0
        config["host"] = "francescg.mysql.pythonanywhere-services.com"
        config["user"] = "francescg"
        config["passwd"] = "sapastre"
        config["db"] = "francescg$per_tests"
        config["logdir"] = "/home/francescg/tests_nauticos/logs/"

    return config


conf = config.get_config()
mysql = MySQL()
app = Flask(__name__)
app.config["MYSQL_DATABASE_USER"] = conf["user"]
app.config["MYSQL_DATABASE_PASSWORD"] = conf["passwd"]
app.config["MYSQL_DATABASE_DB"] = conf["db"]
app.config["MYSQL_DATABASE_HOST"] = conf["host"]
mysql.init_app(app)

TOPIC_ID = 0

logging.basicConfig(filename=conf["logdir"] + "server.log", level=logging.DEBUG)
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")

logging.debug("OK!")


@app.route("/")
def hello_world():
    return "Hello from Flask!"

Пример #25
0
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'
"""
Пример #26
0
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)
    transfer = S3Transfer(s3)
    image_path = os.path.join(UPLOAD_DIR, image_name)
    key_name = storage_dir + "/" + image_name
Пример #27
0
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))
        environ["wsgi.input"] = stream
        app_iter = self.app(environ, start_response)
        try:
Пример #28
0
mysql = MySQL()
app = Flask(__name__)
app.secret_key = "some_secret_key"

# 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"] = os.environ["MYSQL_DB"]
for key in os.environ.keys():
    if re.match(r"MYSQL.*_TCP_PORT$", key):
        mysqlDbPort = os.environ[key]
        app.config["MYSQL_DATABASE_PORT"] = int(mysqlDbPort)
    if re.match(r"MYSQL.*_TCP_ADDR$", key):
        mysqlDbHost = os.environ[key]
        app.config["MYSQL_DATABASE_HOST"] = mysqlDbHost

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")