Exemplo n.º 1
0
def create_app():
    app = Flask(__name__,
                instance_relative_config=True,
                static_folder='static')
    cred = credentials.Certificate(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config',
                     'ServiceAccountkey.json'))
    app.config['BASE_DIR'] = os.path.dirname(os.path.abspath(__file__))
    if not config.DEBUG:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ[
            'SQLALCHEMY_DATABASE_URI']
    elif config.ENV == 'LOCAL':
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % config.POSTGRES
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    init_dimen()

    with app.app_context():
        db.init_app(app)
        db.create_all()
        settings = Settings.init_setup()
        firebase_admin.initialize_app(
            cred, {
                'storageBucket': settings.firebaseStorageBucket,
                'databaseURL': settings.firebaseDatabaseURL
            })
    app.config['SECRET_KEY'] = settings.secretKey
    if Settings.environment[settings.appEnvironment] == 'Development':
        app.config['DEBUG'] = True
    else:
        app.config['DEBUG'] = False
    app.config["POSTS_PER_PAGE"] = config.POSTS_PER_PAGE
    CORS(app, resources={r"*": {"origins": "*"}})

    return app
Exemplo n.º 2
0
def create_app(address, **kwargs):
    app = Flask(__name__)

    db_path = os.path.expanduser(kwargs['data_folder'] + '/calsotchat.sqlite')
    logging.info(f'DB file -> sqlite:///{db_path}')
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    cors = CORS(app, resources={r"/api*": {"origins": "*"}})

    db.init_app(app)

    with app.app_context():
        db.create_all()

        # Check if current user is created in db, otherwise create it
        my_contact = Contact.query.filter_by(address=address).first()
        if not my_contact:
            my_contact = Contact(nickname="", address=address, online=True)
            my_contact.save()
            logging.info("Local user created")
            myself = Myself(address=address, )
            myself.save()

        return app
Exemplo n.º 3
0
def create_app():
    # Create Flask Application
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

    #Database set up stuff
    from backend.db import db
    from backend.models import Request, Edge
    db.app = app
    db.init_app(app)
    db.create_all()

    #Using apimanager for some blueprints
    from backend.api import apimanager
    apimanager.init_app(app, flask_sqlalchemy_db=db)

    #Turn on CORS permissively for now
    CORS(app)

    @app.route('/')
    def hello():
        return "Hello dank wizard"

    return app
Exemplo n.º 4
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)

    # app.config.from_pyfile('config.py')

    app.config['SECRET_KEY'] = 'dev'
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['MONGODB_SETTINGS'] = {
        'db': 'mozy',
        'host': 'db',
        'username': '******',
        'password': '******',
        'authentication_source': 'mozy'
    }
    app.config['SECURITY_PASSWORD_SALT'] = 'dev'
    app.config['SECURITY_REGISTERABLE'] = 'dev'

    db.init_app(app)
    auth = Auth(app)

    if not os.path.isdir(app.instance_path):
        os.makedirs(app.instance_path)

    with app.app_context():
        default = {'email': '*****@*****.**', 'password': '******'}
        if not User.lookup("*****@*****.**"):
            User(email=default['email'],
                 password=auth.guard.encrypt_password(
                     default['password'])).save()

    #@flask_praetorian.roles_required('user')
    @app.route('/route', methods=['POST'])
    def post_route():
        req = flask.request.get_json()
        start = req.get('start')
        end = req.get('end')
        t = Trip(start=[int(start['lon']),
                        int(start['lat'])],
                 end=[int(end['lon']), int(end['lat'])])
        t.save()
        print(end)
        return ""

    @app.route('/route', methods=['GET'])
    def get_route():
        ret = {'type': "FeatureCollection", 'features': []}
        for trip in Trip.objects:
            ts = {
                "properties": {},
                "type": "Feature",
                "geometry": trip['start']
            }
            ret['features'].append(ts)

        return flask.jsonify(ret)

    @app.route('/login', methods=['POST'])
    def login():
        """
        Logs a user in by parsing a POST request containing user credentials and
        issuing a JWT token.
        {
          "username": "******",
          "password": "******"
        }
        """
        req = flask.request.get_json(force=True)
        username = req.get('username', None)
        password = req.get('password', None)
        user = auth.guard.authenticate(username, password)
        ret = {
            'access_token': auth.guard.encode_jwt_token(user),
            'status_code': 200
        }
        return (flask.jsonify(ret), 200)

    @app.route('/register', methods=['POST'])
    def register():
        """
        Registers a user from post request
        {
          "username": "******",
          "password": "******"
        }
        """
        req = flask.request.get_json(force=True)
        username = req.get('username', None)
        password = req.get('password', None)

        success, data = auth.register(username, password)

        if not success:
            return (flask.jsonify({'message': data, 'status_code': 409}), 409)

        user = auth.guard.authenticate(username, password)
        ret = {
            'access_token': auth.guard.encode_jwt_token(user),
            'status_code': 200
        }
        return (flask.jsonify(ret), 200)

    @app.after_request
    def after_request_cors(resp):
        resp.headers.set('Access-Control-Allow-Origin', "*")
        resp.headers.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        resp.headers.set('Access-Control-Allow-Headers', 'Content-Type')
        return resp

    return app

class BackgroundTaskMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request,
                       call_next: RequestResponseEndpoint) -> Response:
        request.state.background = None
        response = await call_next(request)
        if request.state.background:
            response.background = request.state.background
        return response


middleware = [Middleware(BackgroundTaskMiddleware)]

app = Starlette(debug=True, middleware=middleware)
gino_db.init_app(app)

# load_modules(app)
app.mount("/graphql",
          GraphQL(schema, debug=True, extensions=[ApolloTracingExtension]))

# For debugging
if __name__ == "__main__":
    uvicorn.run(app, host='0.0.0.0', port=8000)

# TODO: Auth
# https://spectrum.chat/ariadne/general/how-to-implement-a-very-simple-auth-layer~80b7d221-6d0c-4df8-800a-e4cc6a07c99d
# Session middlewere

# TODO: CORS middleware and more
Exemplo n.º 6
0
from flask_restful import Api

# Patch PYTHONPATH
from sys import path
path.append(".")

from backend import config
from backend.db import db
from backend.create_db import create_db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_URI
app.config[
    'SQLALCHEMY_TRACK_MODIFICATIONS'] = config.SQLALCHEMY_TRACK_MODIFICATIONS

db.init_app(app=app)

blueprint = Blueprint('api', __name__)
api = Api(blueprint)

from backend.session.view import UserRootAPI, UserAPI, LoginAPI
api.add_resource(LoginAPI, "/login")
api.add_resource(UserRootAPI, "/user")
api.add_resource(UserAPI, "/user/<string:id>")

from backend.customer.view import CustomerRootAPI, CustomerAPI, CustomerOrdersAPI
api.add_resource(CustomerRootAPI, "/customer")
api.add_resource(CustomerAPI, "/customer/<string:id>")
api.add_resource(CustomerOrdersAPI, "/customer/<string:id>/orders")

from backend.employee.view import EmployeeRootAPI, EmployeeAPI, EmployeeOrdersAPI
Exemplo n.º 7
0
from flask import Flask
from flask_cors import CORS

from backend.__config__ import BaseConfig
from backend.db import db
from backend.service import auth_service, user_service, spbu_service
from backend.service.util.json_encoder import ModelEncoder

application = Flask(__name__)
CORS(
    application,
    supports_credentials=True,
)

application.config.from_object(BaseConfig)
application.app_context().push()
application.json_encoder = ModelEncoder

db.init_app(application)

# if not database_exists(BaseConfig.SQLALCHEMY_DATABASE_URI):
# db.create_all()
# initialize_database()

application.register_blueprint(auth_service.auth, url_prefix='/auth')
application.register_blueprint(user_service.user, url_prefix='/user')
application.register_blueprint(spbu_service.spbu, url_prefix='/spbu')

application.run(debug=True)