def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) Bootstrap(app) app.config['SECRET_KEY']= ## insert your secret key @app.route('/', methods=('GET', 'POST')) def index(): if request.method == 'POST': try: question = request.form['question'] except KeyError, e: print 'key eroor' print 'I got a KeyError - reason "%s"' % str(e) except:
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/') def index(): form = ExampleForm() return render_template('index.html', form=form) return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config[ 'RECAPTCHA_PUBLIC_KEY'] = '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser flash('critical message', 'critical') flash('error message', 'error') flash('warning message', 'warning') flash('info message', 'info') flash('debug message', 'debug') flash('different message', 'different') flash('uncategorized message') churn_stats = [] if request.method == "POST": #get steamid that the user has entered steamid_to_process = request.form['steamid'] churn_stats = get_stats(steamid_to_process) #print(churn_stats) return render_template('index.html', form=form, churn_stats=[churn_stats]) @app.route('/about') def about(): return render_template('about.html') @app.route('/contact') def contact(): return render_template('cover.html') return app
def create_app(configfile=None): flask_app = Flask(__name__) AppConfig(flask_app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(flask_app) # in a real app, these should be configured through Flask-Appconfig flask_app.config['SECRET_KEY'] = 'devkey' flask_app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' flask_app.register_blueprint(integral_blueprint) @flask_app.route('/') def index(): return render_template('index.html') return flask_app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' #app.config['RECAPTCHA_PUBLIC_KEY'] = \ # '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser database = r"/Users/bhatnagarakshit10/Documents/flask-bootstrap/pythonsqlite.db" conn = pythonsqllite.create_connection(database) with conn: df = pythonsqllite.read_data(conn) df = pd.read_csv( '/Users/bhatnagarakshit10/Documents/flask-bootstrap/usa_lat_long.csv', index_col=False) print(len(df)) print(len(df.to_dict('records'))) #flash('critical message', 'critical') #flash('error message', 'error') #flash('warning message', 'warning') #flash('info message', 'info') #flash('debug message', 'debug') #flash('different message', 'different') #flash('uncategorized message') #return render_template('index.html', form=form, data=df.to_dict('records'), len=len(df)) return render_template('index.html', data=df.T.to_dict().values(), len=len(df)) return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) Bootstrap(app) question_asked = [] app.config['SECRET_KEY']= '3V3PT7-TXHKXVKX82' @app.route('/', methods=('GET', 'POST')) def index(): if request.method == 'POST': reference_page_url = None try: question = request.form['question'] except KeyError: app.logger.info("No questions are given, try the 2nd route") try: question = question_asked[-1] reference_page_url = request.form['reference_page_url'] app.logger.info(f"User has given a reference page: {reference_page_url}") except: print('I got another exception that I cannot explain') raise app.logger.info(question) if not reference_page_url: question_asked.append(question) answer = qa.ask(question) else: answer = qa.ask(question, reference_page_url) app.logger.info(re.sub('\n\n', '\n', answer)) answer = re.sub('([(].*?[)])', "", answer) form1 = ExampleForm1() return render_template('answer.html', answer=answer, question=question, form=form1) form = ExampleForm() return render_template('index.html', form=form) return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) Bootstrap(app) app.config[ 'SECRET_KEY'] = "b'\xa4\xe3]\x7f)\xc5\xfbQ\x9f\x1d{\xfc\xa8\x81J\n" @app.route('/') def index(): return render_template('index.html') @app.route('/ask_me', methods=('GET', 'POST')) def ask_me(): if request.method == 'POST': try: question = request.form['question'] except KeyError as e: print('key error') print('I got a KeyError - reason "%s"' % str(e)) except: print('I got another exception, but I should re-raise') raise print(question) answer = answer_question(question) print('answer: ', answer) answer = re.sub('([(].*?[)])', "", answer) return render_template('answer.html', answer=answer, question=question) form = QuestionForm() return render_template('ask_me.html', form=form) return app
def create_app(configfile=None): app = Flask(__name__, template_folder='templates') AppConfig(app) # Install our Bootstrap extension Bootstrap(app) # For debugging (there will be errors without it) Debug(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend) app.config['BOOTSTRAP_SERVE_LOCAL'] = True app.secret_key = 'try_to_guess' # We initialize the navigation as well nav.init_app(app) return app
def create_app(configfile=None): # We are using the "Application Factory"-pattern here, which is described # in detail inside the Flask docs: # http://flask.pocoo.org/docs/patterns/appfactories/ app = Flask(__name__) # We use Flask-Appconfig here, but this is not a requirement AppConfig(app) # Install our Bootstrap extension Bootstrap(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend) # Because we're security-conscious developers, we also hard-code disabling # the CDN support (this might become a default in later versions): app.config['BOOTSTRAP_SERVE_LOCAL'] = True return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/garage') def add_numbers(): ajax_request = request.args.get('ajax_request', 0, type=str) print( "wassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\n") #open_garage() return jsonify(result=ajax_request) @app.route('/', methods=('GET', 'POST')) def index(): #form = ExampleForm() #form.validate_on_submit() # to get error messages to the browser #flash('critical message', 'critical') #flash('error message', 'error') #flash('info message', 'info') #flash('debug message', 'debug') #flash('different message', 'different') #flash('uncategorized message') flash('This application is undergoing tests', 'warning') #return render_template('index.html', form=form) return render_template('index.html') return app
def create_app(configfile=None): # We are using the "Application Factory"-pattern here, which is described # in detail inside the Flask docs: # http://flask.pocoo.org/docs/patterns/appfactories/ app = Flask(__name__) # We use Flask-Appconfig here, but this is not a requirement AppConfig(app, configfile) # Install our Bootstrap extension bootstrap.init_app(app) # Install our Misaka (Markdown) extension misaka.init_app(app) debug.init_app(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend) # # Because we're security-conscious developers, we also hard-code disabling # # the CDN support (this might become a default in later versions): # app.config['BOOTSTRAP_SERVE_LOCAL'] = False # We initialize the navigation as well nav.init_app(app) register_renderer(app, 'inverse', InverseRenderer) # REST V1 from app.blueprints.api_v1.views import api_v1_bp app.register_blueprint(api_v1_bp, url_prefix='/api/v1') return app
def create_app(configfile=None): app = Flask(__name__) AppConfig(app) Bootstrap(app) # EAM : Set limit on the number of items in cache (RAM) cache.init_app(app, config={ 'CACHE_TYPE': 'simple', 'CACHE_THRESHOLD': 1000 }) with app.app_context(): from .frontend import frontend app.register_blueprint(frontend) app.json_encoder = MiniJSONEncoder nav.init_app(app) compress.init_app(app) htmlmin.init_app(app) return app
def create_app(configfile='config.py'): app = Flask(__name__) AppConfig(app, configfile) @app.route('/', methods=['GET', 'POST']) def jet(): if request.method == 'POST': term = (request.form['term']).strip() iw = request.form['iw'] same_l0 = request.form['kind'] weight = { 'title': 1 - np.float(iw), 'image': np.float(iw), 'brand': 0 } if same_l0 == 'same': sku, hits = knn_for_product_type_web(id=term, weight=weight, same_l0=True) else: sku, hits = knn_for_product_type_web(id=term, weight=weight, same_l0=False) if sku is None: return render_template('index.html', term=term, iw=iw, kind=same_l0, no_sku='1') else: if hits == []: return render_template('index.html', term=term, iw=iw, sku=sku, kind=same_l0, no_hits='1') else: return render_template('index.html', term=term, iw=iw, sku=sku, hits=hits, kind=same_l0) else: return render_template('index.html', kind='same') @app.route('/walmart', methods=['GET', 'POST']) def walmart(): if request.method == 'POST': image_url = (request.form['image_url']).strip() sku, hits = knn_for_product_type_image_url_web(image_url=image_url) if hits == []: return render_template('walmart.html', image_url=image_url, sku=sku, no_hits='1') else: return render_template('walmart.html', image_url=image_url, sku=sku, hits=hits) else: return render_template('walmart.html') @app.route('/documentation') def doc(): md = markdown(get_readme()) content = Markup(md) return render_template('documentation.html', content=content) return app
def create_sample_app(): app = Flask('testapp') AppConfig(app) return app
def create_app(configfile=None): """Create the web application and define basic endpoints.""" # do the imports here to not shadow e.g. "import bayesian.frontend.api_v1" # by Blueprint imported here from .api_v1 import api_v1 from .exceptions import HTTPError from .utils import JSONEncoderWithExtraTypes app = Flask(__name__) AppConfig(app, configfile) cache.init_app(app) # actually init the DB with config values now rdb.init_app(app) app.rdb = rdb # We need JSON encoder that can serialize datetime.datetime app.json_encoder = JSONEncoderWithExtraTypes app.register_blueprint(api_v1) # Redirect to latest API version if /api is accessed app.route('/api')( lambda: redirect(url_for('api_v1.apiendpoints__slashless'))) # Likewise for base URL, and make that accessible by name @app.route('/') def base_url(): return redirect(url_for('api_v1.apiendpoints__slashless')) @app.errorhandler(HTTPError) def handleerrors(e): bp = app.blueprints.get(request.blueprint) # if there's an error pre-request (e.g. during authentication) in non-GET requests, # request.blueprint is not set yet if not bp: # sort by the length of url_prefix, filter out blueprints without prefix bps = reversed( sorted([(name, b) for name, b in app.blueprints.items() if b.url_prefix is not None], key=lambda tpl: len(tpl[1].url_prefix))) for bp_name, b in bps: if request.environ['PATH_INFO'].startswith(b.url_prefix): bp = b break if bp: handler = getattr(bp, 'coreapi_http_error_handler', None) if handler: return handler(e) return Response(e.error, status=e.status_code) setup_logging(app) @app.before_request def set_current_user(): g.current_user = None @app.after_request def access_control_allow_origin(response): response.headers["Access-Control-Allow-Origin"] = "*" response.headers[ "Access-Control-Allow-Headers"] = "authorization, content-type" response.headers["Access-Control-Allow-Methods"] = "DELETE, GET, HEAD, OPTIONS,"\ "PATCH, POST, PUT" response.headers["Allow"] = "GET, HEAD, OPTIONS, PATCH, POST, PUT" return response return app
from flask import Flask from flask_appconfig import AppConfig from models.user import db app = Flask(__name__) config = AppConfig() default_config = "default_config" config.init_app(app, default_settings=default_config) db.init_app(app) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': app.run(debug=True)
def create_submodule_app(): app = Flask('module.app') AppConfig(app) return app
from flask import Flask, request from flask_appconfig import AppConfig import json import log app = Flask(__name__) @app.route('/') def index(): return 'This is Github listener server' @app.route('/api/github-webhook', methods=['POST']) def github_webhook(): request_data = request.json if not request_data: return "JSON data is expected", 400 log.info("Headers from Github:\n" + json.dumps(dict(request.headers), indent=4, sort_keys=False)) log.info("Payload from Github:\n" + json.dumps(request_data, indent=4, sort_keys=False)) return "OK", 200 if __name__ == '__main__': AppConfig(app, configfile="config.py") app.config['SECRET_KEY'] = 'S3cr3t!' app.run(host='0.0.0.0', port=9000)
#!/usr/bin/env python3 import os, json, sys #, queue from flask import Flask, render_template, flash from flask_appconfig import AppConfig #from flask_bootstrap import Bootstrap from flask_socketio import SocketIO from flask_cors import CORS app = Flask(__name__) CORS(app) AppConfig(app, None) #Bootstrap(app) socketio = SocketIO(app) #msgQ = queue.Queue() conf = json.loads(open('config.json').read()) app.config['WTF_CSRF_ENABLED'] = False # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' app.config['BASE_FOLDER'] = conf['main']['folder'] app.config['FEATURE'] = conf['feature'] app.config['PORT'] = int(conf["main"]['port']) app.config['IP'] = conf["main"]['ip'] app.config['NAME'] = conf["main"]['name']
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser # flash('critical message', 'critical') # flash('error message', 'error') # flash('warning message', 'warning') # flash('info message', 'info') # flash('debug message', 'debug') # flash('different message', 'different') # flash('uncategorized message') return render_template('index.html', form=form) @app.route('/result', methods=['POST']) def result(): # will capture our predictions, handles result # content_type = request.headers["content-type"] # if content_type == "application/json": if request.method == 'POST': to_predict_list = request.values['yelp_url'] result = ValuePredictor(to_predict_list) return render_template("result.html", prediction=result) # return Response(json.dumps(result), mimetype='application/json') # return jsonify(test) # response = app.response_class( # response=json.dumps(result), # status=200, # mimetype='application/json') # return render_template("results.html", prediction=result) # @app.route('/result', methods=['POST']) # def resultpage(): # will capture our predictions, handles result # if request.method == 'POST': # to_predict_list = request.values['yelp_url'] # results = ValuePredictor(to_predict_list) # return render_template("results.html", prediction=results) @app.route('/about') def aboutpage(): title = "About this site" paragraph = ["blah blah blah memememememmeme blah blah memememe"] pageType = 'about' return render_template("index.html", title=title, paragraph=paragraph, pageType=pageType) @app.route('/about/contact') def contactPage(): title = "About this site" paragraph = ["blah blah blah memememememmeme blah blah memememe"] pageType = 'about' return render_template("index.html", title=title, paragraph=paragraph, pageType=pageType) return app
return scandir.walk(root, followlinks=True) os.walk = mywalk thisdir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(thisdir, 'contents')) sys.path.insert(0, os.path.join(thisdir, 'pages')) sys.path.insert(0, thisdir) configfile = os.path.join(thisdir, 'config/default') app = Flask(__name__) app.config['APP_DIR'] = thisdir app.config['RELOAD_LOG'] = os.path.join(app.config['APP_DIR'], 'logs/reload.log') config = AppConfig(app, configfile) Bootstrap(app) Session(app) setup_logger(app) renderer = Renderer(app) pages = FlatPages(app) MetaInfo(pages) auth = Authentication(app) navtags = NavTags(app) error_pages = ErrorPages(app) toolbar = DebugToolbarExtension(app) reload_log = ReloadLog(app) reload_log.touch_date() dbdir = os.path.join(thisdir, 'hash') userdb.gUsers = userdb.Users(dbdir)
def create_app(configfile=None): logger.info('Loading user data...') customerDB = readPickle(os.path.join(data_dir, 'customerDB.pkl')) username2customerID = readPickle( os.path.join(data_dir, 'username2customerID.pkl')) user_data = readPickle(os.path.join(data_dir, 'user_data.pkl')) user_clusters = readPickle(os.path.join(data_dir, 'user_clusters.pkl')) logger.info('Loading product data...') prod_data = readJson(os.path.join(data_dir, 'new_fund.json')) prod_clusters = readJson(os.path.join(data_dir, 'cluster_centers.json')) clusters_dis = getClusterDist(prod_clusters) logger.info('Loading expert data...') expert_data = readJson( os.path.join(data_dir, 'financial_commissioner.json')) logger.info('Loading finished') app = Flask(__name__, static_url_path='/src/static') app.jinja_env.add_extension("chartkick.ext.charts") app._static_folder = os.path.abspath("src/static/") AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': logger.debug(request.form) if str(request.form['username']) in username2customerID: return render_template('registerForm.html', fromUrl=request.args['fromUrl']) updateCustomer(request.form, customerDB, username2customerID) session['isLogin'] = json.dumps(request.form) return redirect(url_for(redirectUrl())) return render_template('registerForm.html', fromUrl=request.args['fromUrl']) @app.route('/login', methods=('GET', 'POST')) def login(): form = LoginForm() if request.method == 'POST' and form.validate_on_submit(): username = str(form.username.data) password = str(form.password.data) logger.debug(username in username2customerID) if username in username2customerID and password == str( customerDB[int(username2customerID[username])][2]): logger.debug(customerDB[username2customerID[username]]) # print('[INFO]:login --> username ( ' + form.username.data + ' ) confirmed') logger.info('Username [ ' + username + ' ] login') session['isLogin'] = json.dumps(request.form) # customer = [username, username2customerID[username]] return redirect(url_for(redirectUrl())) return render_template('login.html', form=form) @app.route('/personalStatus') def personalStatus(): data = {'isLogin': True if 'isLogin' in session else False} if 'isLogin' not in session: return redirect(url_for('.mainPage')) return render_template('personalStatus.html', data=data) @app.route('/history') def history(): if 'isLogin' not in session: return redirect(url_for('.mainPage')) data = {'isLogin': True, 'listIdx': 10} if json.loads( session['isLogin'])['username'] not in username2customerID: user_id = int(json.loads(session['isLogin'])['customer_id']) else: user_id = username2customerID[json.loads( session['isLogin'])['username']] logger.info('Username : '******'isLogin'])['username'] + ' , ID : ' + str(user_id)) prod_list = create_recommand_list(user_id, user_data, prod_clusters)[:5] logger.info('Generate history product ID:') logger.info(prod_list) product_dict = {} for idx in range(5): fromData = randomDate( str(idx + 1) + '/1/200' + str(idx + 1), str(idx + 3) + '/1/200' + str(idx + 1), random.random()) toData = randomDate( str(idx + 3) + '/1/200' + str(idx + 1), str(idx + 7) + '/1/200' + str(idx + 1), random.random()) product_dict[idx] = prod_data[prod_list[idx]] product_dict[idx]['from'] = fromData product_dict[idx]['end'] = toData product_dict[idx]['revenue'] = float( (random.randint(0, 400) - 200)) / 10 return render_template('history.html', data=data, products=product_dict) @app.route('/') def mainPage(): data = {'isLogin': True if 'isLogin' in session else False} logger.info('Login status : ' + 'Login' if data['isLogin'] else 'Not login') logger.info('Switch to main page') return render_template('index.html', data=data) @app.route('/hotissue') def hotIssue(): data = {'isLogin': True if 'isLogin' in session else False} logger.info('Login status : ' + 'Login' if data['isLogin'] else 'Not login') logger.info('Switch to hot issue page') return render_template('hotissue.html', data=data) @app.route('/logout') def logout(): logger.info('Username [ ' + json.loads(session['isLogin'])['username'] + ' ] logout') session.pop('isLogin', None) return redirect(url_for(redirectUrl())) @app.route('/productRank') def productRank(): if 'isLogin' not in session: return redirect(url_for('.mainPage')) logger.info('Switch to product rank page') data = {'isLogin': True, 'listIdx': 10} if json.loads( session['isLogin'])['username'] not in username2customerID: user_id = int(json.loads(session['isLogin'])['customer_id']) else: user_id = username2customerID[json.loads( session['isLogin'])['username']] if 'isRefresh' in request.args and request.args['isRefresh'] == 'no': if 'listIdx' in request.args: listIdx = int(request.args['listIdx']) product_dict = ast.literal_eval(request.args['productDict']) like_prod(user_id, product_dict[listIdx]['id'], user_data, user_clusters, prod_data, clusters_dis) logger.info('User ID [ ' + str(user_id) + ' ] likes product ID [ ' + str(product_dict[listIdx]['id']) + ' ] from cluster [ ' + str(product_dict[listIdx]['cluster_id']) + ' ]') logger.info('Product cluster scores:') logger.info(user_data[user_id]['scores']) return render_template('productRank.html', products=product_dict, data=data) elif 'productIdx' in request.args: data['listIdx'] = int(request.args['productIdx']) product_dict = ast.literal_eval(request.args['productDict']) logger.info('Product ID [ ' + str(product_dict[data['listIdx']]['id']) + ' ] selected.') return render_template('productRank.html', products=product_dict, data=data) logger.info('Username : '******'isLogin'])['username'] + ' , ID : ' + str(user_id)) prod_list = create_recommand_list(user_id, user_data, prod_clusters) logger.info('Generate recommended product ID:') logger.info(prod_list) product_dict = {} for idx in range(10): product_dict[idx] = prod_data[prod_list[idx]] return render_template('productRank.html', products=product_dict, data=data) @app.route('/expertRank') def expertRank(): if 'isLogin' not in session: return redirect(url_for('.mainPage')) logger.info('Switch to expert rank page') data = {'isLogin': True} if json.loads( session['isLogin'])['username'] not in username2customerID: user_id = int(json.loads(session['isLogin'])['customer_id']) else: user_id = username2customerID[json.loads( session['isLogin'])['username']] expert_dict = match(expert_data, user_id, user_data, prod_data, prod_clusters) logger.info('Username : '******'isLogin'])['username'] + ' , ID : ' + str(user_id)) logger.info('Generate recommended financial commissioner ID:') logger.info([key for key in expert_dict]) logger.info('Successful experience with product ID:') logger.info([[item['id'] for item in expert_dict[key]['top5']] for key in expert_dict]) return render_template('expertRank.html', experts=expert_dict, data=data) return app
# $ flask --app=sample_app dev # # Afterwards, point your browser to http://localhost:5000, then check out the # source. from flask import Flask from flask_appconfig import AppConfig from flask_bootstrap import Bootstrap from frontend import frontend_app from nav import nav_app app = Flask(__name__) # We use Flask-Appconfig here, but this is not a requirement AppConfig(app) # Install our Bootstrap extension Bootstrap(app) # Our application uses blueprints as well; these go well with the # application factory. We already imported the blueprint, now we just need # to register it: app.register_blueprint(frontend_app) # Because we're security-conscious developers, we also hard-code disabling # the CDN support (this might become a default in later versions): app.config['BOOTSTRAP_SERVE_LOCAL'] = True # We initialize the navigation as well nav_app.init_app(app)
from app.models.user_model import User # Define the WSGI application object app = Flask(__name__) logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) db.init_app(app) # Configurations app.config.from_pyfile('config.py') # add the app blueprints app.register_blueprint(routes) AppConfig(app, configfile=None) bootstrap = Bootstrap(app) app.secret_key = '\x84\xa4{;\x7f\xa6\xc4\x1f\xbf\x89\xd7\x17T\xd88\xbe\x0b\xfam=E\xdc6' mail = Mail(app) def init_email_error_handler(app): """ Initialize a logger to send emails on error-level messages. Unhandled exceptions will now send an email message to app.config.ADMINS. """ # if app.debug: return # Do not send error emails while developing # Retrieve email settings from app.config
def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' #NoSQL Backend backend = FileBackend("/tmp/wakeonlan.db") backend.create_index(Device, fields={'id': 1}, unique=True) #TEST Devices alldevices = backend.filter(Device, {}) if len(alldevices) == 0: try: pc1 = Device({ "id": "001122334411", "name": "PC 1", "mac": "00:11:22:33:44:11", "ip": "192.168.222.111", 'status': '' }) backend.save(pc1) pc2 = Device({ "id": "001122334422", "name": "PC 2", "mac": "00:11:22:33:44:22", "ip": "192.168.222.112", 'status': '' }) backend.save(pc2) pc3 = Device({ "id": "001122334433", "name": "Router", "mac": "00:11:22:33:44:33", "ip": "192.168.222.1", 'status': '' }) backend.save(pc3) backend.commit() except: backend.revert() pass # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' # app.config['RECAPTCHA_PUBLIC_KEY'] = \ # '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' def getDeviceById(id): device = None try: device = backend.get(Device, {'id': id}) except: pass return device def pingDeviceById(id): #Get Device device = backend.get(Device, {'id': id}) if device: #Get Device's IP ip = device['ip'] result = pingDeviceByIp(ip) #Update Status UP/Down/'' if result == 0: device['status'] = 'UP' else: device['status'] = 'DOWN' backend.save(device) return result return None def wolDeviceById(id): #Get Device device = backend.get(Device, {'id': id}) if device: #WoL for Device MAC mac = device['mac'] wolDeviceByMac(mac) return None @login_manager.user_loader def user_loader(user_id): """Given *user_id*, return the associated User object. :param unicode user_id: user_id (email) user to retrieve """ user_entry = User.getById(user_id) if user_entry is not None: user = User(user_entry[0], user_entry[1]) return user else: return None @app.route('/', methods=('GET', 'POST')) @login_required def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser # flash('critical message', 'critical') # flash('error message', 'error') # flash('warning message', 'warning') # flash('info message', 'info') # flash('debug message', 'debug') # flash('different message', 'different') # flash('uncategorized message') alldevices = None alldevices = backend.filter(Device, {}).sort('name') #app.logger.info('Devices: %s' % (len(alldevices) ) ) return render_template('index.html', form=form, devices=alldevices) @app.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'GET': form = LoginForm() form.validate_on_submit() # to get error messages to the browser return render_template('login.html', form=form) username = request.form['username'] password = request.form['password'] user_entry = User.get(username, password) if user_entry is None: flash('Username or Passord is invalid', 'error') return redirect(url_for('login')) user = User(user_entry[0], user_entry[1]) login_user(user, remember=True) return redirect(request.args.get('next') or url_for('index')) @app.route("/logout", methods=["GET"]) @login_required def logout(): """Logout the current user.""" user = current_user user.authenticated = False logout_user() return redirect(url_for('login')) @app.route('/addDevice', methods=('GET', 'POST')) @login_required def addDevice(): if request.method == 'GET': form = AddDeviceForm() form.validate_on_submit() # to get error messages to the browser return render_template('add_device.html', form=form) name = request.form['name'] mac = request.form['mac'] ip = request.form['ip'] id = mac.replace(':', '') try: newDevice = Device({ "id": id, "name": name, "mac": mac, "ip": ip, 'status': '' }) backend.save(newDevice) backend.commit() except: flash('Error creating new Device', 'error') pass return redirect(url_for('index')) @app.route('/editListDevice', methods=('GET', 'POST')) @login_required def editListDevice(): alldevices = None alldevices = backend.filter(Device, {}).sort('name') return render_template('list_device.html', devices=alldevices) @app.route('/pingDevice/<deviceId>', methods=('GET', 'POST')) @login_required def pingDevice(deviceId): app.logger.info('pingDevice: %s' % (deviceId)) device = getDeviceById(deviceId) result = pingDeviceById(deviceId) app.logger.info('pingDevice: %s' % (result)) if result is None: flash('Ping - Error on device %s' % (device['name']), 'error') elif result == 0: flash('Device %s is UP' % (device['name']), 'info') else: flash('Device %s is DOWN' % (device['name']), 'error') return redirect(url_for('index')) @app.route('/wolDevice/<deviceId>', methods=('GET', 'POST')) @login_required def wolDevice(deviceId): app.logger.info('wolDevice: %s' % (deviceId)) device = getDeviceById(deviceId) result = wolDeviceById(deviceId) if device: flash('WoL sent to %s' % (device['name']), 'info') else: flash('WoL error', 'error') return redirect(url_for('index')) @app.route('/deleteDevice/<deviceId>', methods=('GET', 'POST')) @login_required def deleteDevice(deviceId): app.logger.info('wolDevice: %s' % (deviceId)) device = getDeviceById(deviceId) try: backend.delete(device) backend.commit() flash('%s Deleted' % (device['name']), 'info') except: flash('Delete error', 'error') pass return redirect(url_for('editListDevice')) return app
from flask_appconfig import AppConfig from social.apps.flask_app.routes import social_auth from social.apps.flask_app.me.models import init_social from flask.ext import login, mongoengine from social.apps.flask_app.template_filters import backends from mrq.job import queue_job, Job from mrq.context import setup_context, get_current_config import json sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) DEBUG = bool(os.getenv("IMGFAB_DEBUG")) app = Flask('imgfab') AppConfig(app, os.path.abspath(os.path.join(__file__, '../settings.py'))) Bootstrap(app) app.config.update({"DEBUG": DEBUG}) db = mongoengine.MongoEngine(app) app.register_blueprint(social_auth) init_social(app, db) app.context_processor(backends) login_manager = login.LoginManager() login_manager.init_app(app) if not get_current_config(): setup_context()
def create_app(configfile=None): """ This function creates the application. Parameters: configfile (str) : the optional and highly recommened configuration file Returns app (Flask) : an instance of a Flask application """ import datetime from . helpers.begin_end import begin_end from flask import Flask, render_template, request, flash from flask_bootstrap import Bootstrap from flask_appconfig import AppConfig from . models.search.SearchForm import SearchForm from . models.search.search_route import searchy from . models.search.quick_search import quick_search app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) # This should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' @app.route('/', methods=('GET', 'POST')) def index(): form = SearchForm(request.form) # check whether the HTTP request sends data if request.method == 'POST': fields = ["x_pol", "y_pol", "gen_sys"] # format timestamps if form.quick_search.raw_data[0]: quick = begin_end(form, 'quick') else: begin = begin_end(form, 'begin') end = begin_end(form, 'end') # if time range is more than a week, this could take a while begin_check = datetime.datetime.strptime(begin, "%Y-%m-%d_%H:%M") end_check = datetime.datetime.strptime(end, "%Y-%m-%d_%H:%M") delta_t = end_check - begin_check if delta_t.days >= 7: flash("Time range more than 1 week. This might take 3 minutes.") plottable = False empty_field_counter = 0 for i in range(3): # generate an HTML document with a graph of selected data if (form[fields[i]].raw_data[0] != ""): if (form.quick_search.raw_data[0] != ""): plottable = quick_search(quick, form[fields[i]].raw_data[0]) else: plottable = searchy(begin, end, form[fields[i]].raw_data[0]) else: empty_field_counter += 1 # Check whether the user left all non-date params empty if (empty_field_counter >= 3): flash("Please select an option from a dropdown, below.") # Notify the user if no data matches their query. elif not plottable: flash("There is no data within that time range.", 'warning') return render_template('index.html', form=form) return app
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 avatarGen(value): avatar = Avatar(rows=10, columns=10) image_byte_array = avatar.get_image(string=value, width=50, height=50, pad=10) avatar.save(image_byte_array=image_byte_array, save_location='static/img/' + value + '.png') return 'static/img/' + value + '.png' 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.jinja_env.filters['avatarGen'] = avatarGen @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': flash('Turned all rooms on!') for pin in pins: GPIO.output(pin, GPIO.HIGH) if master == 'off': flash('Turned all rooms off!') for pin in pins: GPIO.output(pin, GPIO.LOW) if master == 'toggle': flash('Toggle all rooms !') 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) flash('Reset all rooms !') return redirect(url_for('switch')) @app.route('/switch/<changePin>/<action>') def action(changePin, action): changePin = int(changePin) deviceName = pins[changePin]['name'] if action == 'on': flash('Turned ' + deviceName + ' on!') GPIO.output(changePin, GPIO.HIGH) if action == 'off': flash('Turned ' + deviceName + ' off!') GPIO.output(changePin, GPIO.LOW) if action == 'toggle': flash('Toggled ' + deviceName + ' !') GPIO.output(changePin, not GPIO.input(changePin)) if action == 'reset': GPIO.output(changePin, GPIO.LOW) time.sleep(5) GPIO.output(changePin, GPIO.HIGH) flash('Reset ' + deviceName + ' !') 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" } } flash('Event Successfully Add !') 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) flash('Event Successfully Delete !') 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': flash('Message Successfully Sent !') 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 7) AS ping ORDER BY id ASC" ) ping = ping_cur.fetchall() templateData = {'ping': ping} return render_template('network.html', **templateData) @app.route('/reboot') def reboot(): os.system('sudo reboot') return redirect(url_for('index')) @app.route('/shutdown') def shutdown(): os.system('sudo halt') return redirect(url_for('index')) return app
def create_app(configfile=None): app = Flask(__name__) # Flask-Appconfig is not necessary, but highly recommend =) https://github.com/mbr/flask-appconfig AppConfig(app, configfile) Bootstrap(app) app.config['SECRET_KEY'] = 'devkey' # in a real app, these should be configured through Flask-Appconfig PDS_OAUTH_ENDPOINT = 'http://my-tyk-instance.dev:8080/oauth/authorize/' PDS_OAUTH_TOKEN_ENDPOINT = 'http://my-tyk-instance.dev:8080/oauth/token/' PDS_CLIENT_ID = 'ffedab5c7d3549455af73176612cbb10' PDS_CLIENT_SECRET = 'ZjEzZmIyZTQtNGZlYy00YjliLTc3Y2QtYzI3MzdhZGQ2YTIy' CLIENT_CALLBACK = 'http://127.0.0.1:9190/token_callback/' REQUEST_STATE = '0807edf7d85e5d' @app.route('/', methods=('GET', 'POST')) def index(): form = ContactForm() form.validate_on_submit() # to get error messages to the browser return render_template('index.html', form=form) @app.route('/pds/contacts/', methods=('GET', 'POST')) def request_authorization(): try: pds_authorize_url = PDS_OAUTH_ENDPOINT + "?client_id=" + PDS_CLIENT_ID + \ "&response_type=code&state=" + REQUEST_STATE + \ "&redirect_uri=" + CLIENT_CALLBACK return redirect(pds_authorize_url) except Exception as e: return redirect('/') @app.route('/token_callback/', methods=('GET', 'POST')) def token_callback(): try: if request.method == 'GET' and request.args.get('error'): return jsonify(response={ 'status': False, 'message': request.args.get('error') }) elif request.method == 'GET' and request.args.get( 'code') and request.args.get('code') != '': """ Authorization code received """ data = { 'grant_type': 'authorization_code', 'client_id': PDS_CLIENT_ID, 'code': str(request.args.get('code')), 'redirect_uri': CLIENT_CALLBACK } payload = urllib.urlencode(data) base64string = base64.encodestring( '%s:%s' % (PDS_CLIENT_ID, PDS_CLIENT_SECRET)).replace( '\n', '') headers = { 'authorization': "Basic " + base64string, 'cache-control': "no-cache", 'content-type': "application/x-www-form-urlencoded" } response = requests.post(url=PDS_OAUTH_TOKEN_ENDPOINT, data=payload, headers=headers) if response.status_code == 200: user_data = get_user_data(response.json(), request.args.get('user_id')) return jsonify({'user_response': user_data}) else: return jsonify({ 'status': False, 'message': response.json() }) except ValueError as e: return jsonify(response={'Error': 'Value error'}) except KeyError as e: return jsonify(response={'Error': 'Key error'}) def get_user_data(token_data, user_id): user_data_url = "http://my-tyk-instance.dev:8080/api/v1/users/" + str( user_id) + "/emails/" headers = { 'authorization': "Bearer " + str(token_data['access_token']), 'cache-control': "no-cache" } response = requests.request("GET", user_data_url, headers=headers) if response.status_code == 200: print(response.text) return response.json() else: return { 'error': "Unable to retrieve user data", 'status': response.status_code } return app
def create_app(configfile=None): root_dir = '.' data_dir = os.path.join(root_dir, 'data') mdl_dir = os.path.join(root_dir, 'mdl') logger = logging.getLogger(__name__) # TODO: # Initial ML model class hospital = 'NTU_example_31_14_20170715' hm = HospitalManager() # update model hm.updateModel() # Register training funtion executed once every day # TODO: # change interval and filename scheduler = BackgroundScheduler() scheduler.start() scheduler.add_job( func=lambda: trainModel('input.csv'), trigger=IntervalTrigger(days=1), id='training_model', name='training model every day', replace_existing=True) atexit.register(lambda: scheduler.shutdown()) logger.info('Initial Flask app') app = Flask(__name__) AppConfig(app, configfile) app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = '6Mfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' # Usgae: # /feature?hospital=NTU&filename=example_31_14 @app.route('/feature') def getFeature(): # TODO: # return the data of features in JSON format according to different hospital if 'hospital' in request.args and 'filename' in request.args: hospital = str(request.args['hospital']) filename = str(request.args['filename']) features = hm.getInputFeature(hospital, filename) else: features = {} return json.dumps(features, indent=4, ensure_ascii=False) # Usgae: # /predict?hospital=NTU&filename=example_31_14 (used the newest model) # /predict?hospital=NTU&filename=example_31_14&time=-3 (specified model) # time: the # model counted backward, default = -1 (the newest model) # ex: time = -3, means the third model counted from the end of list. @app.route('/predict') def predict(): if 'hospital' in request.args and 'filename' in request.args: hospital = str(request.args['hospital']) filename = str(request.args['filename']) data = [0] * (len(hm.getInputFeature(hospital, filename)['Bool']) + len(hm.getInputFeature(hospital, filename)['Float'])) for args in request.args: if args != 'hospital' and args != 'filename': if int(args[1:]) < len(data): data[int(args[1:])] = float(request.args[args]) if 'time' in request.args: time = int(request.args['time']) pred_focus = hm.predictFocus(data, hospital, filename, time) else: pred_focus = hm.predictFocus(data, hospital, filename) else: pred_focus = [] return json.dumps(pred_focus, indent=4, ensure_ascii=False) # logger.info (request.args) # # TODO: # # 1. check current hospital # cur_hospital = str(request.args['hospital']) # cur_features = [0] * 37 # for args in request.args: # if args != 'hospital': # cur_features[int(args[1:])] = 1 # logger.info('Features from client:') # logger.info([cur_features]) # # 2. parse the feature clicked by user # # 3. feed the feature to the model and predict answer # pred_idx = km.predictFocus([cur_features]) # # pred_idx = rfm.predictFocus(cur_features) # logger.info('Predict result idx:') # logger.info(pred_idx) # pred = [results[val] for val in pred_idx] # return json.dumps(pred, indent=4, ensure_ascii=False) @app.route('/update') def update(): # TODO: # update the csv file with current record return 'update' # Usgae: # /addHospital?hospital=NTU @app.route('/addHospital') def addHospital(): if 'hospital' in request.args: hospital = str(request.args['hospital']) return hm.addHospital(hospital) else: return 'Please give a hospital name' # Usgae: # /removeHospital?hospital=NTU @app.route('/removeHospital') def removeHospital(): if 'hospital' in request.args: hospital = str(request.args['hospital']) return hm.removeHospital(hospital) else: return 'Please give a hospital name' # Usgae: # /addFile?hospital=NTU&filename=example_31_14 # /addFile?hospital=NTU&filename=example_31_14&method=rf @app.route('/addFile') def addFile(): if 'hospital' in request.args and 'filename' in request.args: hospital = str(request.args['hospital']) filename = str(request.args['filename']) if 'method' in request.args: method = str(request.args['method']) return hm.addFile(hospital, filename, method) else: return hm.addFile(hospital, filename) elif 'hospital' in request.args: return 'Please give a CSV file name' elif 'filename' in request.args: return 'Please give a hospital name' else: return 'Please give a CSV file and hospital name' # Usage: # removeFile?hospital=NTU&filename=example_31_14 @app.route('/removeFile') def removeFile(): if 'hospital' in request.args and 'filename' in request.args: hospital = str(request.args['hospital']) filename = str(request.args['filename']) return hm.removeFile(hospital, filename) elif 'hospital' in request.args: return 'Please give a CSV file name' elif 'filename' in request.args: return 'Please give a hospital name' else: return 'Please give a CSV file and hospital name' @app.route('/admin') def routeAdmin(): return admin.hello() signal.signal(signal.SIGINT, hm.shutdown) return app