Beispiel #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
Beispiel #2
0
import os
import config

from flask import Flask, abort, g, request, url_for, redirect
from flask import render_template as flask_render_template
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

def render_template(template, *args, **kwargs):
    lang_path = config.LANG_MAP.get(g.current_lang, 'en_US.ISO8859-1')
    kwargs['include_template'] = "%s/htdocs/%s" % (lang_path, template)
    return flask_render_template(template, *args, **kwargs)

@app.before_request
def before():
    if request.view_args and 'lang_code' in request.view_args:
        if request.view_args['lang_code'] not in config.LANG_CODES:
            print 'aborting'
            return abort(404)
Beispiel #3
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
Beispiel #4
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()
Beispiel #5
0
import os 
from flask import Flask, make_response
from flask.ext import restful
from flask.ext.pymongo import PyMongo
from flask.ext.assets import Environment, Bundle
from bson.json_util import dumps
import jinja2

# basic paths
MONGO_URL = "mongodb://localhost:27017/violence"
ASSETS_DIR=os.path.join(os.path.dirname(os.path.abspath(__file__)), '../static')

# app
app = Flask(__name__)
app._static_folder = ASSETS_DIR
app.config['SECRET_KEY'] = 'secret!'
app.debug = True
app.jinja_loader=jinja2.FileSystemLoader('templates')

# compass config
assets = Environment(app)

main_scss = Bundle('scss/style.scss', 'scss/media.scss', filters='compass', output='css/style.css')
assets.register('main_scss', main_scss)

# mongo db
app.config['MONGO_URI'] = MONGO_URL
mongo = PyMongo(app)

def output_json(obj, code, headers=None):
    resp = make_response(dumps(obj), code)
databases = {
    'login': 'sqlite:///login.db',
    'requests': 'sqlite:///requests.db',
    'ServerState': 'sqlite:///ServerState.db'
}
"""
databases = {
    "login": "sqlite:///login.sqlite3",
    "requests": "sqlite:///requests.sqlite3",
    "ServerState": "sqlite:///ServerState.sqlite3",
}
app.config["SQLALCHEMY_BINDS"] = databases


db = SQLAlchemy(app)
app._static_folder = "/Users/macx/Desktop/大空调/myproject/static/"

room_id = 724
server_mode = "cold"
client_state = "off"
server_state = "off"

server_state_temp = "off"
server_mode_temp = "cold"
client_mode = "cold"
client_power = 0.8

queue = []


def ClientWork(start, room_id):
Beispiel #7
0
from flask import session as login_session
import random
import string
import os
from math import floor
from OpenSSL import SSL

from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2
import json
from flask import make_response
import requests

app = Flask(__name__)
app._static_folder = "~/Desktop/onlineU/static"

HOST = '0.0.0.0'
PORT = 80

CLIENT_ID = json.loads(
    open('client_secrets.json', 'r').read())['web']['client_id']
APPLICATION_NAME = "Education"


# Connect to Database and create database session
engine = create_engine('sqlite:///' + DATABASE_NAME)
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()
Beispiel #8
0
import sys
import logging
import numpy as np

from flask import Flask, request, jsonify, make_response, current_app, \
        render_template
from datetime import datetime
from bus import bus
from flask.ext.cors import CORS

app = Flask(__name__)
app._static_folder = 'static'
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)


cors = CORS(app, resources={r"/latlng/*": {"origins": "*"}})

bus_stops = {'10813': [-0.0984574616503, 51.3760929581],
 '1164': [-0.118444497979, 51.4013254207],
 '1441': [-0.111505659588, 51.3886330116],
 '14622': [-0.11532824762, 51.4624163884],
 '15100': [-0.127886565845, 51.4190123595],
 '15101': [-0.123989076582, 51.4147954483],
 '15102': [-0.121592866634, 51.4076438324],
 '15104': [-0.11950429888, 51.4038783631],
 '15105': [-0.119676700562, 51.4045826277],
 '15106': [-0.114913800215, 51.3952345961],
 '15107': [-0.11553210181, 51.3969801748],
 '15108': [-0.112343246015, 51.3902831629],
 '15110': [-0.109847701645, 51.3852700354],
Beispiel #9
0
from flask import Flask, url_for
from flask import render_template
from random import randint
import json

app = Flask(__name__)
app._static_folder = "/var/www/junyi/flask"
max = 10

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

@app.route('/addition')
@app.route('/addition/<name>')
def addition(name="Junyi"):
	num_list = []
	while len(num_list) < 3:
		num_list.append([randint(1, 5), randint(1,5)])
		
	return render_template('addition.html', name=name, num_list=num_list)

if __name__ == '__main__':
	app.run(host='0.0.0.0', debug=True)
Beispiel #10
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
	
	# print('received message: ' + str(message))
Beispiel #11
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
Beispiel #12
0
import os
import sys
import subprocess
from flask_restful import Api, Resource
from flask import Flask, send_file, send_from_directory, safe_join, request, Response, abort

app = Flask(__name__)
api = Api(app)
app._static_folder = "/var/www/dc/dc/static/"

from rest import *

#Define API endpoints
#Map classes to API endpoints
api.add_resource(CharacterList, '/characters.json')
api.add_resource(TeamsList, '/teams.json')
api.add_resource(ShowsList, '/shows.json')
api.add_resource(MoviesList, '/movies.json')
api.add_resource(ComicsList, '/comics.json')
api.add_resource(CreatorsList, '/creators.json')
api.add_resource(CharacterUpdate, '/characters/<string:id>.json')
api.add_resource(TeamsUpdate, '/teams/<string:id>.json')
api.add_resource(ShowsUpdate, '/shows/<string:id>.json')
api.add_resource(MoviesUpdate, '/movies/<string:id>.json')
api.add_resource(ComicsUpdate, '/comics/<string:id>.json')
api.add_resource(CreatorsUpdate, '/creators/<string:id>.json')
api.add_resource(searchDB, '/search/<string:search_text>.json')



import GPIOController

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():
    global lLock
from flask import Flask,make_response,render_template,redirect,session,escape,request,url_for

from mysql import MySQLDatabase
from imdb_module import IMDataBase

import json

db = MySQLDatabase('imdb','imdb','imdb','localhost')
# imDB = IMDataBase()

DEBUG = 1

# http://flask.pocoo.org/docs/0.10/quickstart/
app = Flask(__name__)
app._static_folder = '/Users/juan/say-it-louder/static/'

# set the secret key.  keep this really secret:
app.secret_key = 'This_is_a_secret'


######################################################################################################################
#                                        Main App and common options                                                 #
######################################################################################################################

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

    # if not 'user_name' in session:
    #     if DEBUG:
    #         print "Not logged in. Redirecting to /login"
    #     return redirect("/login")
        self.desc_map = {
            self.data : "data",
            self.event : "event",
            self.id : "id"
        }

    def encode(self):
        if not self.data:
            return ""
        lines = ["%s: %s" % (v, k)
                 for k, v in self.desc_map.iteritems() if k]

        return "%s\n\n" % "\n".join(lines)

app = Flask(__name__)
app._static_folder = './'
subs = []

@app.route('/')
def root():
    return app.send_static_file('index.html')

import os
@app.route('/<path:path>')
def static_proxy(path):
    return app.send_static_file(path)

@app.route("/next_video")
def push_nextVideo():
    def notify():
        msg = "NEXT!"
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)
Beispiel #17
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

    return render_template('/index.html', answer=answer, previous_text=reviewText)
Beispiel #18
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.')
            return redirect(url_for('index'))
Beispiel #19
0
import json
from flask import Flask, request, redirect, url_for, send_from_directory
import frame
import classifier
import api
import numpy as np
import sys
import os
import glob
import random
import imageio

# Setup Flask app.
app = Flask(__name__)
app.debug = True
app._static_folder = '../client'


# Setup classifier.
# Creates classification network and node ID --> English string lookup.
# node_lookup = classifier.NodeLookup()
videoFolder = './server/videos'
cacheFolder = './server/cache'
# createdGraph = False

if "cache" not in os.listdir('./server'):
    os.mkdir("./server/cache")

# Routes
@app.route('/')
def root():
Beispiel #20
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
Beispiel #21
0
            # then it should be ), otherwise raise an exception
            self._expect('RPAREN')

            # 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()
Beispiel #22
0
from flask import Flask, request, render_template, redirect
from cards import card_dict
# set the project root directory as the static folder, you can set others.

app = Flask(__name__, static_url_path='')
app._static_folder = "static/"


@app.route('/')
def root():
    f = open("card.txt", 'r')
    cur_card = f.read()
    f.close()
    return render_template('index.html', card=card_dict[cur_card])


@app.route('/set', methods=['GET'])
def set_card():
    ranks = ['2', '3', '4', '5', '6',
             '7', '8', '9', '10', 'j',
             'q', 'k', 'a']
    return render_template('set_card.html', ranks=ranks)


@app.route('/save', methods=['GET'])
def save_card():
    suits = ['h', 'd', 'c', 's']
    ranks = ['a', 'k', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q']

    bin = request.args.get("bin")
    if bin:
Beispiel #23
0
    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)
Beispiel #24
0
from flask import url_for
from flask import session
from flask import jsonify
from flask.ext.scrypt import generate_random_salt
from flask.ext.assets import Environment, Bundle
from flask_oauthlib.client import OAuth
from flask_oauthlib.client import OAuthException
# from flask import make_response
# from flask import jsonify
from sqlalchemy import func, cast, Date

init_logging('pajbot')
log = logging.getLogger('pajbot')

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

assets = Environment(app)

# Basic CSS and Javascript:
# Available under: base_css, semantic_css, base_js
base_css = Bundle('css/base.min.css',
        output='css/base.gen.%(version)s.css')
semantic_css = Bundle('semantic/semantic.min.css',
        output='semantic/semantic.gen.%(version)s.css')
base_js = Bundle('scripts/base.js', filters='jsmin',
        output='scripts/base.gen.%(version)s.js')
semantic_js = Bundle('semantic/semantic.min.js',
        output='semantic/semantic.gen.%(version)s.js')
deacons_list = []
for deacon in deacons_data.iterrows():
    deacons_list.append({
        'name': deacon[1][1],
        'parish': deacon[1][3],
        'lat':  deacon[1][5],
        'lng': deacon[1][6]
    })

names_lowercase_to_uppercase = {x['name'].lower(): x['name'] for x in deacons_list+elders_list+members_list}
info_for_person = {x['name']: x for x in deacons_list+elders_list+members_list}

print "Found", len(members_list), "members,", len(deacons_list), "deacons, and", len(elders_list), "elders."

app = Flask(__name__)
app._static_folder = "."

@app.route("/members")
def members():
    return jsonify(grouped_members_list)

@app.route("/deacons")
def deacons():
    return jsonify(deacons_list)

@app.route("/elders")
def elders():
    return jsonify(elders_list)

def autocomplete_for(string):
    return [v for k, v in names_lowercase_to_uppercase.iteritems() if all([y in k for y in string.lower().split()])]