def setUp(self): """Define test variables and initialize app.""" self.app = app_factory(config.Testing, config.project_name) self.client = self.app.test_client self.new_company = company = { "name": "New Company", "description": "A company", "company_type": "buyer" } self.updated_company = company = { "name": "Updated Company", "description": "A company", "company_type": "buyer" } self.comparison_company = { "id": 1, "name": "New Company", "description": "A company", "company_type": "buyer", "products": [], "orders": [] } self.updated_comparison_company = { "id": 1, "name": "Updated Company", "description": "A company", "company_type": "buyer", "products": [], "orders": [] } # binds the app to the current context with self.app.app_context(): # drop and create all tables db.drop_all() db.create_all()
def setUpClass(cls): print "" print cls.__display__ from main import app_factory from database import db, create_all, drop_all cls.app = app_factory(config.Testing) cls.client = cls.app.test_client() cls.app_key = 'testing' cls.api_token_admin = 'adminadmin' cls.api_token_member = 'membermember' cls.api_token_client = 'clientclient' drop_all() create_all() db.engine.execute('INSERT INTO `applications` (id, name, display, app_key, status) VALUES (1, "reflectiv", "Reflectiv", "testing", "DEV");') db.engine.execute('INSERT INTO `application_plans` (id, display, description, application_id, sms, members, storage, projects, monthly_price, yearly_price, currency, share) VALUES (1, "Free membership", "Free membership", 1, 0, 3, 0, 3, 0, 0, "USD", 50);') db.engine.execute('INSERT INTO `organizations` (name, display, currency, application_id, application_plan_id, created) VALUES ("reflectiv", "Reflectiv", "USD", 1, 1, "2014-04-01 00:00:00");') db.engine.execute('INSERT INTO `members` (id, display, organization_id, status, is_admin, is_disabled, lang) VALUES (1, "Administrator", 1, "MEMBER", 1, 0, "en"), (2, "Simple Member", 1, "MEMBER", 0, 0, "en"), (3, "Client", 1, "CLIENT", 0, 0, "en");') db.engine.execute('INSERT INTO `sessions` (expires, token, member_id) VALUES ("2015-12-31 00:00:00", "adminadmin", 1), ("2015-12-31 00:00:00", "membermember", 2), ("2015-12-31 00:00:00", "clientclient", 3);')
def run(self): from flask import request from wufoo.wufoo_model import WufooSurveyModel app = app_factory(config.Dev) with app.test_client() as c: from database import db test_file = open("test/wufoo.json", "r").read() test_json_dict = json.loads(test_file) form_structure = json.loads(test_json_dict['FormStructure']) form_url = "https://rubinovitz.wufoo.com/forms/my-new-feature/" print form_structure new_survey = WufooSurveyModel(username="******", wufoo_email=form_structure['Email'], url=form_url, name=form_structure['Url']) db.session.add(new_survey) db.session.commit() rv = c.post('/api/v1/wufoo', data=test_json_dict) db.session.delete(new_survey) print rv
def setUp(self): import config from main import app_factory from database import create_all self.app = app_factory(config.Testing) self.client = self.app.test_client() create_all()
def run(self, new=False): """ Run the mining args: new- if true, check for users that haven't been mined yet and mine only their data. """ from twitter.twitter_model import TwitterModel from quickbooks.quickbooks_model import QuickbooksUser from facebook.facebook_model import FacebookModel from google_analytics.google_analytics_models import GoogleAnalyticsUserModel from twitter.twitter_mine import track_keywords from google_analytics.ga_mine import mine_visits from facebook.fb_mine import mine_fb_page_data from quickbooks.qb_mine import mine_qb_data app = app_factory(config.Dev) print 'inside mine' with app.app_context(): api_token = app.config.get('QUICKBOOKS_SERVER_API_TOKEN') quickbooks_server_url = app.config.get( 'QUICKBOOKS_SERVER_URL') + "/data" if new: new_twitters = TwitterModel.query.filter_by(active=False).all() new_fbs = FacebookModel.query.filter_by(active=False).all() new_gas = GoogleAnalyticsUserModel.query.filter_by( active=False).all() new_qbs = QuickbooksUser.query.filter_by(active=False).all() for user in new_twitters: try: track_keywords(username=user.username) except: print '%s failed twitter mine' % (user.username) for user in new_fbs: try: mine_fb_page_data(username=user.username) except: print '%s failed fb mine' % (user.username) for user in new_gas: try: mine_visits(username=user.username) except: print '%s failed ga visitor mine' % (user.username) for user in new_qbs: try: mine_visits( username=user.username, quickbooks_server_url=quickbooks_server_url, api_token=api_token) except: print '%s failed qb mine' % (user.username) else: mine_fb_page_data() mine_visits() track_keywords() mine_qb_data(quickbooks_server_url, api_token)
def client(loop, aiohttp_client, create_tables): logger.debug("Create test client") app = app_factory( global_config=config["DEFAULT"], **config['app:main'], ) return loop.run_until_complete(aiohttp_client(app))
def setUpClass(cls): print "" print cls.__display__ from main import app_factory from database import db, create_all, drop_all cls.app = app_factory(config.Testing) cls.client = cls.app.test_client() drop_all() create_all()
def run(self): app = app_factory(config.Dev) with app.app_context(): from database import db from google_analytics.google_analytics_models import GoogleAnalyticsUserModel ga_users = GoogleAnalyticsUserModel.query.all() print 'ga_users before' + str(ga_users) for ga_user in ga_users: db.session.delete(ga_user) db.session.commit() print 'ga_users now ' + str( [ga_user.refresh_token for ga_user in ga_users])
def setUp(self): import config from main import app_factory from extensions import db self.app: Empty = app_factory(config.Test, config.project_name) self.client = self.app.test_client() # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure/page/2 self.app_context = self.app.app_context() self.app_context.push() db.create_all()
def setUpClass(cls): print("") print(cls.__display__) from main import app_factory from database import db, create_all, drop_all cls.app = app_factory(config.Testing) cls.client = cls.app.test_client() drop_all() create_all() db.engine.execute('INSERT INTO ...') # Maybe some default datas ?
def run(self, new=False): """ Run the mining args: new- if true, check for users that haven't been mined yet and mine only their data. """ app = app_factory(config.Dev) with app.app_context(): from scale.scale_model import StartupDataModel from scale.scale_mine import get_vcs users = StartupDataModel.query.filter_by( vc_matcher_done=False).filter( StartupDataModel.description != None).all() if users: get_vcs(users)
def create_app(self): from main import app_factory from depot.manager import DepotManager import config_defaults #app = Flask(__name__) #app.config['TESTING'] = True # Default port is 5000 config_defaults.Config['LIVESERVER_PORT'] = 8943 # Default timeout is 5 seconds config_defaults.Config['LIVESERVER_TIMEOUT'] = 10 application = app_factory(config_defaults.Config, config_defaults.project_name) return application
def run(self, suite=None): blueprint = None tests = None if suite: if suite.find('.'): blueprint, tests = suite.split('.', 1) else: blueprint = suite app = app_factory(config=config.Testing) client = app.test_client() with app.app_context(): db.drop_all() db.create_all() db.engine.execute('SET foreign_key_checks=0' ) # We don't need foreign key checks on tests unittest.TextTestRunner(verbosity=2).run( BlueprintTesting(blueprint, tests).suite()) db.drop_all()
def run(self): import csv app = app_factory(config.Dev) with app.app_context(): from database import db from users.user_model import User with open('user_table.csv', 'rb') as csvfile: for row in csvfile: id, email, password, last_login_at, current_login_at, last_login_ip, current_login_ip, login_count, created, company, active, confirmed_at, onboarded = row.split( ';') active = True new_user = User(email=email, password=password, company=company, active=active, onboarded=False) db.session.add(new_user) db.session.commit() print 'user ' + email + 'migrated'
def create_app(self): from main import app_factory from depot.manager import DepotManager import config_defaults if 'admin_queryEndpoint' in config_defaults.Test: del config_defaults.Test['admin_queryEndpoint'] del config_defaults.Test['admin_updateEndpoint'] del config_defaults.Test['knowledge_queryEndpoint'] del config_defaults.Test['knowledge_updateEndpoint'] # Default port is 5000 config_defaults.Test['LIVESERVER_PORT'] = 8943 # Default timeout is 5 seconds config_defaults.Test['LIVESERVER_TIMEOUT'] = 10 application = app_factory(config_defaults.Test, config_defaults.project_name) application.config['TESTING'] = True application.config['WTF_CSRF_ENABLED'] = False return application
def run(self): import urllib from main import app_factory app = app_factory(config.Dev) output = [] for rule in app.url_map.iter_rules(): options = {} for arg in rule.arguments: options[arg] = "[{0}]".format(arg) methods = ','.join(rule.methods) try: url = url_for(rule.endpoint, **options) line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url)) except: line = "{:50s} {:20s} {}".format(rule.endpoint, methods, rule.rule) output.append(line) for line in sorted(output): print line
def setUp(self): """Define test variables and initialize app.""" self.app = app_factory(config.Testing, config.project_name) self.client = self.app.test_client self.company = {"name":"Seller Company", "description":"A selling company", "company_type": "seller"} self.product = {"name":"First Product", "description":"A first product", "price": 10.0, "company_id": 1} self.updated_product = {"name":"Updated Product", "description":"A first product", "price": 10.0, "company_id": 1} self.comparison_product = { "company": { "company_type": "seller", "description": "A selling company", "id": 1, "name": "Seller Company" }, "description": "A first product", "id": 1, "name": "First Product", "price": 10.0 } self.updated_comparison_product = { "company": { "company_type": "seller", "description": "A selling company", "id": 1, "name": "Seller Company" }, "description": "A first product", "id": 1, "name": "Updated Product", "price": 10.0 } # binds the app to the current context with self.app.app_context(): # drop and create all tables db.drop_all() db.create_all() self.client().post('/companies', data=self.company)
def run(self, new=False): app = app_factory(config.Dev) with app.app_context(): from database import db from sqlalchemy.sql import func from users.user_model import Role, User from google_analytics.google_analytics_models import GoogleAnalyticsVisitors from twitter.twitter_model import TwitterModel, CohortTweetCountModel from facebook.facebook_model import FacebookPageData, CohortFacebookLikesModel # get all cohorts cohorts = db.session.query(Role.name.distinct()).all() yesterday = datetime.datetime.now() - timedelta(days=1) today = datetime.datetime.now() # mine for each cohort for cohort in cohorts: # get yesterday and today so we can query changes in between days if not new: start = yesterday end = today else: start = db.session.query(GoogleAnalyticsVisitors).order_by( GoogleAnalyticsVisitors.date).first().date end = today while start < end: # get all users in cohort cohort_usernames = User.query.filter( User.roles.any(name=cohort[0])).with_entities( User.email).all() # get all GA visitor counts from after this time yesterday and before now visitors = GoogleAnalyticsVisitors.query.filter( GoogleAnalyticsVisitors.username.in_(cohort_usernames), GoogleAnalyticsVisitors.date > start, GoogleAnalyticsVisitors.date < end).with_entities( GoogleAnalyticsVisitors.visitors).all() detupled_vistors = [x[0] for x in visitors] print detupled_vistors if detupled_vistors: visitor_avg = ( sum(detupled_vistors)) / len(detupled_vistors) else: visitor_avg = 0 new_ga_visitors = GoogleAnalyticsVisitors.query.filter_by( username="******" + cohort[0], date=start).first() if not new_ga_visitors: new_ga_visitors = GoogleAnalyticsVisitors( username="******" + cohort[0], visitors=visitor_avg, date=start) else: new_ga_visitors.visitors = visitor_avg db.session.add(new_ga_visitors) db.session.commit() start = start + timedelta(days=1) # because you don't have time to figure out this query in SQLAlchemy right now tweet_DateCounts = {} fb_like_DateCounts = {} for username in cohort_usernames: twitter_words = TwitterModel.query.filter_by( username=username).first() if twitter_words: twitter_words = twitter_words.words for word in twitter_words: word_name = word.word dates = [ counts.date for counts in word.counts.all() if counts.date > yesterday and counts.date < today ] counts = [ counts.count for counts in word.counts.all() if counts.date > yesterday and counts.date < today ] for i in range(len(dates)): date = dates[i] count = counts[i] try: tweet_DateCounts[ date] = tweet_DateCounts[date] + count except: tweet_DateCounts[date] = count facebook_likes = FacebookPageData.query.filter_by( username=username).all() for like in facebook_likes: date = like.date like_count = like.likes try: fb_like_DateCounts[ date] = fb_like_DateCounts[date] + 1 except: fb_like_DateCounts[date] = like_count for date in tweet_DateCounts: count = tweet_DateCounts[date] new_tweet_count = CohortTweetCountModel.query.filter_by( date=date).first() if not new_tweet_count: new_tweet_count = CohortTweetCountModel( cohort_name=cohort, date=date, count=count) else: new_tweet_count.count = count db.session.add(new_tweet_count) db.session.commit() for date in fb_like_DateCounts: count = fb_like_DateCounts[date] new_fb_count = CohortFacebookLikesModel.query.filter_by( date=date).first() if not new_fb_count: new_fb_count = CohortFacebookLikesModel( cohort_name=cohort, date=date, likes_count=count) else: new_fb_count.count = count db.session.add(new_fb_count) db.session.commit()
# coding:utf-8 import sys #site.addsitedir('/apps/ontology_browser/venv') app_dir = '/home/hbgd/hbgdki_ontology/hbgd' if not app_dir in sys.path: sys.path.insert(0, app_dir) from main import app_factory import config application = app_factory(config.Config, config.project_name)
def run(self): app = app_factory(config.Dev) with app.app_context(): requests.get(app.config.get('QUICKBOOKS_SERVER_URL'))
def setUp(self): """docstring for setUp""" self.app = app_factory(Testing).test_client() self.db = get_db()
import sys sys.path.append('/var/www/invoicy/app/') from main import app_factory import config_prod app = app_factory(config_prod.Prod)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Ivan Kolodyazhny. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import config from main import app_factory app = app_factory(config=config.Production)
from main import app_factory app = app_factory()
import config from main import app_factory app = app_factory(config=config.Production)
# coding:utf-8 from main import app_factory import config app = app_factory(config.Config, config.project_name)
''' initialize app defined by blueprint in apis.py ''' from .apis import blueprint from main import app_factory from flask import (Flask, request_finished) from database import Session import config app = Flask(__name__) app = app_factory(config.Config, config.project_name) app.register_blueprint(blueprint) # remove session when connection completed def remove_session(sender, response, **extra): Session.remove() request_finished.connect(remove_session, app)
# coding:utf-8 from main import app_factory from config import project_name import os config_obj_path = os.environ['FLASK_CONFIG_DEFAULT'] app = app_factory(config_obj_path, project_name) if __name__ == '__main__': args = (app,) kwargs = { 'host': '0.0.0.0', 'port': 5000, 'debug': os.getenv('FLASK_DEBUG', '0') == '1', 'use_reloader': os.getenv('FLASK_DEBUG', '0') == '1', } {% if cookiecutter.use_socketio -%} from extensions import io io.run(*args, **kwargs) {% else %} app.run(*args, **kwargs) {% endif %}
# coding:utf-8 import sys #site.addsitedir('/apps/satoru/venv') app_dir = '/apps/satoru' if not app_dir in sys.path: sys.path.insert(0, app_dir) from main import app_factory import config application = app_factory(config.Config, config.project_name) celery = application.celery
import config from main import app_factory app = app_factory(config=config.Dev) from .flaskkeystone import flask_keystone keystone = flask_keystone.Keystone(app) keystone.init_app(app)
from main import app_factory from config import project_name import os try: config_obj_path = os.environ['FLASK_CONFIG_DEFAULT'] except KeyError as e: print( "Please, provide the environment variable FLASK_CONFIG_DEFAULT. It is required." ) exit() app = app_factory(config_obj_path, project_name) if __name__ == '__main__': _debug = app.config.get('DEBUG', False) kwargs = { 'host': os.getenv('FLASK_HOST', '0.0.0.0'), 'port': int(os.getenv('FLASK_PORT', '5000')), 'debug': _debug, 'use_reloader': app.config.get('USE_RELOADER', _debug), **app.config.get('SERVER_OPTIONS', {}) } app.run(**kwargs)
activate_this = '/home/usernama/virtualenv_path/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys sys.path.insert(0, '/var/www/gisservices') from main import app_factory from os import environ import config environ['GISSERVICES_CONFIG'] = '/var/www/gisservices/local_config.py' application = app_factory(config.Config)
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery app = app_factory(config.Dev) app.config.update(CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379') celery = make_celery(app) @celery.task() def add_together(a, b): return a + b if __name__ == "__main__": app.run()
from flask.ext.script import Manager from flask.ext.lettuce import Harvest if __name__ == "__main__": import config from main import app_factory manager = Manager(app_factory) manager.add_option("-c", "--config", dest="config_obj", default=config.Dev, required=False) manager.add_command("harvest", Harvest(lambda: app_factory(config.Test))) manager.run()
# coding:utf-8 from main import app_factory from config import cmm app = app_factory(cmm, cmm.project_name) if __name__ == '__main__': app.run()
def create_app(self): return app_factory(TestConfig)
import sys sys.path.append('/srv/www/2lead.in/api/') from main import app_factory import config app = app_factory(config.Prod)
def setUp(self): """Define test variables and initialize app.""" self.app = app_factory(config.Testing, config.project_name) self.client = self.app.test_client self.seller_company = { "name": "Seller Company", "description": "A selling company", "company_type": "seller" } self.buyer_company = { "name": "Buyer Company", "description": "A buying company", "company_type": "buyer" } self.product = { "name": "First Product", "description": "A first product", "price": 10.0, "company_id": 1 } self.product2 = { "name": "Second Product", "description": "A second product", "price": 20.0, "company_id": 1 } self.order = json.dumps({ "buyer_id": 2, "seller_id": 1, "line_items": [{ "product_id": 1, "quantity": 3 }, { "product_id": 2, "quantity": 1 }] }) self.comparison_order = { "buyer": { "company_type": "buyer", "description": "A buying company", "id": 2, "name": "Buyer company" }, "id": 1, "line_items": [{ "product": { "description": "A first product", "id": 1, "name": "First Product", "price": 10 }, "quantity": 3, "unit_price": 30 }, { "product": { "description": "A second product", "id": 1, "name": "Second Product", "price": 20 }, "quantity": 1, "unit_price": 20 }], "seller": { "company_type": "seller", "description": "A selling company", "id": 1, "name": "Seller Company" }, "total": 50 } # binds the app to the current context with self.app.app_context(): # drop and create all tables db.drop_all() db.create_all() self.client().post('/companies', data=self.seller_company) self.client().post('/companies', data=self.buyer_company) self.client().post('/products', data=self.product) self.client().post('/products', data=self.product2)