def _main(config): model.setup_db(config['db']['connection_string']) week_ago = datetime.datetime.now() - datetime.timedelta(days=7) todays_transactions = model.session.query(model.Transaction).filter(model.Transaction.date > week_ago).all() for t in todays_transactions: print(t)
def setUp(self): """Define test variables and initialize app.""" self.app = app self.client = self.app.test_client self.casting_assistant = CASTING_ASSISTANT self.casting_director = CASTING_DIRECTOR self.executive_producer = EXECUTIVE_PRODUCER setup_db(self.app, TEST_DATABASE_URI) with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app)
def create_app(): app = Flask(__name__) app.logger.setLevel(logging.INFO) with app.app_context(): db_file = os.environ.get('COUNT_DB') or 'counter.db' db_uri = 'sqlite:///' + db_file app.config['SQLALCHEMY_DATABASE_URI'] = db_uri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False apply_db_migrations(db_uri) db = setup_db(app) Counter = create_classes(db) @app.route('/') @app.route('/<name>') def counter(name = None): if name: if name == 'favicon.ico': return abort(404) app.logger.info("name %s", name) cntr = db.session.query(Counter).filter_by(name=name).first() app.logger.info(cntr) if not cntr: cntr = Counter(name=name, count=1) db.session.add(cntr) else: cntr.count += 1 db.session.commit() app.logger.info(cntr) return render_template('counter.html', name = name, counter = cntr.count) else: counters = [ {"name": counter.name, "count" : counter.count} for counter in db.session.query(Counter).all()] app.logger.info(counters) return render_template('counter.html', counters = counters) return app
def update_config(self, config): plugins.toolkit.add_template_directory(config, 'templates') plugins.toolkit.add_resource('fanstatic', 'piwik') setup_db()
#import dependencies import os from flask import Flask, jsonify, abort, request from model import setup_db, Movies, Actors from flask_cors import CORS from auth import AuthError, requires_auth from datetime import datetime from werkzeug.exceptions import HTTPException # create app app = Flask(__name__) # binds a flask application and a SQLAlchemy service setup_db(app) # Cross-Origin-Resource-Sharing cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE,OPTIONS') return response # endpoints @app.route('/') def get_home(): return('Welcome to the Casting Agency')
def reset(): database = CreateDB() create_tables() setup_db() return redirect(url_for('index'))
import os import sys import time from model import Camera import json import CaptureImage import time import subprocess import platform import utils app = Flask(__name__) CORS(app) # Set up database db = setup_db(app) migrate = Migrate(app, db) @app.route("/") def home(): path_to_check = utils.get_base_application_path() return "hello world <br>" + \ path_to_check + "<br>\n" @app.route("/get-ptp-device-ids") def get_ptp_devices(): try: device_ids = CaptureImage.get_usb_device_ids() return jsonify({"success": True, "device-ids": device_ids})
import os from model import setup_db, DB_ROWS, get_row import linear_regression import graphing CSV_FILE = os.environ.get('CSV_FILE', './data/housing.csv') TARGET = os.environ.get('TARGET', 'median_home_value') LEARNING_RATE = float(os.environ.get('LEARNING_RATE', '0.001')) ITERATIONS = int(os.environ.get('ITERATIONS', '10000')) if __name__ == '__main__': setup_db(CSV_FILE) feature = os.getenv('FEATURE') if feature: graphing.draw_scatter(feature, get_row(TARGET), get_row(feature), None, None, 'start', showLine=False) linear_regression.run(get_row(feature), feature) else: for name in DB_ROWS: graphing.draw_scatter(name, get_row(TARGET), get_row(name), None, None, 'start', showLine=False)
def create_app(): app = Flask(__name__) app.config['DEBUG'] = True app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit") app.config["GITHUB_OAUTH_CLIENT_ID"] = os.environ.get( "GITHUB_OAUTH_CLIENT_ID") app.config["GITHUB_OAUTH_CLIENT_SECRET"] = os.environ.get( "GITHUB_OAUTH_CLIENT_SECRET") app.register_blueprint(github_bp, url_prefix="/login") # setup db to store OAuth tokens setup_db(app, github_bp) # environment varaibales REPOSITORY = os.environ.get("REPOSITORY") OWNER = os.environ.get("OWNER") url = f"repos/{OWNER}/{REPOSITORY}" def authorizing(f): @wraps(f) def wrapper(*args, **kwargs): if not github.authorized: return redirect(url_for("github.login")) else: ACCESS_TOKEN = app.blueprints['github'].token['access_token'] print("ACCESS_TOKEN=", ACCESS_TOKEN) return f() return wrapper def get_all_contributors(repo): body = repo.to_dict() return jsonify({"success": True, "body": body}) def get_one_contributor(login): contributor = Contributor(login=login, load_stats=True) return jsonify({"success": True, "body": contributor.to_dict()}) @app.route("/") @authorizing def index(): contribtuor_res = Repository.get_contribtuor_res() if contribtuor_res.status_code == 404: abort(404) elif contribtuor_res.status_code == 403: abort(403) else: return render_template('index.html') @app.route("/contributors") @authorizing def contributors_endpoint(): query_string = request.query_string if not query_string: # no query string repo = Repo() return get_all_contributors(repo) else: # get login of query string login = request.args.get('login') return get_one_contributor(login=login) @app.route("/logout") def logout(): ACCESS_TOKEN = app.blueprints['github'].token['access_token'] CLIENT_ID = os.environ.get("GITHUB_OAUTH_CLIENT_ID") payload = "{\"access_token\": \"%s\"}" % (ACCESS_TOKEN) logout_url = f"https://api.github.com/applications/{CLIENT_ID}/grant" headers = { 'Authorization': 'Basic NjliYTRiMTBhNGE0Y2RhM2IxNzQ6MDJlN2FmYTQ1NTIxYmYyMzBhYzNkNTg4MGQ0MWIwNGRlMWUzYWY1OQ==', 'Content-Type': 'application/json', 'Cookie': '_octo=GH1.1.2130686163.1612643408; logged_in=no' } resp = req("DELETE", logout_url, headers=headers, data=payload) if resp.ok: del app.blueprints['github'].token session.clear() return "Ok" else: abort(401) @app.errorhandler(404) def error_404(error): return jsonify({"success": False, "message": "page not found"}), 404 @app.errorhandler(403) def error_403(error): return jsonify({"success": False, "message": "forbidded call"}), 403 return app