def setUp(self): """Executed before each test. Define test variables and initialize app.""" self.app = create_app(TestingConfig) self.client = self.app.test_client self.ticket = {"event_id": 2, "price": 500, "quantity": 50} self.update_ticket = {"event_id": 2, "price": 500, "quantity": 10} with self.app.app_context(): db.create_all() initialize_db()
def setUp(self): """Executed before each test. Define test variables and initialize app.""" self.app = create_app(TestingConfig) self.client = self.app.test_client self.event_t = { "name": "Python Tech", "description": "Event for python developers all over the world" } with self.app.app_context(): db.create_all() initialize_db()
def main (global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config (settings, 'sqlalchemy.') initialize_db (engine) config = Configurator (settings = settings) config.add_static_view ('static', 'static', cache_max_age = 3600) config.add_route ('home', '/') config.scan () return config.make_wsgi_app ()
def __init__(self): self.db = models.initialize_db(settings.database_dir) self.avg_user = models.User.raw(models.GLOBAL_PID, db=self.db) self.last_updated_d = datetime.fromtimestamp( float(json.loads(self.avg_user)[models.User.MTIME_KEY])) self.last_updated_float = float( calendar.timegm(self.last_updated_d.timetuple())) self.last_updated = self.last_updated_d.strftime("%a, %d %b %y %T GMT")
def setUp(self): """Executed before each test. Define test variables and initialize app.""" self.app = create_app(TestingConfig) self.client = self.app.test_client self.user = { "email": "*****@*****.**", "firstname": "Yeku Wilfred", "lastname": "chetat", "phone": "671357962", "password": "******" } with self.app.app_context(): # create all tables db.create_all() initialize_db()
def setUp(self): """Executed before each test. Define test variables and initialize app.""" self.app = create_app(TestingConfig) self.client = self.app.test_client self.event = { "title": "Markup Start", "description": "This is an event I am creating fo\ r meeting with friends", "start_datetime": "2020-05-30 15:45", "location": "Douala Bonamoussadi", "event_type_id": 1, "image_url": "https://img.nen/j.png", "organizer_id": 1 } with self.app.app_context(): db.create_all() initialize_db()
def initialize_db(): """bootstrap_endpoint Bootstraps the database using the models.initialize_db() method. Returns: dict, 201 response code: success dict, 500 response code: failure """ secret_key = request.get_json() if secret_key["key"] == SECRET: models.initialize_db() exists = models.db_exists(models.DB_NAME) routes_table_exists = models.table_exists("routes") route_lengths_exists = models.table_exists("route_lengths") assert exists == routes_table_exists == route_lengths_exists APP.logger.info("PostGres DB with tables is online.") return ( json.dumps({"Success!": "PostGres DB with postgis extensions is created."}), 201, ) APP.logger.warn("Error! Failed to initialize the db.") return json.dumps({"Error": "Failed to initialize the db"}), 500
import time as timer from datetime import datetime, timedelta import tornado.web import tornado.wsgi from google.appengine.ext import db import models import utils import precompute # initialize users and events if models.User.all().count() == 0: models.initialize_db() MAX_NUMBER_OF_EVENTS = 500 class MainHandler(tornado.web.RequestHandler): def get(self): err = {} user_id = self.get_argument("user_id", None) if not user_id: err["message"] = "Please append query parameter /?user_id=<int>" err["user_id"] = user_id self.write(utils.json_encode(err)) else: pipeline = precompute.EventCountPipeline(user_id)
def empty_database(): db.execute_sql('DROP TABLE IF EXISTS contact, addressbook') models.initialize_db()
# Usage: # python -i environment.py # >>> with session_scope() as s: # ... s.query(MxStatus).count() # __author__ = 'Jared Sanson <*****@*****.**>' __version__ = 'v0.1' import sqlalchemy as sql import sqlalchemy.orm from contextlib import contextmanager from datetime import datetime from models import initialize_db, MxStatus, MxLogPage, FxStatus engine = initialize_db() Session = sql.orm.sessionmaker(bind=engine) @contextmanager def session_scope(): session = Session() try: yield session session.commit() except: session.rollback() raise finally: session.close()
def init(): initialize_db() return 'OK', 200
}) # Error handlers. @app.errorhandler(500) def internal_error(error): return jsonify({"message": "internal server error", "status": 500}), 500 @app.errorhandler(404) def not_found_error(error): return jsonify({"message": "not found", "status": 404}), 404 @app.errorhandler(400) def bad_request_error(error): return jsonify({"message": "Bad request", "status": 400}), 400 # ----------------------------------------------------------------------------# # Launch. # ----------------------------------------------------------------------------# # Default port: if __name__ == '__main__': delete_db() initialize_db() load_database() app.run()
def before_request(): initialize_db()
def __enter__(self): self.db_session = initialize_db() return self
def empty_database(): db.execute_sql('DROP TABLE IF EXISTS contact, addressbook') models.initialize_db()
from twilio.rest import Client import config # Twilio Client # Kyle fix this please # client = Client(account_sid, auth_token) app = Flask(__name__) # conf = os.environ.get("APP_SETTINGS", "config.StagingConfig") # if os.environ.get("FLASK_ENV") == "production": # app.config.from_object(config.ProductionConfig) # else: app.config.from_object(config.StagingConfig) initialize_db(app) CORS(app, supports_credentials=True) with open("secrets.json") as f: secrets = json.load(f) @app.before_first_request def before_first_req(): db.session.execute("SELECT 1") # if not ConstantsModel.query.first(): # db.session.add(ConstantsModel()) # db.session.commit() def sqldict(row):
SLACK_TEAM_ID = os.environ["SLACK_TEAM_ID"] SLACK_TEAM_DOMAIN = os.environ["SLACK_TEAM_DOMAIN"] PAGE_SIZE = 5000 # set up application app = flask.Flask(__name__) app.secret_key = SESSION_SECRET_KEY # used to encrypt flask.session cookies on the client side # set up caching cache = Cache(app, config={"CACHE_TYPE": "simple"}) # set up database app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False models.initialize_db(app) # set up login using Slack OAuth (note: logins are only required when the app is not in debug mode) @app.route("/login") def login(): return slack_auth.login(SLACK_TEAM_ID, SLACK_CLIENT_ID, SLACK_AUTHORIZATION_REDIRECT_URL) @app.route("/logout", methods=["POST"]) def logout(): return slack_auth.logout("/") @app.route("/authorize") def authorize(): after_login_url = slack_auth.get_after_login_url() or "/" return slack_auth.authorize(SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, after_login_url, flask.redirect(after_login_url)) slackegginess_required = slack_auth.team_membership_required( SLACK_TEAM_ID, lambda page_url: flask.render_template("login.html", login_url=flask.url_for("login", next=page_url))
def __init__(self): self.engine: Engine = initialize_db()
sample_id, instance = map(int, sample[0].split('.')) return (sample_id * 1000) + instance metadata = sorted(raw_meta, key=samplekey) HASHED_MAP = defaultdict(list) for name, _, hashed in metadata: HASHED_MAP[name.split('.', 1)[0]].append(hashed) DOIT_CONFIG = { 'default_tasks': ['gen'], 'continue': True, 'pipeline_name': "HMP2 Visualizations" } db = models.initialize_db(settings.database_dir) firstitem = itemgetter(0) def extract_phylum(biom_row): for item in biom_row['metadata']['taxonomy']: if item.startswith("p__"): return item.replace("p__", '') return None def phylum_abd(biom_fname): with open(biom_fname) as f: data = json.load(f)
def get_config(config=None): """ This function defines the configuration of the site """ if config is None: config = Configurator() # Setup jinja templating config.include('pyramid_jinja2') config.add_jinja2_renderer('.html') # Static files config.add_static_view('static', 'static') config.add_static_view('assets', 'assets') # Home page is the editor config.add_route('editor', '/') # Calculation views config.add_route('calculations', '/calculations') config.add_route('calculation', '/calculations/{one}') # Static pages config.add_route('about', '/about') config.add_route('help', '/help') # Ajax paths config.add_route('submitquantum', '/ajax/submitquantum') config.add_route('smiles_to_sdf', '/ajax/smiles') config.add_route('sdf_to_smiles', '/ajax/sdf') # database settings = config.get_settings() settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager' # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') # use pyramid_retry to retry a request when transient exceptions occur config.include('pyramid_retry') # engine = get_engine(settings) models.initialize_db(engine) session_factory = get_session_factory(engine) config.registry['dbsession_factory'] = session_factory # make request.dbsession available for use in Pyramid config.add_request_method( # r.tm is the transaction manager used by pyramid_tm lambda r: get_tm_session(session_factory, r.tm), 'dbsession', reify=True) # Scan a Python package and any of its subpackages for objects marked with # configuration decoration config.scan() # Commit any pending configuration actions. config.commit() # Setup jinja enviroment jinja2_env = config.get_jinja2_environment() jinja2_env.filters['static_url'] = static_url_filter return config
def get_config(config=None): """ This function defines the configuration of the site """ if config is None: config = Configurator() # Setup jinja templating config.include('pyramid_jinja2') config.add_jinja2_renderer('.html') # Static files config.add_static_view('static', 'static') config.add_static_view('assets', 'assets') # Home page is the editor config.add_route('editor', '/') # Calculation views config.add_route('calculations', '/calculations') config.add_route('calculation', '/calculations/{one}') # Static pages config.add_route('about', '/about') config.add_route('help', '/help') # Ajax paths config.add_route('submitquantum', '/ajax/submitquantum') config.add_route('smiles_to_sdf', '/ajax/smiles') config.add_route('sdf_to_smiles', '/ajax/sdf') # database settings = config.get_settings() settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager' # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') # use pyramid_retry to retry a request when transient exceptions occur config.include('pyramid_retry') # engine = get_engine(settings) models.initialize_db(engine) session_factory = get_session_factory(engine) config.registry['dbsession_factory'] = session_factory # make request.dbsession available for use in Pyramid config.add_request_method( # r.tm is the transaction manager used by pyramid_tm lambda r: get_tm_session(session_factory, r.tm), 'dbsession', reify=True ) # Scan a Python package and any of its subpackages for objects marked with # configuration decoration config.scan() # Commit any pending configuration actions. config.commit() # Setup jinja enviroment jinja2_env = config.get_jinja2_environment() jinja2_env.filters['static_url'] = static_url_filter return config
def get_config(config=None): """This function defines the configuration of the site""" if config is None: config = Configurator() # Setup jinja templating config.include("pyramid_jinja2") config.add_jinja2_renderer(".html") # Static files config.add_static_view("static", "static") config.add_static_view("assets", "assets") # Home page is the editor config.add_route("editor", "/") # Calculation views config.add_route("calculations", "/calculations") config.add_route("calculation", "/calculations/{one}") # Static pages config.add_route("about", "/about") config.add_route("help", "/help") # Ajax paths config.add_route("submitquantum", "/ajax/submitquantum") config.add_route("smiles_to_sdf", "/ajax/smiles") config.add_route("sdf_to_smiles", "/ajax/sdf") # database settings = config.get_settings() settings["tm.manager_hook"] = "pyramid_tm.explicit_manager" # use pyramid_tm to hook the transaction lifecycle to the request config.include("pyramid_tm") # use pyramid_retry to retry a request when transient exceptions occur config.include("pyramid_retry") # engine = get_engine(settings) models.initialize_db(engine) session_factory = get_session_factory(engine) config.registry["dbsession_factory"] = session_factory # make request.dbsession available for use in Pyramid config.add_request_method( # r.tm is the transaction manager used by pyramid_tm lambda r: get_tm_session(session_factory, r.tm), "dbsession", reify=True, ) # Scan a Python package and any of its subpackages for objects marked with # configuration decoration config.scan() # Commit any pending configuration actions. config.commit() # Setup jinja enviroment jinja2_env = config.get_jinja2_environment() jinja2_env.filters["static_url"] = static_url_filter return config
SLACK_AUTHENTICATION_REDIRECT_URL = os.environ["SLACK_AUTHENTICATION_REDIRECT_URL"] SLACK_TEAM_ID = os.environ["SLACK_TEAM_ID"] PAGE_SIZE = 5000 # set up application app = flask.Flask(__name__) app.secret_key = SESSION_SECRET_KEY # used to encrypt flask.session cookies on the client side # set up caching cache = Cache(app, config={"CACHE_TYPE": "simple"}) # set up database app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False models.initialize_db(app) # set up login using Slack OAuth @app.route("/login") def login(): return slack_auth.login(SLACK_TEAM_ID, SLACK_CLIENT_ID, SLACK_AUTHENTICATION_REDIRECT_URL) @app.route("/logout", methods=["POST"]) def logout(): return slack_auth.logout("/") @app.route("/authenticate") def authenticate(): after_login_url = slack_auth.get_after_login_url() or "/" return slack_auth.authenticate(SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, after_login_url, flask.redirect(after_login_url)) slackegginess_required = slack_auth.team_membership_required( SLACK_TEAM_ID, lambda page_url: flask.render_template("login.html", login_url=flask.url_for("login", next=page_url))