def backup_app(appid): # get app try: app = app_module.get_app(appid) except OSError: logging.info('Could not get app with id: {}'.format(appid)) return # check this app is on this server if 'serverid' in os.environ and app['serverid'] != os.environ['serverid'] : logging.info('App not on this server: {}'.format(appid)) return # get user try: user = app_module.get_sysuser(app['sysuserid']) app['sysuser'] = user except OSError: logging.info('Could not get user with id: {}'.format(app['sysuserid'])) return # get databases try: databases = app_module.get_databases(appid) app['databases'] = databases except OSError: logging.info('Could not get databases for app {}'.format(appid)) return _backup_app(app)
def set_email(self, email: str) -> bool: """ Change the user's email address to the new given one. :param email: The user's new email address. Must not be used by a different user. :return: ``False`` if the email address already is in use by another user, ``True`` otherwise. """ old_email = self.get_email() if old_email == email: return True user = User.load_from_email(email) if user is not None and user != self: return False self._email = email if not old_email: # If there is no old email the user has just been created. Do not send an email in this case. return True application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) email_obj = Email(_('Your Email Address Has Been Changed'), 'userprofile/emails/change_email_address_confirmation') email_obj.prepare(name=self.name, new_email=email, support_email=support_address) email_obj.send(old_email) return True
def set_password(self, password: str) -> None: """ Hash and set the given password. :param password: The plaintext password. """ if not password: return # If the password stayed the same do not do anything; especially, do not send an email. if self.check_password(password): return # If the user does not have a password at the moment, their account has been newly created. Do not send an email # in this case. if self.password_hash is not None: application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) email = Email(_('Your Password Has Been Changed'), 'userprofile/emails/reset_password_confirmation') email.prepare(name=self.name, support_email=support_address) email.send(self.get_email()) self.password_hash = bcrypt.generate_password_hash(password)
def _set_email(self, email: str) -> bool: """ Change the user's email address to the new given one. An email will be sent to the user's old email address informing them about this change. :param email: The user's new email address. Must not be used by a different user. :return: `False` if the email address is already in use by another user, `True` otherwise. """ old_email = self.email if old_email == email: return True user = User.load_from_email(email) if user is not None and user != self: return False self._email = email if not old_email: # If there is no old email the user has just been created. Do not send an email in this case. return True application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) email_obj = Email( _('Your Email Address Has Been Changed'), 'userprofile/emails/change_email_address_confirmation') email_obj.prepare(name=self.name, new_email=email, support_email=support_address) email_obj.send(old_email) return True
def set_password(self, password: str) -> None: """ Hash and set the given password. :param password: The plaintext password. """ if not password: return # If the password stayed the same do not do anything; especially, do not send an email. if self.check_password(password): return # If the user does not have a password at the moment, their account has been newly created. Do not send an email # in this case. if self._password_hash is not None and self.email is not None: application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) email = Email(_('Your Password Has Been Changed'), 'userprofile/emails/reset_password_confirmation') email.prepare(name=self.name, support_email=support_address) email.send(self.email) self._password_hash = bcrypt.generate_password_hash(password)
def send(self, recipient: Union[str, List[str]]) -> None: """ Send the mail to the given recipients. :param recipient: A single recipient or a list of recipients to which the mail will be send. :raise TypeError: If the recipients argument is not a string or a list of strings. """ if isinstance(recipient, str): recipients = [recipient] elif isinstance(recipient, list): recipients = recipient else: raise TypeError( 'Argument "recipients" must be a string or a list of strings.') message = Message(self._subject, sender=self._sender, recipients=recipients) message.body = self._body_plain message.html = self._body_html application = get_app() thread = Thread(target=self._send, args=(message, application)) thread.start()
def __init__(self, subject: str, body: str, sender: Optional[str] = None) -> None: """ :param subject: The mail's subject line. :param body: The path (within the template folder) to the template for this mail's body (without the file extension). :param sender: The sender of the mail. If not set, the sender will be taken from the app configuration. :raise NoMailSenderError: If no sender is given and none is configured in the app configuration. :raise RuntimeError: If no application is available (i.e. outside the application context). """ application = get_app() title = application.config['TITLE_SHORT'] self._body_template_base_path: str = body self._body_plain: Optional[str] = None self._body_html: Optional[str] = None self._subject: str = f'{title} » {subject}' self._sender: Optional[str] = sender if self._sender is None: self._sender = application.config['MAIL_FROM'] # If the sender is still not known, raise an error. if self._sender is None: raise NoMailSenderError( 'No sender given and none configured in the app configuration.' )
def test_get_app_success(self): """ Test getting the current application object. Expected result: The application object is successfully returned. """ app = get_app() self.assertIsNotNone(app)
def runserver(host, port, debugger, reloader, threaded, processes, ssl): args = { 'host': host, 'port': port, 'debug': debugger, 'use_reloader': reloader, } if processes: args['processes'] = processes else: args['threaded'] = threaded if ssl: args['ssl_context'] = ('ssl_cert.cert', 'ssl_key.key') get_app().run(**args)
def _create_headers(self): with get_app().test_request_context(): identity = _create_identity_object(user=self._user, company=self._company) token = create_access_token(identity) return { 'Authorization': 'Bearer {}'.format(token) }
def setUp(self): self.app = app.get_app("TEST") self.app.config.update(SERVER_NAME='localhost') self.app_context = self.app.app_context() self.app_context.push() self.setup_dummy_data() self.client = self.app.test_client(use_cookies=True) self.user_data = {'email': "*****@*****.**", 'password': "******"}
def init(args): from app import get_app app = get_app(args) logging_level = logging.DEBUG if app.config['DEBUG'] else logging.INFO logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging_level) from routes import routes from api.subsonic import subsonic app.register_blueprint(routes) app.register_blueprint(subsonic) return app
def get_healthz(): app = get_app() flask_mode = os.environ.get('FLASK_ENV', 'development') return jsonify({ 'profile': f'{flask_mode}', 'debug': f'{app.debug}', 'app_env': f'{app.config["ENV"]}' })
def list_routes(): import urllib output = [] for rule in get_app().url_map.iter_rules(): methods = ','.join(rule.methods) output.append( map(urllib.parse.unquote, [rule.endpoint, methods, str(rule)])) print(tabulate(output, headers=['Endpoint', 'Methods', 'URL']))
def test_cache(self): from flask.ext.cache import Cache import app as app_module with app_module.get_app().app_context(): from flask import current_app as app cache = Cache(app, config={'CACHE_TYPE': 'simple'}) blog_cache = BlogCache(cache) self.assertEqual(blog_cache.get('blog', 'key'), None) blog_cache.set('blog', 'key', 'value') self.assertEqual(blog_cache.get('blog', 'key'), 'value') blog_cache.invalidate('blog') self.assertEqual(blog_cache.get('blog', 'key'), None)
def init(args): from app import get_app app = get_app(args) logging_level = logging.DEBUG if app.config['DEBUG'] else logging.INFO logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging_level) from routes import routes from api.subsonic import subsonic app.register_blueprint(routes) app.register_blueprint(subsonic) return app
def setup(context=None, config=None): if config: config.update(get_test_settings()) else: config = get_test_settings() drop_elastic(config) app = get_app(config) drop_mongo(app) if context: context.app = app context.client = app.test_client()
def xtest_json_response(self): _test_foo_data = { "test": "data" } @json_response def _test_foo(): return _test_foo_data with get_app().app_context(): result, code = _test_foo() self.assertEqual(loads(result), _test_foo_data) self.assertEqual(code, 200)
def test_csv(self): app = appl.get_app(test=True) client = app.test_client() response = client.post( '/editor', data=dict( source= "https://raw.githubusercontent.com/oeg-upm/morph-rdb/master/morph-examples/examples-csv/SPORT.csv", ontologies=['dbpedia'], kg="", ), follow_redirects=True) self.assertEquals(response.status_code, 200) self.assertNotIn('error', str(response.data).lower())
def app(): app = get_app() server_config = ConfigManager.get_instance().get_server_config() application_root = ConfigManager.get_instance().get_application_root() app.register_blueprint(waypoint_controller, url_prefix=application_root) app.register_blueprint(incidence_controller, url_prefix=application_root) app.register_blueprint(municipality_controller, url_prefix=application_root) app.config['DEVELOPMENT'] = server_config["development"] yield app
def setup(context=None, config=None): app_config = get_test_settings() if config: app_config.update(config) app = get_app(app_config) drop_elastic(app) drop_mongo(app) # create index again after dropping it app.data.elastic.init_app(app) if context: context.app = app context.client = app.test_client()
def test_get_app_failure(self): """ Test getting the current application object outside the application context. Expected result: ``None`` is returned without an exception. """ # Remove the application context. self.app_context.pop() app = get_app() self.assertIsNone(app) # Re-add the application context so the tear-down method will not pop an empty list. self.app_context.push()
def test_get_app_failure(self): """ Test getting the current application object outside the application context. Expected result: `None` is returned without an exception. """ # Remove the application context. self.app_context.pop() with self.assertRaises(NoApplicationError): app = get_app() self.assertIsNone(app) # Re-add the application context so the tear-down method will not pop an empty list. self.app_context.push()
def login_validate(): username = request.json.get('username', None) password = request.json.get('password', None) remember = request.json.get('remember', False) form = LoginForm() valid = form.validate() print(form.errors) if valid: user = User.query.filter_by(username=username).first() if user and user.verify_password(pwd=password): login_user(user, remember) session.permanent = True app = get_app() app.permanent_session_lifetime = timedelta( minutes=app.config['SESSION_LIFETIME']) return jsonify({'next_url': url_for('todo_list.index')}) else: flash('Invalid username or password, please try again.') return jsonify({'next_url': url_for('login.index')})
def delete(self) -> None: """ Delete the user's account. Log them out first if necessary. Notify them via mail. This action will directly be committed to the database. """ if self == current_user: self.logout() # Notify the user via email. application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) email = Email(_('Your User Profile Has Been Deleted'), 'userprofile/emails/delete_account_confirmation') email.prepare(name=self.name, new_email=self.get_email(), support_email=support_address) email.send(self.get_email()) db.session.delete(self) db.session.commit()
def setUp(self): from app import get_app from api.subsonic import subsonic Args = collections.namedtuple( 'Args', 'with_scanner config debug yes host port check test_regex') app = get_app( Args(with_scanner=False, config=os.path.join(os.path.dirname(__file__), 'test', 'settings.cfg'), debug=False, yes=False, host='0.0.0.0', port='5000', check=False, test_regex=False)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test/festival.db' app.config['TESTING'] = True app.register_blueprint(subsonic) self.app = app.test_client()
def runserver(): # if sys.argv[1] == 'db': # call(['alembic', '-c', os.path.join(os.path.dirname(__file__), 'migrations', 'alembic.ini')] + sys.argv[2:]) bottle.run( app=app.get_app(), **app.config.get( 'Server', { 'server': 'wsgiref', 'host': '127.0.0.1', 'port': 8000, 'interval': 1, 'reloader': True, 'quiet': False, 'plugins': None, 'debug': True, 'config': None, } ) )
def setUp(self): self.external_url = 'http://23.253.252.30' app = get_app('testsdb') self.app = app.test_client() db.create_all() self.speeding = Crime("Speeding", "www.speeding.com", "Goin' real real fast!") self.ched = Celebrity(name='Ched', description='Actor', twitter_handle='@Ched', birthday=date(1900,1,1), wiki_url='ched.wiki', imdb_url='ched.imdb', picture_url='ched.picture') self.charge1 = Charge(date=date(2000,1,1), location='Austin, Texas', description='Driving Fast!', classification='Class A misdemeanor', crime = self.speeding, celebrity = self.ched) self.cr1 = Crime("1") self.cr2 = Crime("2") self.ce1 = Celebrity("1") self.ce2 = Celebrity("2")
def setup(context=None, config=None): app_config = get_test_settings() if config: app_config.update(config) app = get_app(app_config) logger = logging.getLogger('superdesk') logger.setLevel(logging.ERROR) logger = logging.getLogger('elasticsearch') logger.setLevel(logging.ERROR) logger = logging.getLogger('urllib3') logger.setLevel(logging.ERROR) drop_elastic(app) drop_mongo(app) # create index again after dropping it app.data.elastic.init_app(app) if context: context.app = app context.client = app.test_client()
def __init__(self, validity: Optional[int] = None) -> None: """ :param validity: If not `None`, the specified value will be used as the validity (in seconds) for the token from its time of creation. If `None`, the validity set in the application configuration (`TOKEN_VALIDITY`) will be used. """ application = get_app() self._jwtoken_class: str = self._get_class_name() """ The name of the class creating the token. Used for validation of a token. """ self._key: str = application.config['SECRET_KEY'] """ The private key for encoding and decoding the token. """ self._validity: int = application.config['TOKEN_VALIDITY'] """ The time in seconds how long the token will be valid after its time of creation. """ if validity is not None: self._validity = validity self._expiration_date: Optional[float] = None """ The date and time when this token will be expire. Specified as the time in seconds since the epoch_. .. _epoch: https://docs.python.org/3/library/time.html#epoch """ self._token: Optional[str] = None """
def __init__(self, query: BaseQuery, page_param: str = 'page') -> None: """ Initialize the pagination object. The current page will be determined from the page parameter in the request arguments. If the page parameter is not included in the request arguments, the current page defaults to `1`. :param query: The base query that will be paginated. :param page_param: The name of the page parameter specifying the current page. Defaults to `page`. """ # Get the current page from the request arguments. try: self.current_page = request.args.get(page_param, 1, type=int) except TypeError: # In tests, the above call fails because get does not take keyword arguments - it does however work outside # of requests. Thus, fall back to this manual conversion. self.current_page = int(request.args.get(page_param, 1)) application = get_app() self.rows_per_page = application.config['ITEMS_PER_PAGE'] self._rows = query.paginate(self.current_page, self.rows_per_page)
def __init__(self, query: BaseQuery, page_param: str = 'page') -> None: """ The current page will be determined from the page parameter in the request arguments. If the page parameter is not included in the request arguments, the current page defaults to `1`. :param query: The base query that will be paginated. :param page_param: The name of the page parameter specifying the current page. Defaults to ``page``. """ self.current_page: int self.rows_per_page: int # Get the current page from the request arguments. try: self.current_page = request.args.get(page_param, 1, type=int) except TypeError: # In tests, the above call fails because get does not take keyword arguments - it does however work outside # of requests. Thus, fall back to this manual conversion. self.current_page = int(request.args.get(page_param, 1)) application = get_app() self.rows_per_page = application.config['ITEMS_PER_PAGE'] self._rows = query.paginate(self.current_page, self.rows_per_page)
def _delete(self) -> None: """ Delete the user's account. Log them out first if necessary. Notify them via mail. This action will directly be committed to the database. """ if self == current_user: self.logout() # Notify the user via email. application = get_app() support_address = application.config.get('SUPPORT_ADDRESS', None) if self.email is not None: email = Email(_('Your User Profile Has Been Deleted'), 'userprofile/emails/delete_account_confirmation') email.prepare(name=self.name, new_email=self.email, support_email=support_address) email.send(self.email) db.session.delete(self) db.session.commit()
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from app import get_app application = get_app()
#!/usr/bin/env python # -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license """Superdesk Manager""" import superdesk from flask.ext.script import Manager from app import get_app app = get_app(init_elastic=True) manager = Manager(app) if __name__ == '__main__': manager.run(superdesk.COMMANDS)
from app import get_app celery = get_app().celery
""" Runs the lunchticket webapi """ import os from app import get_app, create_app CONFIG_TYPE = os.getenv('APP_SETTINGS') or 'development' APP = get_app(create_app)(CONFIG_TYPE) if __name__ == '__main__': APP.run(host=APP.config.get('HOST'), port=APP.config.get('PORT'), ssl_context=('cert/localhost.crt', 'cert/localhost.key'))
def setUp(self): app_config = self.get_test_settings() self.app = get_app(app_config)
def create_app(self): app = get_app('config.TestConfiguration') return app
for k, v in rating_prior.items(): rating_prior[k] = (rating_prior[k] - r_min) / (r_max - r_min) * 40.0 neighbor_avgs = rm.compute_avgs(games, rating_prior) print('%d : %.4f' % (i, loss)) # Update the ratings and show how we did. wins, losses = {}, {} for g in g_vec: wins[g[0]] = wins.get(g[0], 0) + g[2] losses[g[0]] = losses.get(g[0], 0) + 1 - g[2] wins[g[1]] = wins.get(g[1], 0) + 1 - g[2] losses[g[1]] = losses.get(g[1], 0) + g[2] for k in sorted(rating_prior, key=lambda k: rating_prior[k]): db.session.add(Rating(user_id=k, rating=rating_prior[k])) print("%d: %f (%d - %d)" % (k, rating_prior[k], wins.get(k, 0), losses.get(k, 0))) db.session.commit() if __name__ == '__main__': app = get_app('config.DockerConfiguration') with app.app_context(): #db.session.remove() #Rating.__table__.drop(db.engine) #db.get_engine(app).dispose() #db.create_all() rate_all()
rated=False, result=result, game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 10000000)), ) return g print("Games...") games = [make_game() for i in range(2000)] print("Saving games...") for g in games: db.session.add(g) db.session.commit() strongest = max(p_priors, key=lambda k: p_priors[k]) strongest_games = [str(g) for g in games if g.white.user_id == strongest or g.black.user_id == strongest] print("Strongest, %d (%f):\n%s" % (strongest, p_priors[strongest], strongest_games)) if __name__ == "__main__": app = get_app("config.DockerConfiguration") with app.app_context(): db.session.remove() db.drop_all() db.get_engine(app).dispose() print("Creating tables...") db.create_all() print("Creating test data...") create_test_data() print("Creating extra data...") create_extra_data()
"""Ingest Uploader""" from flask.ext.script import Manager from app import get_app from eve.utils import config import ntpath import imghdr import sys import os from superdesk import get_resource_service from superdesk.media.renditions import generate_renditions from superdesk.upload import url_for_media app = get_app() manager = Manager(app) def upload_fixture_image(fixture_image_path, headline='test'): with app.app_context(): with open(fixture_image_path, mode='rb') as f: file_name = ntpath.basename(fixture_image_path) file_type = 'image' content_type = '%s/%s' % (file_type, imghdr.what(f)) file_id = app.media.put( f, filename=file_name, content_type=content_type, resource=get_resource_service('ingest').datasource, metadata={} )
def main(): import gevent.monkey; gevent.monkey.patch_all() import pages, bottle from app import get_app bottle.run(app=get_app(), reloader=True, debug=True, server='gevent') pass
from flask_script import Manager as ScriptManager from app import get_app script_manager = ScriptManager(get_app())
from app import get_app from app.models import db app = get_app('config.DockerConfiguration') db.init_app(app) app.app_context().__enter__()
#!/usr/bin/env python # -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license """Superdesk Manager""" import superdesk from flask_script import Manager from app import get_app app = get_app(init_elastic=False) manager = Manager(app) if __name__ == '__main__': manager.run(superdesk.COMMANDS)
# This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license """Superdesk Manager""" import arrow import superdesk from flask_script import Manager from app import get_app app = get_app() manager = Manager(app) @manager.option('-l', '--limit', type=int) def fix_timestamps(limit=0): lookup = {'extra.original_published_at': {'$ne': None}} items = superdesk.get_resource_service('archive').get_from_mongo( req=None, lookup=lookup) updated = 0 for item in items: try: published = arrow.get( item['extra']['original_published_at']).datetime except ValueError: continue
from app import get_app application = get_app()