Example #1
0
def create_app(config_name):
    if config_name != "test":
        print "Application created based on config_name: %s" % (config_name)

    app = Flask(__name__)
    app._static_folder = "static"
    app.debug = True

    app_config = config[config_name]
    app.config.from_object(app_config)
    config[config_name].init_app(app)

    app.secret_key = "tell you"

    db.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    pages.init_app(app)
    from .send_mail import sendmail as send_mail_blueprint

    app.register_blueprint(send_mail_blueprint)

    from .webviews import webviews as webviews

    app.register_blueprint(webviews)
    return app
Example #2
0
import struct
import sys, os
import binascii
import fcntl
import time
import random
import threading
from Server import Server
from multiprocessing import Process

import lxml
from lxml.html.clean import Cleaner

app = Flask(__name__)
socketio = SocketIO(app)
app._static_folder = "/home/tyler/Documents/SmartHome/cSocket-Server/"


@app.route("/")
def root():
    return app.send_static_file("index.html")
    # return "hello"


@socketio.on("checkForNew")
def handle_message(message):
    print "got check request"
    print str(json.dumps(server.getDevList()))
    socketio.emit("deviceList", str(json.dumps(server.getDevList())))  # {"list": server.getDevList()})
    # print json.dumps(server.getDevList());
    pass
config = ConfigParser.ConfigParser()
vibratorManager = VibratorManager()

update_intervall = 1
sequence_time = 120
bEnd = False
tThread = None

lLock = threading.Lock()

from flask import Flask
from flask import send_from_directory

app = Flask(__name__, static_url_path="/")
app._static_folder = os.path.dirname(os.path.realpath(__file__))

app.debug = False


@app.route("/points/<int:value>/")
def setPoints(value):
    global lLock
    lLock.acquire()
    vibratorManager.set_points(value)
    lLock.release()
    return "1"


@app.route("/points/")
def getPoints():
Example #4
0
from models import User
from flask import Flask, request, session, redirect, url_for, render_template, flash
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app._static_folder = "/home/pratik/Downloads/MovieBud/moviebud/static"


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


@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        repassword = request.form["password2"]

        if len(username) < 1:
            flash("Your username must be at least one character.")
        elif len(password) < 5:
            flash("Your password must be at least 5 characters.")
        elif password != repassword:
            flash("Passwords do not match")
        elif not User(username).register(password):
            flash("A user with that username already exists.")
        else:
            session["login"] = username
            flash("Logged in.")
Example #5
0
            # return the previous saved value
            return expr_value
        elif self._accept("DOLLAR"):
            # if it's a dollar we can break
            # raise SyntaxError('Expected $')
            return "not valid"
        else:
            # return "not valid"
            return "not valid"
            # raise SyntaxError('Expect NUMBER or LPAREN')


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


@app.route("/echo", methods=["POST"])
def my_form_post():
    e = ExpressionEvaluator()
    s = request.form["text"]
    b = e.parse(s)
    b = str(b)
    return render_template("index.html", text=b)


if __name__ == "__main__":
    app.debug = True
    app._static_folder = "templates/"
    app.run()
Example #6
0
#!/usr/bin/env python
from flask import Flask, render_template, Response, send_file

# Raspberry Pi camera module (requires picamera package)
from camera_pi import Camera
import tempfile
from datetime import datetime
import os, sys, re

app = Flask(__name__)
path = os.path.dirname(os.path.realpath(__file__))
app._static_folder = path + "/static"


@app.route("/")
def index():
    """Video streaming home page."""
    return render_template("index.html")


def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n")


@app.route("/video_feed")
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera()), mimetype="multipart/x-mixed-replace; boundary=frame")
Example #7
0
    return lastnonce


def get_user_by_key(app, key):
    """
    An SQLAlchemy User getting function. Get a user by public key.

    :param str key: the public key the user belongs to
    """
    user = ses.query(SLM_User).join(UserKey).filter(UserKey.key == key).first()
    return user


# Setup flask app and FlaskBitjws
app = Flask(__name__)
app._static_folder = "%s/static" % os.path.realpath(os.path.dirname(__file__))

FlaskBitjws(
    app, privkey=cfg.PRIV_KEY, get_last_nonce=get_last_nonce, get_user_by_key=get_user_by_key, basepath=cfg.BASEPATH
)

# Setup logging
logfile = cfg.LOGFILE if hasattr(cfg, "LOGFILE") else "server.log"
loglevel = cfg.LOGLEVEL if hasattr(cfg, "LOGLEVEL") else logging.INFO
logging.basicConfig(filename=logfile, level=loglevel)
logger = logging.getLogger(__name__)

# Setup CORS
CORS(app)

# Setup database
Example #8
0
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir

app = Flask(__name__, static_folder="./public/css/style.css")
app.config.from_object("config")
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = "login"
oid = OpenID(app, os.path.join(basedir, "tmp"))
app._static_folder = os.path.abspath("static/style.css")
print os.path.abspath(app._static_folder)
from app import views, models
Example #9
0
import os
import config

from flask import Flask, render_template, abort, g, request
from distros_installs import distros_installs

from flask.ext.babel import Babel

app = Flask(__name__)
app._static_folder = os.getcwd() + "/website/static"
app.config["SECRET_KEY"] = os.urandom(64)
if app.debug:
    from flaskext.lesscss import lesscss

    lesscss(app)
# app.config.from_pyfile('translations.cfg')
babel = Babel(app, default_locale="en_US.ISO8859-1")

from events import get_rss


@babel.localeselector
def get_locale():
    lang = request.cookies.get("lang")
    if lang in config.LANGUAGES:
        return lang
    return request.accept_languages.best_match(config.LANGUAGES)


@app.route("/")
def index():
Example #10
0
import os
import re
import datetime
from flask import Flask, send_from_directory, request, jsonify, g, Response
from database import db, Sensor, Measurement, create_tables, list_to_dict
import xml.etree.ElementTree as ElementTree
import os

app = Flask(__name__)
app.debug = True
# get the port from the app cloud or use fallback
port = int(os.getenv("VCAP_APP_PORT") or 8080)

app._static_folder = "www/"


@app.route("/")
def index():
    """
        Home page of the weather app
    """
    return app.send_static_file("index.html")


@app.route("/js/<path:path>")
def send_js(path):
    """
        Serves static javascript files
    """
    return send_from_directory("www/js/", path)
from flask import Flask
import flask
import pandas as pd
from collections import defaultdict
import pymongo


app = Flask(__name__)
app.config.from_object(__name__)
app._static_folder = "static"
DF = None
DB = None
INDEX = None
TITLE = None


def save_to_db(form, title, db=DB):
    """
    PURPOSE:    Triggered from submit button on form.
                Saves training labels for words in article
                headline in mongodb
    INPUT:      form (html form) - fields are correct labels
                title (str) - headline of article
                db (pymongo obj) - conn to mongodb
    OUTPUT:     None
    """
    labels = defaultdict(list)
    for position, word in enumerate(title.split()):
        word = word.replace(".", "[dot]")
        word = word.replace("$", "[dol]")
        labels[word].append({"position": position, "label": "other", "POS": ""})
Example #12
0
"""Flask demo"""
from flask import Flask, render_template, request
import json
import sys

sys.path.append("../PREDICTOR")
from satisfcation_predictor import Predictor

# Init Flas app and Twitter api
app = Flask(__name__)
app._static_folder = "./static/"
predictor = None


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


@app.route("/show", methods=["GET", "POST"])
def show_tweets():
    reviewText = request.form["screen_name"].encode("ascii", "ignore").lower().strip()
    print reviewText
    try:
        print "Review text is ", reviewText
        answer = predictor.predict(reviewText)
        print answer
    except Exception as e:
        print "Some error", reviewText, "\n", str(e)
    else:
        pass
Example #13
0
from flask import Flask
from base.views import blueprint as main_blueprint

app = Flask(__name__)
app._static_folder = "base/static"
app.config.update(DEBUG=True, JQUERY="", CFG_SITE_NAME="Invenio Software")
app.register_blueprint(main_blueprint)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
Example #14
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
from flask import Flask
from flask.ext.cors import CORS

# assets dir
basedir = os.path.dirname(os.path.realpath(__file__))
ASSETS_DIR = os.path.join(os.path.dirname(basedir), "client")

# config file
try:
    if os.environ["SPACEGAME_ENV"] == "test":
        config_path = os.path.join(os.path.dirname(basedir), os.path.join("tests", "config.json"))
except KeyError:  # spacegame env_path does not exist
    config_path = os.path.join(os.path.dirname(basedir), "config.json")

with open(config_path) as config_file:
    config = json.load(config_file)

# init app
app = Flask(__name__)
CORS(app)  # needed for automated testing

# config
app._static_folder = ASSETS_DIR
app.secret_key = config["secret"]

import server.routes
# encoding: utf-8

from flask import Flask, flash, url_for, render_template
from flask import request, redirect, make_response, session
from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime
import os, re
import sys

reload(sys)
sys.setdefaultencoding("utf-8")

app = Flask(__name__)
app.config.from_pyfile("app.cfg")
db = SQLAlchemy(app)
app._static_folder = "/Users/macx/Desktop/大空调/myproject/static/"

# imagepath = os.path.join(os.getcwd(), "static/images")

room_id = 724
server_mode = "cold"
client_state = "off"
client_mode = "cold"
client_power = 0.8

queue = []


def ClientWork(start, room_id):
    global queue
    if start == "on/refresh":
Example #16
0
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.script import Server
from flask.ext.sqlalchemy import SQLAlchemy
import os
import yaml


# Initialize Application
app = Flask(__name__, template_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), "../views"))
app._static_folder = "../../static"


# Load Configs
parsed_config = None
config = {}
config_path = None

env = os.environ.get("FLASK_ENV")

if env == "prod":
    config_path = "config_prod.yaml"
else:
    config_path = "config_dev.yaml"

with open(config_path, "r") as stream:
    parsed_config = yaml.load(stream)


config["JWT_ALGORITHM"] = "HS512"
config["BCRYPT_ROUNDS"] = 12
Example #17
0
from flask import Markup
from flask import redirect

# from flask import make_response
# from flask import jsonify
from sqlalchemy import func, cast, Date

init_logging("tyggbot")
log = logging.getLogger("tyggbot")

cron = BackgroundScheduler(daemon=True)

cron.start()

app = Flask(__name__)
app._static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
app.register_blueprint(api.page)

config = configparser.ConfigParser()

parser = argparse.ArgumentParser(description="start the web app")
parser.add_argument("--config", default="config.ini")
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", type=int, default=2325)
parser.add_argument("--debug", dest="debug", action="store_true")
parser.add_argument("--no-debug", dest="debug", action="store_false")
parser.set_defaults(debug=False)

args = parser.parse_args()

config = load_config(args.config)
Example #18
0
from flask import Flask, render_template
from models.conectDB import MongodbDOA, PostgresDAO
app = Flask(__name__)
app._static_folder = "/templates"

pgDB = PostgresDAO()

@app.route("/")
def main():
    pgDB.insertCompany(),
    return render_template('index.html')

@app.route("/cadastro")
def singup():
    pass
@app.route("/login")
def login():
    pass
@app.route('/admin')





if __name__ == "__main__":
    app.run()