예제 #1
0
import os
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from application.security import authenticate, identity
from application.resources.user import UserRegister
from application.resources.location import Location, LocationList
from application.resources.course import Course, CourseList
from application.db import db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL_NEW', 'sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'test'
api = Api(app)

jwt = JWT(app, authenticate, identity)  # /auth

api.add_resource(Location, '/location/<string:name>')
api.add_resource(LocationList, '/locations')
api.add_resource(Course, '/course')
api.add_resource(CourseList, '/courses')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    db.init_app(app)
    app.run(port=5000, debug=True)
예제 #2
0
def init_app(database, print_db_echo):

    #importtaa oracle tarvittaessa
    if database == "oracle":
        import cx_Oracle  #siirretty oracle importit tänne, koska pytest ei tykkää niistä tuolla ylhäällä
        import application.oracleConfig

    #määritä app
    app = Flask(__name__, static_folder='../build', static_url_path='/')
    cors = CORS(app)

    #kirjautuminen
    app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=30)
    app.config["SESSION_REFRESH_EACH_REQUEST"] = True
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    login_manager = LoginManager()
    login_manager.init_app(app)
    app.config["SECRET_KEY"] = urandom(32)
    if database == "oracle":
        app.config['LOGIN_DISABLED'] = False
    else:
        app.config['LOGIN_DISABLED'] = True

    @login_manager.user_loader
    def load_user(account_id):
        return Account.query.get(account_id)

    #määrittele tietokantayhteys
    if database == "oracle":
        dnsStr = cx_Oracle.makedsn('oracle.luomus.fi',
                                   1521,
                                   service_name='oracle.luomus.fi')
        dnsStr = dnsStr.replace('SID', 'SERVICE_TYPE')
        try:
            app.config[
                "SQLALCHEMY_DATABASE_URI"] = "oracle://" + oracleConfig.username + ":" + oracleConfig.password + "@" + dnsStr
            app.config["SQLALCHEMY_ECHO"] = print_db_echo
            print('Tietokantayhteys luotu.')
        except Exception as e:
            print(e)
    else:
        try:
            app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///:memory:'
            app.config["SQLALCHEMY_ECHO"] = print_db_echo
            print('Testitietokantayhteys luotu.')
        except Exception as e:
            print(e)

    #Tietokannan luonti
    app.register_blueprint(api_blueprint)
    db.init_app(
        app
    )  #db siirretty omaksi luokaksi, että se näkyy kaikille, jostain syystä init_app() systeemillä tehtäessä se ei näy. kaikkiin models.py tiedostoihin from application.db import db

    with app.app_context(
    ):  #appioliota käyttäen luodaan tietokantataulut, tämä googlesta
        try:
            #Määritellään tyhjennetäänkö tietokanta sovelluksen alussa
            if database == "oracle":
                #db.reflect()
                #db.drop_all()
                db.create_all()
            else:
                db.reflect()
                db.drop_all()
                db.create_all()
            print('Taulut luotu')

            #Lisätään tiedot tiedostosta
            SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
            filename = os.path.join(SITE_ROOT, '', 'locations.json')
            with open(filename) as json_file:
                data = json.load(json_file)
                for o in data["observatories"]:
                    createObservatory(o['observatory'], "actiontest")
                    obsId = getObservatoryId(o['observatory'])
                    for l in o["locations"]:
                        createLocation(l, obsId)
                    for t in o["types"]:
                        createType(t, obsId)

            print('Lintuasema luotu')

        except Exception as e:
            print(e)

    return app
예제 #3
0
파일: __init__.py 프로젝트: cpwr/PromTal
def create_app(config_name):
    app = Flask(__name__, template_folder=templates_dir, static_folder=static_folder)
    app.config.from_object(config[config_name])
    app.wsgi_app = AuthMiddleware(app.wsgi_app)

    Bootstrap(app)
    db.init_app(app)
    redis.init_app(app)
    ldap.init_app(app)
    sms_service.init_app(app)
    celery.init_app(app)

    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

    from application import models

    for _module in Module.get_all():
        app.register_blueprint(_module)

    # for rule in app.url_map.iter_rules():
    #     print(rule, rule.methods)

    @app.template_filter('datetime')
    def format_datetime(value, time=True, old_time=True, check_year=True):
        _date = value
        if isinstance(value, datetime):
            _date = value.date()

        time_str = "в %s" % value.strftime('%H:%M')
        date_str = ''

        today = date.today()
        if not check_year:
            _date = _date.replace(year=today.year)

        if _date == today:
            date_str = "Сегодня"
        elif _date == today - timedelta(1):
            date_str = "Вчера"
        elif _date == today + timedelta(1):
            date_str = "Завтра"
        else:
            date_str = value.strftime('%d.%m.%y')
            time = time if old_time else False

        date_str = ' '.join((date_str, time_str)) if time else date_str
        return date_str

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(403)
    def forbidden(e):
        return render_template('403.html'), 403

    @app.context_processor
    def inject_variables():
        return {
            'current_user': get_user(),
            'widget': widget.get
        }

    return app