Exemplo n.º 1
0
def init_app(app):
    # Allow specific origins
    origins = os.environ.get('CORS_ORIGINS', '*')

    cors = CORS(origins=origins)
    cors.init_app(app)
    return cors
Exemplo n.º 2
0
 def __init__(self, app=None):
     if app is not None:
         if app.config["DEBUG"]:
             self.cors = CORS()
         self.init_app(app)
Exemplo n.º 3
0
class OneLove(object):
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    api = None
    app = None
    blueprint = None
    collect = Collect()
    db = MongoEngine()
    jwt = JWT()
    mail = Mail()
    security = Security()
    socketio = None
    toolbar = None
    user_datastore = None

    def __init__(self, app=None):
        if app is not None:
            if app.config["DEBUG"]:
                self.cors = CORS()
            self.init_app(app)

    def init_app(self, app):
        global current_app
        current_app = self
        self.app = app
        if app.config["DEBUG"]:
            self.cors.init_app(self.app, resources={r"/api/*": {"origins": "*"}})

        from api import api_v0, api

        self.api = api

        self.blueprint = Blueprint(
            "onelove", __name__, template_folder="templates", static_folder="static", static_url_path="/static/onelove"
        )
        self.app.register_blueprint(self.blueprint)

        self.app.register_blueprint(api_v0, url_prefix="/api/v0")
        self.app.register_blueprint(apidoc.apidoc)

        self.mail.init_app(self.app)

        self.db.init_app(self.app)

        self.user_datastore = MongoEngineUserDatastore(self.db, User, Role)
        self.security.init_app(self.app, self.user_datastore)

        self.jwt.init_app(self.app)
        self.collect.init_app(self.app)

        if self.app.config.get("DEBUG_TB_PANELS", False):
            from flask_debugtoolbar import DebugToolbarExtension
            from flask_debug_api import DebugAPIExtension

            self.toolbar = DebugToolbarExtension(self.app)
            self.toolbar = DebugAPIExtension(self.app)

        self.socketio = SocketIO(self.app, logger=True)
        self.app.onelove = self

    @jwt.authentication_handler
    def authenticate(username, password):
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            return None
        result = OneLove.Result(id=str(user.id), email=user.email, first_name=user.first_name, last_name=user.last_name)
        if verify_password(password, user.password):
            return result

    @jwt.identity_handler
    def identity(payload):
        try:
            user = User.objects.get(id=payload["identity"])
        except User.DoesNotExist:
            user = None
        return user
Exemplo n.º 4
0
def make_app():
    cors = CORS(origins=[
        'https://app.communityshare.us:443', # production app
        'http://communityshare.localhost:5000', # local dev angular app
        'http://communityshare.localhost:8000', # local dev elm app
        'https://dmsnell.github.io/cs-elm/', # live elm app
    ])
    compress = Compress()
    webpack = Webpack()
    app = Flask(__name__, template_folder='../static/')
    app.response_class = JsonifyDictResponse

    app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_CONNECTION
    app.config['WEBPACK_ASSETS_URL'] = config.WEBPACK_ASSETS_URL
    app.config['WEBPACK_MANIFEST_PATH'] = config.WEBPACK_MANIFEST_PATH

    cors.init_app(app)
    compress.init_app(app)
    webpack.init_app(app)

    if config.SSL != 'NO_SSL':
        flask_sslify.SSLify(app)
        app.wsgi_app = ReverseProxied(app.wsgi_app)

    register_user_routes(app)
    register_search_routes(app)
    register_conversation_routes(app)
    register_share_routes(app)
    register_survey_routes(app)
    register_email_routes(app)
    register_statistics_routes(app)

    community_share.api.register_routes(app)

    @app.teardown_appcontext
    def close_db_connection(exception):
        store.session.remove()

    @app.errorhandler(BadRequest)
    def handle_bad_request(error):
        return str(error), HTTPStatus.BAD_REQUEST

    app.errorhandler(Unauthorized)(jsonify_with_code(HTTPStatus.UNAUTHORIZED))
    app.errorhandler(Forbidden)(jsonify_with_code(HTTPStatus.FORBIDDEN))
    app.errorhandler(NotFound)(jsonify_with_code(HTTPStatus.NOT_FOUND))
    app.errorhandler(InternalServerError)(jsonify_with_code(HTTPStatus.INTERNAL_SERVER_ERROR))

    @app.route('/static/build/<path:filename>')
    def build_static(filename):
        return send_from_directory(
            app.root_path + '/../static/build/',
            filename,
            cache_timeout=YEAR_IN_SECONDS,
        )

    @app.route('/static/js/<path:filename>')
    def js_static(filename):
        return send_from_directory(app.root_path + '/../static/js/', filename)

    @app.route('/static/fonts/<path:filename>')
    def fonts_static(filename):
        return send_from_directory(app.root_path + '/../static/fonts/', filename)

    @app.route('/static/css/<path:filename>')
    def css_static(filename):
        return send_from_directory(app.root_path + '/../static/css/', filename)

    @app.route('/static/templates/footer.html')
    def footer_template():
        return render_template('templates/footer.html', config=config)

    @app.route('/static/templates/<path:filename>')
    def templates_static(filename):
        return send_from_directory(app.root_path + '/../static/templates/', filename)

    @app.route('/')
    def index():
        logger.debug('rendering index')
        return render_template('index.html', config=config)

    return app
Exemplo n.º 5
0
def register_extensions(app):
    """Register extensions."""

    cors = CORS()
    cors.init_app(app)
from flask_restful import Resource, Api
from resources.csv import CSVResource
from resources.imo import IMOResource
from resources.position import PositionResource
from resources.ship import ShipResource
from utils.logger import log
from flask_cors import CORS
import os
import sys

# app = Flask(__name__)
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.secret_key = "dlka34j90(&83nan341!#3d"

api = Api(app)
cors = CORS(app, resources={r"*": {"origins": "*"}})

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

class health(Resource):
    def get(self):
        # return "Hello World!", 200, {'Access-Control-Allow-Origin': '*'}
        return "Hello World!", 200


Exemplo n.º 7
0
from flask import jsonify
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from werkzeug.wsgi import DispatcherMiddleware
from utils.errors import InvalidType, ApiError
from utils.api import JSONFlask, CustomJSONEncoder

app = JSONFlask(__name__)
app.debug = True
app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=8)
app.config['APPLICATION_ROOT'] = '/api'
app.json_encoder = CustomJSONEncoder
app.url_map.strict_slashes = False
jwt = JWTManager(app)
CORS(app)


def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'application/json')])
    import json
    return json.dumps({'message': 'ok'})


app.wsgi_app = DispatcherMiddleware(simple, {'/api': app.wsgi_app})


# Create a function that will be called whenever create_access_token
# is used. It will take whatever object is passed into the
# create_access_token method, and lets us define what custom claims
# should be added to the access token.
Exemplo n.º 8
0
app.config['MAIL_SERVER'] = config.mail_host.split(":")[0]
app.config['MAIL_PORT'] = int(config.mail_host.split(":")[1])
app.config['MAIL_USERNAME'] = config.mail_user
app.config['MAIL_PASSWORD'] = config.mail_pass
app.config['MAIL_DEFAULT_SENDER'] = config.mail_from
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)

# Setup Storage
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Setup CORS
cors = CORS(app, resources={r".*/api/v1/.*": {"origins": "*"}})

# Logging
log_handler_mail = SMTPHandler(config.mail_host.split(":"),
                               config.mail_from,
                               config.admins,
                               '[faucet] Error',
                               (config.mail_user,
                                config.mail_pass))
log_handler_mail.setFormatter(logging.Formatter(
    "Message type:       %(levelname)s\n" +
    "Location:           %(pathname)s:%(lineno)d\n" +
    "Module:             %(module)s\n" +
    "Function:           %(funcName)s\n" +
    "Time:               %(asctime)s\n" +
    "\n" +
Exemplo n.º 9
0
from logging.handlers import SMTPHandler, RotatingFileHandler
import logging
import os
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_babel import Babel, lazy_gettext as _l
from config import Config
from flask_cors import CORS

db = SQLAlchemy()
migrate = Migrate()
mail = Mail()
babel = Babel()
cors = CORS()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    cors.init_app(app, resources={r"*": {"origins": "*"}})

    # app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) if app.config['ELASTICSEARCH_URL'] else None

    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api')
Exemplo n.º 10
0
Arquivo: admin.py Projeto: Zunaib/seek
from flask import Flask, Blueprint, jsonify, request, json
from flask_pymongo import PyMongo, pymongo
from flask_cors import CORS
from bson.objectid import ObjectId

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "theseek"
app.config["MONGO_URI"] = 'mongodb://*****:*****@adminroutes.route("/deleterequest", methods=['POST'])
def deleterequest():
    admrequest = mongo.db.adminrequest
    requestid = request.get_json()['requestid']
    admrequest_exist = admrequest.find_one({"_id": ObjectId(requestid)})
    result = ""
    if admrequest_exist:
        response = admrequest.delete_one({"_id": ObjectId(requestid)})
        if response:
            result = jsonify({"success": "Admin Request Deleted"})
            return result
        else:
            result = jsonify({"error": "Error Occured"})
Exemplo n.º 11
0
def instantiate_app_with_views(context, app_path_prefix):
    app = Flask(
        "dagster-ui",
        static_url_path=app_path_prefix,
        static_folder=os.path.join(os.path.dirname(__file__), "./webapp/build"),
    )
    schema = create_schema()
    subscription_server = DagsterSubscriptionServer(schema=schema)

    # Websocket routes
    sockets = Sockets(app)
    sockets.add_url_rule(
        "{}/graphql".format(app_path_prefix),
        "graphql",
        dagster_graphql_subscription_view(subscription_server, context),
    )

    # HTTP routes
    bp = Blueprint("routes", __name__, url_prefix=app_path_prefix)
    bp.add_url_rule(
        "/graphiql", "graphiql", lambda: redirect("{}/graphql".format(app_path_prefix), 301)
    )
    bp.add_url_rule(
        "/graphql",
        "graphql",
        DagsterGraphQLView.as_view(
            "graphql",
            schema=schema,
            graphiql=True,
            graphiql_template=PLAYGROUND_TEMPLATE.replace("APP_PATH_PREFIX", app_path_prefix),
            executor=Executor(),
            context=context,
        ),
    )

    bp.add_url_rule(
        # should match the `build_local_download_url`
        "/download/<string:run_id>/<string:step_key>/<string:file_type>",
        "download_view",
        download_log_view(context),
    )

    bp.add_url_rule(
        "/download_debug/<string:run_id>", "download_dump_view", download_dump_view(context),
    )

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    bp.add_url_rule("/dagit/notebook", "notebook", lambda: notebook_view(request.args))
    bp.add_url_rule("/dagit_info", "sanity_view", info_view)

    index_path = os.path.join(os.path.dirname(__file__), "./webapp/build/index.html")

    def index_view(_path):
        try:
            with open(index_path) as f:
                return (
                    f.read()
                    .replace('href="/', 'href="{}/'.format(app_path_prefix))
                    .replace('src="/', 'src="{}/'.format(app_path_prefix))
                    .replace(
                        '<meta name="dagit-path-prefix"',
                        '<meta name="dagit-path-prefix" content="{}"'.format(app_path_prefix),
                    )
                )
        except seven.FileNotFoundError:
            raise Exception(
                """Can't find webapp files. Probably webapp isn't built. If you are using
                dagit, then probably it's a corrupted installation or a bug. However, if you are
                developing dagit locally, your problem can be fixed as follows:

                cd ./python_modules/
                make rebuild_dagit"""
            )

    app.app_protocol = lambda environ_path_info: "graphql-ws"
    app.register_blueprint(bp)
    app.register_error_handler(404, index_view)

    # if the user asked for a path prefix, handle the naked domain just in case they are not
    # filtering inbound traffic elsewhere and redirect to the path prefix.
    if app_path_prefix:
        app.add_url_rule("/", "force-path-prefix", lambda: redirect(app_path_prefix, 301))

    CORS(app)
    return app
Exemplo n.º 12
0
from flask_restful import Api, Resource, reqparse

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
api = Api(app)

images = {
        "character": "",
        "imageData": "kot2"
    }


# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

@app.route('/asl', methods=['GET','PUT'])
def get_image():
    res = {'status':'success'}
    if request.method=='GET':
        res['images'] = images
    if request.method=='PUT':
        data = request.get_data()
        res['images'] = data
    return jsonify(res)

if __name__ == '__main__':
    app.run()