Exemple #1
0
def send_mail(groups,
              subject,
              msg_body,
              add_dests=None,
              sendername='recrutement'):
    '''
    envoie un mail aux administrateurs de l'application
    '''
    if add_dests is None:
        add_dests = []

    # supprimer chaines vides dans listes email
    add_dests = list(filter(lambda x: len(x), add_dests))

    app = get_app()
    if not app.config['SEND_MAIL']:
        return

    dests = add_dests

    msg = Message('[%s] %s' % (sendername, subject),
                  sender=app.config['MAIL_SENDER'],
                  recipients=dests)
    msg.body = msg_body

    thr = threading.Thread(target=_send_async, args=[app, msg, groups])
    thr.start()
def app():
    config_path = get_config_file_path()
    config = load_config(config_path)
    app = server.get_app(config)
    app.config["TESTING"] = True
    app.config["WTF_CSRF_ENABLED"] = False
    return app
Exemple #3
0
def send_mail(
        groups, subject, msg_body,
        add_dests=None, sendername='recrutement'):
    '''
    envoie un mail aux administrateurs de l'application
    '''
    if add_dests is None:
        add_dests = []

    # supprimer chaines vides dans listes email
    add_dests = list(filter(lambda x: len(x), add_dests))

    app = get_app()
    if not app.config['SEND_MAIL']:
        return

    dests = add_dests

    msg = Message(
            '[%s] %s' % (sendername, subject),
            sender=app.config['MAIL_SENDER'],
            recipients=dests)
    msg.body = msg_body

    thr = threading.Thread(target=_send_async, args=[app, msg, groups])
    thr.start()
Exemple #4
0
def get_app_for_cmd(config_file=None, with_external_mods=True):
    """ Return the flask app object, logging error instead of raising them"""
    try:
        conf = load_config(config_file)
        return get_app(conf, with_external_mods=with_external_mods)
    except ConfigError as e:
        log.critical(str(e) + "\n")
        sys.exit(1)
Exemple #5
0
def get_app_for_cmd(config_file=None, with_external_mods=True):
    """ Return the flask app object, logging error instead of raising them"""
    try:
        conf = load_config(config_file)
        return get_app(conf, with_external_mods=with_external_mods)
    except ConfigError as e:
        log.critical(str(e) + "\n")
        sys.exit(1)
Exemple #6
0
def main():
    app = get_app()
    bootstrap = Bootstrap(app)
    import routes
    import api
    #  import pdb;pdb.set_trace();
    app.run(app.config['HOST'],
            app.config['PORT'],
            **app.config['OPTIONS'])
Exemple #7
0
def geonature_app():
    """ set the application context """
    config_path = get_config_file_path()
    config = load_config(config_path)
    app = server.get_app(config)
    ctx = app.app_context()
    ctx.push()
    yield app
    ctx.pop()
Exemple #8
0
 def setUp(self):
     """Define test variables and initialize app."""
     self.app = get_app(load_config())
     self.client = self.app.test_client
     self.observations_post_data = {
         'cd_nom': 3582,
         'obs_txt': 'Tada',
         'count': 1,
         'geometry': {"type": "Point", "coordinates": [5, 45]}
     }
Exemple #9
0
def server():
    if os.path.exists(config.DB_PATH):
        os.remove(config.DB_PATH)

    new_instance = get_app()

    with new_instance.app_context():
        config.db.create_all()

    return new_instance
def send_mail(subject, msg_body, msg_html, dest):
    '''
    envoie un mail aux administrateurs de l'application
    '''
    app = get_app()
    msg = Message(subject, sender=app.config['MAIL_SENDER'], recipients=[dest])

    msg.body = msg_body
    msg.html = msg_html

    with app.app_context():
        mail.send(msg)
Exemple #11
0
def login():
    try:
        user_data = request.json

        try :
            user = models.AppUser.query\
                .filter(models.AppUser.identifiant==user_data['login'])\
                .one()
        except Exception as e:
            resp = Response(json.dumps({'type':'login', 'msg':'Identifiant invalide'}), status=490)
            return resp

        if not user.check_password(user_data['password']):
            resp = Response(json.dumps({'type':'password', 'msg':'Mot de passe invalide'}), status=490)
            return resp

        if not user.actif:
            print('Inactif')
            resp = Response(json.dumps({'type':'inactif', 'msg':'Compte non actif'}), status=490)
            return resp

        #Génération d'un token
        s = Serializer(get_app().config['SECRET_KEY'], expires_in = get_app().config['COOKIE_EXPIRATION'])
        token = s.dumps({'id_role':user.id_role})
        cookie_exp = datetime.datetime.now() + datetime.timedelta(seconds= get_app().config['COOKIE_EXPIRATION'])

        resp = Response(json.dumps({'user':user.as_dict(), 'token': token.decode('ascii'), 'expires':str(cookie_exp)}))

        resp.set_cookie('token', token, expires=cookie_exp)

        #Log de la session
        session = models.LogSession (id_role = user.id_role)

        db.session.add(session)
        db.session.commit()
        return resp
    except Exception as e:
        print(e)
        resp = Response(json.dumps({'login': False}), status=403)
        return resp
 def setUp(self):
     """Define test variables and initialize app."""
     self.app = get_app(load_config())
     self.client = self.app.test_client
     self.observations_post_data = {
         "cd_nom": 3582,
         "obs_txt": "Tada",
         "count": 1,
         "geometry": {
             "type": "Point",
             "coordinates": [5, 45]
         },
     }
Exemple #13
0
def pytest_sessionstart(session):
    """ before session.main() is called. """
    config_path = get_config_file_path()
    config = load_config(config_path)
    app = server.get_app(config)
    app.config['TESTING'] = True
    # push the app_context
    ctx = app.app_context()
    ctx.push()
    
    # setup test data
    execute_script('delete_sample_data.sql')
    execute_script('sample_data.sql')
Exemple #14
0
 def __init__(self):
     from server import db, get_app
     self.app = get_app()
     self.session = db.session
     self.evt = threading.Event()
     if not os.path.exists('./supervision.lock'):
         # Si le fichier de verrouillage existe
         # Aucun thread supplémentaire n'est lancé
         with open('./supervision.lock', 'w'):
             # Ecriture du fichier de verrouillage lors du démarrage
             # du process de scan
             thr = threading.Thread(target=_scan, args=[self.app, self.session, self.evt])
             thr.start()
Exemple #15
0
 def __init__(self):
     from server import db, get_app
     self.app = get_app()
     self.session = db.session
     self.evt = threading.Event()
     if not os.path.exists('./supervision.lock'):
         # Si le fichier de verrouillage existe
         # Aucun thread supplémentaire n'est lancé
         with open('./supervision.lock', 'w'):
             # Ecriture du fichier de verrouillage lors du démarrage
             # du process de scan
             thr = threading.Thread(target=_scan,
                                    args=[self.app, self.session, self.evt])
             thr.start()
Exemple #16
0
def pytest_sessionstart(session):
    """ before session.main() is called. """
    config_path = get_config_file_path()
    config = load_config(config_path)
    app = server.get_app(config)
    app.config["TESTING"] = True
    # push the app_context
    ctx = app.app_context()
    ctx.push()
    logging.disable(logging.DEBUG)

    # setup test data
    execute_script("delete_sample_data.sql")
    execute_script("sample_data.sql")
def get_pq():
    s = Serializer(get_app().config['SECRET_KEY'])
    user_id = s.loads(request.cookies['token'])

    user = userModels.AppUser.query\
        .filter(userModels.AppUser.id_role==user_id['id_role'])\
        .one()

    data = db.session.query(models.PqData)\
        .join(models.Communes, func.ST_Intersects(models.PqData.geom, models.Communes.geom))\
        .filter(models.Communes.code_insee == user.code_insee)\
        .all()

    return jsonify(FeatureCollection([liste.as_geofeature() for liste in data]))
Exemple #18
0
def get_pq():
    s = Serializer(get_app().config['SECRET_KEY'])
    user_id = s.loads(request.cookies['token'])

    user = userModels.AppUser.query\
        .filter(userModels.AppUser.id_role==user_id['id_role'])\
        .one()

    data = db.session.query(models.PqData)\
        .join(models.Communes, func.ST_Intersects(models.PqData.geom, models.Communes.geom))\
        .filter(models.Communes.code_insee == user.code_insee)\
        .all()

    return jsonify(FeatureCollection([liste.as_geofeature()
                                      for liste in data]))
Exemple #19
0
        def __check_auth(*args, **kwargs):
            print('check auth')
            try:
                s = Serializer(get_app().config['SECRET_KEY'])
                data = s.loads(request.cookies['token'])
            except SignatureExpired:
                print('expired')
                return Response('Token Expired', 403) # valid token, but expired
            except BadSignature:
                print('BadSignature')
                return Response('Token BadSignature', 403) # valid token, but expired
            except Exception as e:
                print('Exception')
                print(e)
                return Response('Forbidden', 403)

            return fn(*args, **kwargs)
Exemple #20
0
def manager_main():
    global app, db, User
    app = get_app()
    app.config['host'] = '0.0.0.0'
    manager = Manager(app)
    from flask.ext.migrate import Migrate, MigrateCommand

    bootstrap = Bootstrap(app)
    db = get_db()
    import routes
    import api

    def make_shell_context():
        return dict(app=app, db=db, User=User)

    manager.add_command("shell", Shell(make_context=make_shell_context))
    migrate = Migrate(app, db)
    manager.add_command('db', MigrateCommand)

    manager.run()
    def setUpClass(cls):
        cls.callback_called = False

        cls.digest = hashlib.sha256("").hexdigest()
        cls.headers = {'Authorization': cls.digest}
        authFile = file("test_auth","w")
        authFile.write(cls.digest)
        authFile.close()

        # Configure the app
        server.options.auth_file="test_auth"
        server.restart = cls.callback
        application = server.get_app()
        sock, port = tornado.testing.bind_unused_port()
        cls.loop = tornado.ioloop.IOLoop.instance()
        tserver = tornado.httpserver.HTTPServer(application,
                                               io_loop=cls.loop)
        tserver.add_sockets([sock])
        tserver.start()
        cls.port = port
        thread.start_new_thread(cls.loop.start,())
        cls.url = "http://localhost:{}/".format(cls.port)
Exemple #22
0
# -*- coding:utf-8 -*-
from flask import Blueprint
from server import get_app


auth = Blueprint('auth', __name__)

from . import views
from . import forms

### register must be put after import 
_app = get_app()
_app.register_blueprint(auth, url_prefix = '/auth')
Exemple #23
0
"""
    Give a unique entry point for gunicorn
"""

from geonature.utils.env import load_config, get_config_file_path
from server import get_app

# get the app config file
config_path = get_config_file_path()
config = load_config(config_path)

#give the app context from server.py in a app object
app = get_app(config)
Exemple #24
0
def main():
    app = get_app()
    import routes
    app.run(app.config['HOST'], app.config['PORT'], **app.config['OPTIONS'])
Exemple #25
0
def cli(loop, aiohttp_client):
    app = get_app()
    return loop.run_until_complete(aiohttp_client(app))
Exemple #26
0
 async def get_application(self):
     return get_app()
Exemple #27
0
def wsgi_app():
    app = get_app()
    import routes
    return app
Exemple #28
0
import logging
import threading
import server
from socket_listener.socket_listener import socket_event_listener
from poller.poller import NsePoller

sio = server.get_socket()
app = server.get_app(sio)
nse_poller = NsePoller(sio)
socket_event_listener(sio, nse_poller)

try:
    x = threading.Thread(target=nse_poller.nse_get_stock_quote, args=())
    logging.info("Main    : before running thread")
    x.start()
except:
    print('Error occured..')

if __name__ == '__main__':
    # get_stock_quote(watch_list_to_poll=watch_list_to_poll)
    # app.run(port=8000)
    print('Server started....')
    print('Listening to http://localhost:8000')
Exemple #29
0
"""
    Give a unique entry point for gunicorn
"""
import os

if "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""):
    import gevent.monkey

    gevent.monkey.patch_all()

from server import get_app  # noqa: F401
from gncitizen.utils.env import load_config, get_config_file_path  # noqa: F401

# get the app config file
config = load_config()

# give the app context from server.py in a app object
app = get_app(config)
port = app.config["API_PORT"] if app.config.get("API_PORT", False) else 5002

if __name__ == "__main__":
    app.run(
        host="0.0.0.0",
        port=port,
        extra_files=get_config_file_path(),
        processes=3,
    )
 def get_app(self):
     return server.get_app()
Exemple #31
0
def app():
    app = server.get_app(APP_CONF)
    app.config['TESTING'] = True
    return app
Exemple #32
0
def app():
    return server.get_app()
Exemple #33
0
                        help="Reset database with test data",
                        action="store_true")
    args = parser.parse_args(sys.argv[1:])
    database_path = vars(args).get("database")
    if database_path is None:
        print("Option --database not given")
        sys.exit(1)

    if vars(args).get("reset_with_testdata"):
        try:
            os.remove(database_path)
        except FileNotFoundError:
            pass

    port_str = vars(args).get("port")
    if port_str is None:
        print("Option --port not given")
        sys.exit(1)
    port = int(port_str)

    server = server.Server(database_path)

    if vars(args).get("reset_with_testdata"):
        util.setup_test_data(server.database)

    app = server.get_app()
    app.listen(port)

    loop = tornado.ioloop.IOLoop.current()
    loop.start()
Exemple #34
0
 def get_app(self):
     return server.get_app()
Exemple #35
0
def client():
    return server.get_app().test_client()
Exemple #36
0
from server import get_app, config


if __name__ == '__main__':
    with get_app().app_context():
        config.db.create_all()
Exemple #37
0
 def create_app(self):
     app = get_app()
     app.config['TESTING'] = True
     return app
Exemple #38
0
import json
import datetime
import atexit

from flask import Blueprint, request
from server import db as _db, get_app
from core.utils import json_resp, register_module
from core.utils.serialize import ValidationError
from .models import Equipement, EquipementSerializer

routes = Blueprint('superv', __name__)

register_module('/supervision', routes)

app = get_app()

if app.config.get('ENABLE_SUPERVISION', False):
    from .tools import Scanner, shutdown_fn
    scan = Scanner()

    atexit.register(shutdown_fn, scan)


@routes.route('/')
@json_resp
def sup_index():
    fields = ['id', 'ip_addr', 'label', 'equip_type', 'last_up', 'status']
    conn = _db.engine.connect()
    results = conn.execute('select %s from sup_equipement' % ', '.join(fields))
    out = []
    for item in results:
Exemple #39
0
def app():
    config_path = get_config_file_path()
    config = load_config(config_path)
    app = server.get_app(config)
    app.config['TESTING'] = True
    return app