def create_app(test_config=None): # application factory # create and instantiate an instance of Flask # `instance_relative_config=True` signifies that the app instance configuration files are relative to the instance folder # `test_config` is a key:value map required to signify testing nuances app = Flask(__name__, instance_relative_config=True) # create instance # initialize default configurations for the newly instantiated app app.config.from_mapping( SECRET_KEY=os.getenv("SECRET_KEY"), # secure random phrase used to sign session cookies et al. DATABASE=os.path.join(app.instance_path, 'blogdatabase.sqlite') # define path for database upon autogeneration of the db ) # Set the session app.config['SESSION_TYPE'] = 'filesystem' sess = Session() sess.init_app(app) # allows for alternative source of default configuration e.g. loading configuration from `config.py` [in the instance folder] if test_config is None: # load the instance config, if it exists when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists i.e. creates the instance folder [in case it does not exist] try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello (to show the app works) based on the url path `/hello` @app.route('/hello') def hello(): return 'Hello, World!' # initialize the database, by calling `init_app()` from `db.py` : after initiliazing the app configs db.init_app(app) # initialize the registered auth blueprints, by calling `init_blueprint` from `auth.py` : after initializing the app database auth.init_blueprint(app) # initialize the registered blog blueprints, by calling `init_blueprint` from `blog.py` : after initializing the app database blog.init_blueprint(app) return app # return a properly configured instance of the app
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: app.config.from_pyfile('config.py') else: app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # app.config.from_object(__name__) Session(app) @app.route('/') @app.route('/index') def index(): return render_template('index.html') from . import smomo app.register_blueprint(smomo.bp) from . import tilt app.register_blueprint(tilt.bp) from . import db db.init_app(app) return app
from flask_session.__init__ import Session import flask_sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, session, sessionmaker app = Flask(__name__) # Set up database engine = create_engine(os.getenv("DATABASE_URL")) db = scoped_session(sessionmaker(bind=engine)) app = Flask(__name__) app.config["SQLALCHEMY DATABASE URI"] = os.getenv("DATABASE_URL") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config.from_object(__name__) Session(app) # Configure session to use filesystem app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Check for environment variable if not os.getenv("DATABASE_URL"): raise RuntimeError("DATABASE_URL is not set") def getBookInfo(book_isbn): @app.route("/") def index(): return "Project 1: Welcome to Book Review!"
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: app.config.from_pyfile('config.py') else: app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # app.config.from_object(__name__) Session(app) @app.route('/') @app.route('/index') def index(): cookId = SMSession.getCookId() if cookId == 0: cookId = CookDL.getCurrentCookId() SMSession.setCookId(cookId) currentCook = CookDL.getCook(cookId) latestTime = datetime(2019,1,1) latestTemp = [0, 0, 0] minTemp = [9999, 9999, 9999] maxTemp = [0, 0, 0] temps = [] if currentCook.CookId > 0: temps = TempDL.getTempsForCook(currentCook.CookId) for x in temps: if x.EventDate > latestTime: latestTime = x.EventDate latestTemp[0] = x.Temp1 latestTemp[1] = x.Temp2 latestTemp[2] = x.Temp3 """ if x.Temp < minTemp[x.SensorNum]: minTemp[x.SensorNum] = x.Temp if x.Temp > maxTemp[x.SensorNum]: maxTemp[x.SensorNum] = x.Temp """ return render_template('index.html', cook = currentCook, latestTime = latestTime, latestTemp = latestTemp, minTemp = minTemp, maxTemp = maxTemp, temps = temps, values=temps, currentDT=datetime.now()) @app.route('/editcook', methods=['GET', 'POST']) def startcook(): currentCookId = CookDL.getCurrentCookId() if request.method == "POST": if currentCookId == 0: title = request.form["title"] smokerTarget = request.form["smokerTarget"] target = request.form["target"] CookDL.startCook(title, smokerTarget, target) cookId = CookDL.getCurrentCookId() SMSession.setCookId(cookId) else: CookDL.endCurrentCook() return redirect(url_for('index')) else: if currentCookId == 0: return render_template('startcook.html') else: cook = CookDL.getCook(currentCookId) title = cook.Title return render_template('endcook.html', title=title) @app.route('/selectcook', methods=['GET']) def selectCook(): cookId = request.args.get('cookId') if cookId: SMSession.setCookId(cookId) return redirect(url_for('index')) else: cooks = CookDL.getCooks() return render_template('selectcook.html', cooks=cooks) @app.route('/deletecook', methods=['GET']) def deleteCook(): cookId = request.args.get('cookId') CookDL.delete(cookId) return redirect(url_for('selectCook')) @app.route('/getdata', methods=['GET']) def GetCookData(): date = request.args.get('lastUpdate') cookId = request.args.get('cookId') currentCook = CookDL.getCook(cookId) if currentCook.CookId > 0: allData = {} endTime = datetime.now() if currentCook.End: endTime = currentCook.End allData['duration'] = currentCook.Duration allData['cookStart']= currentCook.Start.strftime(dateFormatString) allData['currentDT']=datetime.now() allData['smokerTarget'] = GenerateTargetData(currentCook.Start, endTime, currentCook.SmokerTarget) allData['target'] = GenerateTargetData(currentCook.Start, endTime, currentCook.Target) currentDate = endTime allData['lastUpdate'] = currentDate.strftime(dateFormatString) temps = [] if date: temps = TempDL.getTempsForCook(currentCook.CookId, date) else: temps = TempDL.getTempsForCook(currentCook.CookId) temps1 = [] temps2 = [] temps3 = [] # get current temps from the first item in the list if len(temps) > 0: currentTemp = temps[-1] # last in the list allData['Sensor1Current'] = '{0:.2f}'.format(currentTemp.Temp1) allData['Sensor2Current'] = '{0:.2f}'.format(currentTemp.Temp2) allData['Sensor3Current'] = '{0:.2f}'.format(currentTemp.Temp3) for x in temps: formattedDate = x.EventDate.strftime(dateFormatString) if x.Temp1 > 0: temp1 = {} temp1['x'] = formattedDate temp1['y'] = x.Temp1 temps1.append(temp1) if x.Temp2 > 0: temp2 = {} temp2['x'] = formattedDate temp2['y'] = x.Temp2 temps2.append(temp2) if x.Temp3 > 0: temp3 = {} temp3['x'] = formattedDate temp3['y'] = x.Temp3 temps3.append(temp3) allData['Temp1'] = temps1 allData['Temp2'] = temps2 allData['Temp3'] = temps3 return jsonify(allData) return jsonify('') @app.route('/recorddata', methods=['GET']) def RecordData(): cookId = CookDL.getCurrentCookId() # if DEBUG: # print("CookId: {0}".format(cookId)) if cookId > 0: # Number of samplet to take numOfSamples = 3 tempSamples = [] tempFinal = [] for i in range(numOfSamples): tempSamples.append(HWTempDL.getTemps()) tempFinal.append(0.0) for tempSample in tempSamples: tempSampleCount = 0 for temp in tempSample: tempFinal[tempSampleCount] = tempFinal[tempSampleCount] + temp tempSampleCount = tempSampleCount + 1 tempSampleCount = 0 for temp in tempFinal: tempFinal[tempSampleCount] = tempFinal[tempSampleCount] / numOfSamples tempSampleCount = tempSampleCount + 1 TempDL.logTemps(tempFinal, cookId) return jsonify('OK') from . import db db.init_app(app) return app
from flask import Flask from flask import render_template, url_for, request, redirect, flash, session, make_response from flask_session.__init__ import Session from module.dbconnect import DBConnect as dbconnect import time app = Flask(__name__, template_folder='template', static_url_path='/static') app.config['SESSION_TYPE'] = 'memached' app.config['SECRET_KEY'] = 'super secret key' sess = Session() @app.route('/') def homepage(): return render_template("homepage.html") @app.route('/forum', methods=['GET', 'POST']) def forum(): if request.method == 'POST': if 'PostThread' in request.form: username = request.form.get("name") email = request.form.get("email_name") subject = request.form.get("subject_name") comment = request.form.get("comment_name") print("form", request.form) input_ = { "username": username, "email": email, "title": subject, "comment": comment
# from app import app # # app.run(debug=True) from app import app from flask_session.__init__ import Session sess = Session() if __name__ == "__main__": app.secret_key = 'super secret key' app.config['SESSION_TYPE'] = 'filesystem' sess.init_app(app) app.debug = True app.run()
""" Created on Mon May 18 22:19:58 2020 @author: bensonsmathew """ from flask import Flask, render_template, request, session from flask_session.__init__ import Session from datetime import datetime import sqlite3 import socket from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import pandas as pd hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print(f"Goto:\nhttp://{IPAddr}:5000\n") engine = create_engine('sqlite:///employee.db') db = scoped_session(sessionmaker(engine)) dept = {i[1]: i[0] for i in db.execute('select * from department')} class employee_cl: "Class to store employee details" def __init__(self, e_num, dept_id, first, last, title, shift, days_off, fte, del_ind): self.e_num = e_num self.dept_id = dept_id self.first = first self.last = last self.title = title self.shift = shift self.days_off = days_off
import os from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy from flask_session.__init__ import Session from config import current_config ## # app Setup ## app = Flask(__name__) app.config.from_object(current_config) # Flask Session sess = Session(app) ## # Authorization Required & # Wrong HTTP Method / Resource not found ## @app.errorhandler(400) @app.errorhandler(401) @app.errorhandler(403) @app.errorhandler(405) @app.errorhandler(404) def _app_errors(e): return jsonify({'success': 0, 'error': str(e)}), 404
from flask import request, session, render_template from flask_session.__init__ import Session from flask_sqlalchemy import SQLAlchemy from flask import Flask from utils.response import terminal_prefix import shlex import re from utils.db_session import provide_db_session import traceback USER_INPUT = "user_input" app = Flask(__name__) app.config.from_object('config.Config') # flask app configs _session = Session(app) _session.app.session_interface.db.create_all() # with app.app_context(): # upgrade(directory="migrations") # run db upgrade db = SQLAlchemy(app) # register routes def get_cmd(cmd_args): if len(cmd_args) == 0: cmd = " ".join(cmd_args) raise ValueError(f'{cmd}: No command')