Пример #1
0
from flask import Flask
from flask_admin import Admin
from flask_cors import CORS
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), "../", "../")))

from portfolio_backend.application.settings import BackendSettings

backend_application = Flask(
    import_name=__name__,
    template_folder=f"{BackendSettings.BASE_DIR}/templates/"
)

backend_application.config.from_object(BackendSettings)
CORS(backend_application)

db = SQLAlchemy(backend_application)
migrate = Migrate(backend_application, db)
ma = Marshmallow(backend_application)
admin = Admin(backend_application, name="portfolio", template_mode="bootstrap3")

from portfolio_backend import admin  # noqa
from portfolio_backend import models  # noqa
from portfolio_backend import routes  # noqa
from portfolio_backend import schemas  # noqa
# fmt: on
Пример #2
0
# Import standard library modules
import re

# Import installed packages
from flask_cors import CORS

# Import app code
from app.main import app
from app.core import config

# Anything from SERVER_NAME
use_domain = config.SERVER_NAME.replace(".", r"\.")
cors_origins_regex = re.compile(r"^(https?:\/\/(?:.+\.)?(" + use_domain +
                                r")(?::\d{1,5})?)$")
CORS(app, origins=cors_origins_regex, supports_credentials=True)
Пример #3
0
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/getMsg": {"origins": "*"}})

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/getMsg', methods=['GET', 'POST'])
def home():
    response = request.json
    print(response)
    return jsonify(response)
    # return response

# 启动运行
if __name__ == '__main__':
    app.run()   # 这样子会直接运行在本地服务器,也即是 localhost:5000
   # app.run(host='your_ip_address') # 这里可通过 host 指定在公网IP上运行
Пример #4
0
app.config["ADMIN_PASSWORD"] = os.getenv("ADMIN_PASSWORD", "admin-password")
app.config["PERMITTED_SOURCE_IP_RANGES"] = os.getenv(
    "PERMITTED_SOURCE_IP_RANGES", "")
app.config["CORS_PERMITTED_ORIGINS"] = os.getenv("CORS_PERMITTED_ORIGINS", "*")
app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET_KEY", "super-secret")
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 3 * 3600  # 3 hours
app.config["JWT_IDENTITY_CLAIM"] = "sub"
app.config["RESTPLUS_MASK_SWAGGER"] = False
app.config["SWAGGER_UI_REQUEST_DURATION"] = True
app.config["SWAGGER_UI_DOC_EXPANSION"] = "list"
app.config["SWAGGER_UI_JSONEDITOR"] = True

api.init_app(app)
db.init_app(app)
jwt.init_app(app)
jwt._set_error_handler_callbacks(api)
marshmallow.init_app(app)
CORS(app, origins=app.config["CORS_PERMITTED_ORIGINS"])

with db.database:
    db.database.create_tables([
        AuditTable, ContactTable, ScanTable, TaskTable, VulnTable, ResultTable
    ])


@app.after_request
def add_header(response):
    response.headers[
        "Cache-Control"] = "private, no-store, no-cache, must-revalidate"
    return response
Пример #5
0
from flask import Flask, jsonify, request
from flask_cors import CORS
import uuid

# configuration
DEBUG = True

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

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

BOOKS = [{
    'id': uuid.uuid4().hex,
    'title': 'On the Road',
    'author': 'Jack Kerouac',
    'read': True
}, {
    'id': uuid.uuid4().hex,
    'title': 'Harry Potter and the Philosopher\'s Stone',
    'author': 'J. K. Rowling',
    'read': False
}, {
    'id': uuid.uuid4().hex,
    'title': 'Green Eggs and Ham',
    'author': 'Dr. Seuss',
    'read': True
}]
Пример #6
0
def create_app(test_config=None):

    # create and configure the app
    app = Flask(__name__)
    setup_db(app)

    CORS(app)

    @app.route('/')
    def index():

        return "Welcome to Musicakes!"

    @app.route('/artists', methods=['GET'])
    def get_artists():

        try:

            all_artists = Artist.query.all()

            formatted_all_artists = [artist.short() for artist in all_artists]

            return jsonify({
                'success': True,
                'artists': formatted_all_artists
            })

        except:

            abort(404)

    @app.route('/releases', methods=['GET'])
    def get_releases():

        try:

            all_releases = Release.query.all()

            formatted_all_releases = [release.short()
                                      for release in all_releases]

            return jsonify({
                'success': True,
                'releases': formatted_all_releases
            })

        except:

            abort(404)

    @app.route('/tracks', methods=['GET'])
    def get_tracks():

        try:

            all_tracks = Track.query.all()

            formatted_all_tracks = [track.short() for track in all_tracks]

            return jsonify({
                'success': True,
                'tracks': formatted_all_tracks
            })

        except:

            abort(404)

    @app.route('/artists', methods=['POST'])
    @requires_auth('create:artist')
    def create_artist(payload):

        try:

            name = request.get_json()['name']
            country = request.get_json()['country']

            new_artist = Artist(
                name=name,
                country=country
            )

            new_artist.insert()

            return jsonify({
                'success': True,
                'name': new_artist.name,
                'country': new_artist.country
            })

        except:

            abort(422)

    @app.route('/releases', methods=['POST'])
    @requires_auth('create:release')
    def create_release(payload):

        try:

            name = request.get_json()['name']
            artist_id = request.get_json()['artist_id']
            price = request.get_json()['price']

            new_release = Release(
                name=name,
                artist_id=artist_id,
                price=price
            )

            new_release.insert()

            return jsonify({
                'success': True,
                'name': new_release.name,
                'artist_id': new_release.artist_id,
                'price': new_release.price
            })

        except:

            abort(422)

    @app.route('/tracks', methods=['POST'])
    @requires_auth('create:track')
    def create_track(payload):

        try:

            name = request.get_json()['name']
            artist_id = request.get_json()['artist_id']
            release_id = request.get_json()['release_id']
            price = request.get_json()['price']

            new_track = Track(
                name=name,
                artist_id=artist_id,
                release_id=release_id,
                price=price
            )

            new_track.insert()

            return jsonify({
                'success': True,
                'name': new_track.name,
                'artist_id': new_track.artist_id,
                'release_id': new_track.release_id,
                'price': new_track.price
            })

        except:

            abort(422)

    @app.route('/artists/<int:id>', methods=['PATCH'])
    @requires_auth('update:artist')
    def update_artist(payload, id):

        try:

            current_artist = Artist.query.get(id)

            if current_artist is None:

                abort(404)

            if 'name' in request.get_json():
                name = request.get_json()['name']
                current_artist.name = name

            if 'country' in request.get_json():
                country = request.get_json()['country']
                current_artist.country = country

            current_artist.update()

            return jsonify({
                'success': True,
                'name': current_artist.name,
                'country': current_artist.country
            })

        except:

            abort(400)

    @app.route('/releases/<int:id>', methods=['PATCH'])
    @requires_auth('update:release')
    def update_release(payload, id):

        try:

            current_release = Release.query.get(id)

            if current_release is None:

                abort(404)

            if 'name' in request.get_json():
                name = request.get_json()['name']
                current_release.name = name

            if 'artist_id' in request.get_json():
                artist_id = request.get_json()['artist_id']
                current_release.artist_id = artist_id

            if 'price' in request.get_json():
                price = request.get_json()['price']
                current_release.price = price

            current_release.update()

            return jsonify({
                'success': True,
                'name': current_release.name,
                'artist_id': current_release.artist_id,
                'price': current_release.price
            })

        except:

            abort(400)

    @app.route('/tracks/<int:id>', methods=['PATCH'])
    @requires_auth('update:track')
    def update_track(payload, id):

        try:

            current_track = Track.query.get(id)

            if current_track is None:

                abort(404)

            if 'name' in request.get_json():
                name = request.get_json()['name']
                current_track.name = name

            if 'artist_id' in request.get_json():
                artist_id = request.get_json()['artist_id']
                current_track.artist_id = artist_id

            if 'release_id' in request.get_json():
                release_id = request.get_json()['release_id']
                current_track.release_id = release_id

            if 'price' in request.get_json():
                price = request.get_json()['price']
                current_track.price = price

            current_track.update()

            return jsonify({
                'success': True,
                'name': current_track.name,
                'artist_id': current_track.artist_id,
                'release_id': current_track.release_id,
                'price': current_track.price
            })

        except:

            abort(400)

    @app.route('/artists/<int:id>', methods=['DELETE'])
    @requires_auth('delete:artist')
    def delete_artist(payload, id):

        try:

            artist = Artist.query.get(id)

            if artist is None:

                abort(404)

            artist.delete()

            return jsonify({
                'success': True
            })

        except Exception as e:
            print(e)

            abort(422)

    @app.route('/releases/<int:id>', methods=['DELETE'])
    @requires_auth('delete:release')
    def delete_release(payload, id):

        try:

            release = Release.query.get(id)

            if release is None:

                abort(404)

            release.delete()

            return jsonify({
                'success': True
            })

        except:

            abort(422)

    @app.route('/tracks/<int:id>', methods=['DELETE'])
    @requires_auth('delete:track')
    def delete_track(payload, id):

        try:

            track = Track.query.get(id)

            if track is None:

                abort(404)

            track.delete()

            return jsonify({
                'success': True
            })

        except:

            abort(422)

    """
        Errors handling
    """

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            'success': False,
            'error': 400,
            'message': 'bad request'
        }), 400

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'success': False,
            'error': 404,
            'message': 'resource not found'
        }), 404

    @app.errorhandler(405)
    def method_not_allowed(error):
        return jsonify({
            'success': False,
            'error': 405,
            'message': 'method not allowed'
        }), 405

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            'success': False,
            'error': 422,
            'message': 'unprocessable'
        }), 422

    @app.errorhandler(500)
    def internal_server_error(error):
        return jsonify({
            'success': False,
            'error': 500,
            'message': 'internal server error'
        }), 500

    @app.errorhandler(AuthError)
    def auth_error(AuthError):
        return jsonify({
            'success': False,
            'error': AuthError.status_code,
            'message': AuthError.error['description']
        }), 401

    return app
Пример #7
0
    length = 102400

    if byte1 < file_size:
        start = byte1
    if byte2:
        length = byte2 + 1 - byte1
    else:
        length = file_size - start

    with open(full_path, 'rb') as f:
        f.seek(start)
        chunk = f.read(length)
    return chunk, start, length, file_size


CORS(server)


@server.route('/download_video', methods=('GET', 'POST'))
def download():
    if request.method == 'POST':
        url = request.args['url']
        print(url)
        db = get_db()
        if not is_video_exists(url):
            video_path = download_video(url)
            print(video_path, url)
            db.execute('INSERT INTO video (url, file_path) VALUES (?, ?) ',
                       (url, video_path))
            db.commit()
            return "download successfully"
Пример #8
0
    print("Cannot load RPi.GPIO")

try:
    from wireless import Wireless
    wireless = Wireless()
except:
    print("Cannot load wireless")

try:
    import alsaaudio
    mixer = alsaaudio.Mixer("Headphone")
except:
    print("Cannot load alsaaudio")

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

# Setup -------------------------------

def loadData():
    try:
        with open('config.json', encoding='utf-8') as json_file:
            return json.load(json_file)
    except:
        print("Cannot load config file")
        return

data = loadData()

OHP_PORT = data["server"]["port"]
OHP_DEBUG = data["server"]["debug"]
Пример #9
0
import os
import json

from flask import Blueprint, jsonify, request
from flask_cors import CORS

from data_management.db import getDb
from data_management.get import getVideo
from data_management.streams import rebootStream
from data_management.tempFileManger import moveFiles

bp = Blueprint('save', __name__, url_prefix='/save')

CORS(bp)


@bp.route('/settings', methods=(['POST']))
def settings():
    """updates the settings in both the file and backend"""
    data = request.json

    wheelRadius = data['wheelRad']
    mainCam = data['mainCamFPS']
    secondaryCam = data['backCamFPS']

    if 'WHEEL_RADIUS' not in os.environ:
        os.environ['WHEEL_RADIUS'] = '6'
    elif (wheelRadius and wheelRadius != os.environ.get('WHEEL_RADIUS')):
        os.environ.pop('WHEEL_RADIUS')
        os.environ['WHEEL_RADIUS'] = str(wheelRadius)
Пример #10
0
def create_app():
    # Flask app initialization
    app = Flask(__name__)

    app.config.from_object(Config())

    # Creating database
    if not os.path.exists(DB_PATH + DB_NAME):
        os.mknod(DB_PATH + DB_NAME)

    # Database configuration
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = bool(os.getenv('SQLALCHEMY_TRACK_MODIFICATIONS'))
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL

    # Database initialization in Flask app
    db.init_app(app)

    scheduler.init_app(app)
    scheduler.start()

    @app.before_first_request
    def load_tasks():
        pass

    # Defining secret key for encryption and time of expiration of each access token that will be generated
    app.config['JWT_SECRET_KEY'] = str(os.getenv('JWT_SECRET_KEY'))
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = int(os.getenv('JWT_ACCESS_TOKEN_EXPIRES'))

    # JWT management initialization in Flask app
    jwt.init_app(app)

    # Defining general configuration for SMTP server
    app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER')
    app.config['MAIL_PORT'] = os.getenv('MAIL_PORT')
    app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS')
    app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')
    app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')
    app.config['FLASKY_MAIL_SENDER'] = os.getenv('FLASKY_MAIL_SENDER')

    # Flask mail handler initialization in Flask app
    out_server_sender.init_app(app)

    # Flask CORS configuration to allow access 
    CORS(app, resources={r"/*": {"origins": "*", "expose_headers":  ['X-Total-Count']}})

    # When the database is "connected in Flask app, the primary keys will activate"
    with app.app_context():
        from sqlalchemy import event
        event.listen(db.engine, 'connect', activate_primary_keys)

    # Defining urls for each resource
    api.add_resource(controller.SensorController, '/sensors/<id_num>')
    api.add_resource(controller.SensorsController, '/sensors')
    api.add_resource(controller.USeismController, '/seisms/unverified/<id_num>')
    api.add_resource(controller.USeismsController, '/seisms/unverified/')
    api.add_resource(controller.VSeismController, '/seisms/verified/<id_num>')
    api.add_resource(controller.GSeismsController, '/seisms/coordinates')
    api.add_resource(controller.VSeismsController, '/seisms/verified/')
    api.add_resource(controller.UserController, '/users/<id_num>')
    api.add_resource(controller.UsersController, '/users')
    api.add_resource(controller.UsersFilter, '/users/filter')
    api.add_resource(controller.SensorsFilter, '/sensors/filter')

    # Defining blueprints for each blueprint
    app.register_blueprint(auth_controller)
    app.register_blueprint(mail_controller)

    # Final app initialization
    api.init_app(app)

    return app
Пример #11
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    setup_db(app)

    CORS(app, resources={r"/*": {"origins": "*"}})

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

    @app.route('/')
    def health():
        return jsonify({'health': 'Running!!'}), 200

    @app.route('/categories')
    def get_categories():
        categories_query = Category.query.order_by(Category.id).all()
        categories_data = {}

        if len(categories_query) == 0:
            abort(500)

        for category in categories_query:
            categories_data[category.id] = category.type

        return jsonify({'categories': categories_data}), 200

    @app.route('/questions')
    def get_questions():
        search_term = request.args.get('search_term', '')
        current_category = request.args.get('current_category', None)
        current_category = None if current_category == '' else current_category
        page = request.args.get('page', 1, type=int)
        start = (page - 1) * QUESTIONS_PER_PAGE
        end = start + QUESTIONS_PER_PAGE

        try:
            questions_query = Question.query.filter(
                Question.question.ilike("%{}%".format(search_term)))

            if current_category is not None:
                questions_query = questions_query.filter(
                    Question.category == current_category)

            questions_query = questions_query.order_by(Question.id).all()
            questions_data = [
                question.format() for question in questions_query
            ]
            selected_questions_data = questions_data[start:end]

            if len(selected_questions_data) == 0:
                raise IndexError

            categories_query = Category.query.order_by(Category.id).all()
            categories_data = {}

            for category in categories_query:
                categories_data[category.id] = category.type

            return jsonify({
                'questions': selected_questions_data,
                'total_questions': len(questions_data),
                'categories': categories_data,
                'current_category': current_category,
                'search_term': search_term
            }), 200

        except IndexError:
            abort(404)

        except:
            abort(500)

    @app.route('/questions/<int:question_id>', methods=['DELETE'])
    def delete_question_by_id(question_id):
        question = Question.query.get_or_404(question_id)

        try:
            question.delete()
            return jsonify({'success': True}), 200

        except:
            abort(500)

    @app.route('/questions', methods=['POST'])
    def create_question():
        try:
            request_body = request.get_json()
            if request_body['question'] == '' or request_body['answer'] == '':
                raise TypeError

            new_question = Question(request_body['question'],
                                    request_body['answer'],
                                    request_body['category'],
                                    request_body['difficulty'])

            new_question.insert()

            return jsonify({'success': True}), 201

        except TypeError:
            abort(422)

        except:
            abort(500)

    @app.route('/questions/search', methods=['POST'])
    def search_questions():
        try:
            request_body = request.get_json()

            if 'searchTerm' not in request_body or 'currentCategory' not in request_body:
                raise TypeError

            questions_search_term = request_body['searchTerm']
            current_category = request_body['currentCategory']
            questions_query = Question.query.filter(
                Question.question.ilike("%{}%".format(questions_search_term)))

            if current_category is not None:
                questions_query = questions_query.filter(
                    Question.category == current_category)

            questions_query = questions_query.order_by(Question.id).all()
            questions_data = [
                question.format() for question in questions_query
            ]

            categories_query = Category.query.order_by(Category.id).all()
            categories_data = {}

            for category in categories_query:
                categories_data[category.id] = category.type

            return jsonify({
                'questions': questions_data[:QUESTIONS_PER_PAGE],
                'total_questions': len(questions_data),
                'categories': categories_data,
                'current_category': current_category,
                'search_term': questions_search_term
            }), 200

        except TypeError:
            abort(400)

        except:
            abort(500)

    @app.route('/categories/<category_id>/questions')
    def get_category_specific_question(category_id):
        try:
            questions_search_term = request.args.get('search_term', '')
            questions_query = Question.query.filter(
                Question.category == category_id,
                Question.question.ilike(
                    "%{}%".format(questions_search_term))).order_by(
                        Question.id).all()
            questions_data = [
                question.format() for question in questions_query
            ]

            if len(questions_data) == 0:
                raise IndexError

            categories_query = Category.query.order_by(Category.id).all()
            categories_data = {}

            for category in categories_query:
                categories_data[category.id] = category.type

            return jsonify({
                'questions': questions_data[:QUESTIONS_PER_PAGE],
                'total_questions': len(questions_data),
                'categories': categories_data,
                'current_category': category_id,
                'search_term': questions_search_term
            }), 200

        except IndexError:
            abort(404)

        except:
            abort(500)

    @app.route('/quizzes', methods=['POST'])
    def play_quiz():
        try:
            request_body = request.get_json()

            if 'previous_questions' not in request_body \
                    or 'quiz_category' not in request_body \
                    or 'id' not in request_body['quiz_category']:
                raise TypeError

            previous_questions = request_body['previous_questions']
            category_id = request_body['quiz_category']['id']
            questions_query = Question.query.with_entities(Question.id).filter(
                Question.id.notin_(previous_questions))

            if category_id != 0:
                questions_query = questions_query.filter(
                    Question.category == str(category_id))

            questions_query = questions_query.order_by(Question.id).all()
            question_ids = [q.id for q in questions_query]

            if len(question_ids) == 0:
                return jsonify({'question': None}), 200

            random_question_id = random.choice(question_ids)
            next_question = Question.query.get(random_question_id).format()

            return jsonify({'question': next_question}), 200

        except TypeError:
            abort(400)

        except:
            abort(500)

    @app.errorhandler(400)
    @app.errorhandler(404)
    @app.errorhandler(405)
    @app.errorhandler(422)
    @app.errorhandler(500)
    def error_handler(error):
        return jsonify({
            'success': False,
            'error': error.code,
            'message': error.description
        }), error.code

    return app
Пример #12
0
from d7a.alp.command import Command
from d7a.alp.interface import InterfaceType
from d7a.d7anp.addressee import IdType, Addressee
from d7a.phy.channel_header import ChannelBand, ChannelCoding, ChannelClass
from d7a.sp.configuration import Configuration
from d7a.sp.qos import QoS, ResponseMode
from d7a.system_files.system_files import SystemFiles
from d7a.system_files.system_file_ids import SystemFileIds
from d7a.types.ct import CT
from modem.modem import Modem

app = Flask(__name__, static_url_path='/static')
app.config[
    'SEND_FILE_MAX_AGE_DEFAULT'] = 0  # do not cache static assets for now
CORS(
    app
)  # TODO can be removed after integrating the ng project (and serving ng through flask)

socketio = SocketIO(app)
eventlet.monkey_patch()
modem = None


@app.route('/')
def index():
    return render_template('index.html',
                           systemfiles=SystemFiles().get_all_system_files(),
                           qos_response_modes=ResponseMode.__members__,
                           id_types=IdType.__members__)

Пример #13
0
                data['num_ab_readings'] = 0
                data['speed_ab_readings'] = 0
            else:
                data['num_ab_readings'] = len(ab_data)
                data['speed_ab_readings'] = max(item['speed_at_enable']
                                                for item in ab_data)

            data['last_updated'] = datetime.datetime.now().strftime(
                "%Y-%m-%dT%H:%M:%SZ")
            with open(app_config['datastore']['filename'], 'w') as outfile:
                json.dump(data, outfile)
            logger.debug(data)
            logger.info("Ending Periodic Processing")


def init_scheduler():
    sched = BackgroundScheduler(daemon=True)
    sched.add_job(populate_stats,
                  'interval',
                  seconds=app_config['scheduler']['period_sec'])
    sched.start()


app = connexion.FlaskApp(__name__, specification_dir='')
CORS(app.app)
app.app.config['CORS_HEADERS'] = 'Content-Type'
app.add_api("openapi.yml", strict_validation=True, validate_responses=True)

if __name__ == "__main__":
    init_scheduler()
    app.run(port=8100, use_reloader=False)
Пример #14
0
def create_app(test_config=None):

    # Initialize the flask application
    app = Flask(__name__)
    db = setup_db(app)
    cors = CORS(app, resources={r'/*': {'origins': '*'}})

    # Add CORS headers to response
    @app.after_request
    def add_cors_headers(response):
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,POST,PATCH,DELETE,OPTIONS')
        return response

    # GET /categories
    @app.route('/categories')
    def get_categories():
        try:
            # Query all the categories
            categories = Category.query.all()

            if not categories:
                abort(404)

            # Format the categories
            categories_data = {}
            for category in categories:
                categories_data[category.id] = category.type

            return jsonify({
                'success': True,
                'categories': categories_data,
            }), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # GET /questions?page=1
    @app.route('/questions')
    def get_questions():
        try:
            # Get the page no. from query string
            page = int(request.args.get('page', 1))

            # Get paginated questions and format data
            questions = Question.query.paginate(page, QUESTIONS_PER_PAGE)
            questions_data = [
                question.format() for question in questions.items
            ]

            # Get all categories and format data
            categories = Category.query.all()
            categories_data = {}
            for category in categories:
                categories_data[category.id] = category.type

            if not questions_data or not categories:
                abort(404)

            return jsonify({
                'success': True,
                'total_questions': questions.total,
                'questions': questions_data,
                'categories': categories_data,
                'current_category': None
            }), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # DELETE /questions/id
    @app.route('/questions/<int:id>', methods=['DELETE'])
    def delete_question(id):
        try:
            # Get the question by id
            question = Question.query.get(id)

            if not question:
                abort(404)

            # Delete question
            db.session.delete(question)
            db.session.commit()

            return jsonify({'success': True, 'id': question.id}), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # POST /questions
    @app.route('/questions', methods=['POST'])
    def add_question():
        try:
            # Get the data submitted
            data = request.get_json()
            question = data.get('question')
            answer = data.get('answer')
            difficulty = int(data.get('difficulty'))
            category = data.get('category')

            if not (data and question and answer and difficulty and category):
                abort(400)

            # Create a new question and add it
            new_question = Question(question, answer, difficulty, category)
            db.session.add(new_question)
            db.session.commit()

            return jsonify({'success': True, 'id': new_question.id}), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # POST /questions/search
    @app.route('/questions/search', methods=['POST'])
    def search_questions():
        try:
            # Get the search term
            data = request.get_json()
            search_term = data.get('searchTerm')

            # if not search_term:
            #     abort(400)

            # Query the database based on search
            questions = Question.query.filter(
                Question.question.ilike(f'%{search_term}%')).all()
            questions = [question.format() for question in questions]

            # if not questions:
            #     abort(404)

            return jsonify({
                'success': True,
                'questions': questions,
                'total_questions': len(questions),
                'current_category': None
            }), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # GET /categories/id/questions
    @app.route('/categories/<int:id>/questions')
    def get_questions_by_category(id):
        try:
            # Get the questions with category id
            questions = Question.query.filter_by(category=id).all()
            questions_data = [question.format() for question in questions]

            if not questions_data:
                abort(404)

            return jsonify({
                'success': True,
                'total_questions': len(questions),
                'questions': questions_data,
                'current_category': id
            }), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    # POST /quizzes
    @app.route('/quizzes', methods=['POST'])
    def play_quiz():
        try:
            data = request.get_json()
            previous_questions = data.get('previous_questions')
            quiz_category = data.get('quiz_category')

            # Get the questions by category
            if quiz_category['id'] == 0:
                questions = Question.query.all()
            else:
                questions = Question.query.filter_by(
                    category=quiz_category['id']).all()

            # Filter out previous questions
            while True:
                question = random.choice(questions)
                if question.id not in previous_questions:
                    break

            return jsonify({
                'success': True,
                'question': question.format()
            }), 200

        except Exception:
            print(sys.exc_info())
            db.session.rollback()
            abort(422)

        finally:
            db.session.close()

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            'success': False,
            'error': 400,
            'message': 'Bad request error'
        }), 400

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'success': False,
            'error': 404,
            'message': 'Resource not found'
        }), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        return jsonify({
            'success': False,
            'error': 500,
            'message': 'An error has occured, please try again'
        }), 500

    @app.errorhandler(422)
    def unprocesable_entity(error):
        return jsonify({
            'success': False,
            'error': 422,
            'message': 'Unprocessable entity'
        }), 422

    return app
Пример #15
0
from flask import Flask, render_template
import responder
from flask_cors import CORS

ALLOWED_HOSTS = {r"/": {"origins": "*"}}

app = Flask(__name__, static_folder='static/')

cors = CORS(app, resources=ALLOWED_HOSTS)

api = responder.API(allowed_hosts=[])
app.config['CORS_HEADERS'] = 'Content-Type'


@app.route("/", methods=['post', 'get'])
def home():
    return 'its working'


if __name__ == "__main__":
    app.run(host='0.0.0.0')
Пример #16
0
def create_app(config=None) -> connexion.FlaskApp:
    # configure_logger()
    logger.info("creating flask app", config=config)
    region = "localhost"
    host = f"http://dynamodb:{CFG.DYNALITE_PORT}" if is_docker() else CFG.DYNALITE_URL
    stripe.api_key = CFG.STRIPE_API_KEY
    logger.debug("aws", aws=CFG.AWS_EXECUTION_ENV)
    if CFG.AWS_EXECUTION_ENV:
        region = "us-west-2"
        host = None
    logger.info("app", port=CFG.DYNALITE_PORT, table_name=CFG.DELETED_USER_TABLE)
    options = dict(swagger_ui=CFG.SWAGGER_UI)

    app = connexion.FlaskApp(__name__, specification_dir="./", options=options)
    app.add_api(
        "swagger.yaml",
        pass_context_arg_name="request",
        strict_validation=True,
        validate_responses=True,
    )

    app.app.subhub_account = SubHubAccount(
        table_name=CFG.USER_TABLE, region=region, host=host
    )
    app.app.subhub_deleted_users = SubHubDeletedAccount(
        table_name=CFG.DELETED_USER_TABLE, region=region, host=host
    )
    if not app.app.subhub_account.model.exists():
        app.app.subhub_account.model.create_table(
            read_capacity_units=1, write_capacity_units=1, wait=True
        )
    if not app.app.subhub_deleted_users.model.exists():
        app.app.subhub_deleted_users.model.create_table(
            read_capacity_units=1, write_capacity_units=1, wait=True
        )

    # Setup error handlers
    @app.app.errorhandler(SubHubError)
    def display_subhub_errors(e: SubHubError):
        if e.status_code == 500:
            logger.error("display sub errors", error=e)
        response = jsonify(e.to_dict())
        response.status_code = e.status_code
        return response

    for error in (
        stripe.error.APIConnectionError,
        stripe.error.APIError,
        stripe.error.RateLimitError,
        stripe.error.IdempotencyError,
    ):
        app.app.errorhandler(error)(intermittent_stripe_error)

    for error in (stripe.error.AuthenticationError,):
        app.app.errorhandler(error)(server_stripe_error)

    for error in (
        stripe.error.InvalidRequestError,
        stripe.error.StripeErrorWithParamCode,
    ):
        app.app.errorhandler(error)(server_stripe_error_with_params)

    for error in (stripe.error.CardError,):
        app.app.errorhandler(error)(server_stripe_card_error)

    for error in (pynamodb.exceptions.GetError,):
        app.app.errorhandler(error)(database_connection_error)

    @app.app.before_request
    def before_request():
        headers = dump_safe_headers(request.headers)
        logger.bind(correlation_id=extract_safe(headers, "X-Amzn-Trace-Id"))
        logger.debug("Request headers", headers=headers)
        logger.debug("Request body", body=request.get_data())
        g.subhub_account = current_app.subhub_account
        g.subhub_deleted_users = current_app.subhub_deleted_users
        g.app_system_id = None
        if CFG.PROFILING_ENABLED:
            if "profile" in request.args and not hasattr(sys, "_called_from_test"):
                from pyinstrument import Profiler

                g.profiler = Profiler()
                g.profiler.start()

    @app.app.after_request
    def after_request(response):
        logger.unbind("correlation_id")
        if not hasattr(g, "profiler") or hasattr(sys, "_called_from_test"):
            return response
        if CFG.PROFILING_ENABLED:
            g.profiler.stop()
            output_html = g.profiler.output_html()
            return app.app.make_response(output_html)
        return response

    CORS(app.app)
    return app
Пример #17
0
import logging  # make our life easier when debugging.
import os  # path joining.
from flask import Flask, jsonify, make_response
from flask_cors import CORS  # if someone loads the front end via file browser, localhost is CORS

DATA_DIR = 'data'
TOTALS_FILE = 'oys_totals.tsv'
FREQ_FILE = 'oys_freq.tsv'
"""
I'd much rather be using connexion (https://github.com/zalando/connexion) or blueprint
for loading API routes from an OpenAPI specification, but I ran out of time when putting
this brief demo together to do everything 'by the book'.
"""
APP = Flask(__name__)
CORS(
    APP
)  # allow cross domain requests so the API doesn't get disallowed by the browser.


def get_tsv_dataset(dataset_path):
    """
    Helper function to get a single TSV row from a data file.
    :param dataset_path: str: path to a TSV that contains a one line dataset.
    :return: list of str, or None if data could not be read.
    """
    if not os.path.exists(dataset_path):
        logging.error('No such path %s', dataset_path)
        return None

    try:
        ds_file = open(dataset_path)
Пример #18
0
import os
from werkzeug.exceptions import HTTPException

# Global Flask Application Variable: app
app = Flask(__name__)
swagger = Swagger(app)

# global strict slashes
app.url_map.strict_slashes = False

# flask server environmental setup
host = os.getenv('HBNB_API_HOST', '0.0.0.0')
port = os.getenv('HBNB_API_PORT', 5000)

# Cross-Origin Resource Sharing
cors = CORS(app, resources={r"/api/v1/*": {'origins': "*"}})

# app_views BluePrint defined in api.v1.views
app.register_blueprint(app_views)


# begin flask page rendering
@app.teardown_appcontext
def teardown_db(exception):
    """
    after each request, this method calls .close() (i.e. .remove()) on
    the current SQLAlchemy Session
    """
    storage.close()

Пример #19
0
import os
from flask import Flask
from flask_cors import CORS

cors = CORS()


def create_app():
    app = Flask(__name__)

    cors.init_app(app)

    app_settings = os.getenv("APP_SETTINGS")
    app.config.from_object(app_settings)
    app.config["CORS_HEADERS"] = "Access-Control-Allow-Origin"

    from project.api.api import views_blueprint
    app.register_blueprint(views_blueprint)

    return app
Пример #20
0
reset_password_salt = "reset-password-salt"

# supported_languages = ["en", "fr", "pt", "it", "de", "es"]
supported_languages = ["en", "fr"]

origins = []
if flask_env == "development":
    origins = ["http://localhost:3000", "http://dev.localhost:3000"]
elif flask_env == "production":
    origins = ["https://www.dofuslab.io", "https://dofuslab.io"]

db = SQLAlchemy(app)
CORS(
    app,
    resources={r"/*": {
        "origins": origins
    }},
    supports_credentials=True,
)

from contextlib import contextmanager


@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    db_session = db.session
    try:
        yield db_session
        db_session.commit()
    except:
Пример #21
0
def create_app(test_config=None):
    # Create the app
    app = Flask(__name__)
    setup_db(app)

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

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

    # Endpoint to return all categories
    @app.route('/categories')
    def retrieve_categories():
      categories = Category.query.order_by(Category.id).all()
      formatted_categories = {category.id: category.type for category in categories}

      if len(categories) == 0:
        abort(404)

      return jsonify({
        'success': True,
        'categories': formatted_categories
      })

    # Endpoint to return all questions
    @app.route('/questions')
    def retrieve_questions():
      selection = Question.query.order_by(Question.id).all()
      current_questions = paginate_questions(request, selection)
      total_questions = len(Question.query.all())
      categories = Category.query.order_by(Category.id).all()
      formatted_categories = {category.id: category.type for category in categories}
      current_category = Category.query.order_by(Category.id).first()

      if len(current_questions) == 0:
        abort(404)

      return jsonify({
        'success': True,
        'questions': current_questions,
        'total_questions': total_questions,
        'categories': formatted_categories,
        'current_category': {current_category.id: current_category.type}
      })

    # Endpoint to delete a question from the database
    @app.route('/questions/<int:question_id>', methods=['DELETE'])
    def delete_questions(question_id):
      try:
        question = Question.query.filter(Question.id == question_id).one_or_none()

        if question is None:
          abort(404)

        db.session.delete(question)
        db.session.commit()
        
      except:
        db.session.rollback()
        abort(422)
      finally:
        db.session.close()

      return jsonify({
        'success': True,
        'deleted': question_id,
        
      })


    # Endpoint that will will create a new question in the database, or complete a search in the text 
    # of the questions based on a search term entered by the user.
    @app.route('/questions', methods=['POST'])
    def create_question():
      body = request.get_json()

      search_term = body.get('searchTerm')

      if search_term:
        search_matches = Question.query.order_by(Question.id).filter(Question.question.ilike('%{}%'.format(search_term)))
        current_questions = paginate_questions(request, search_matches)
        total_questions = len(search_matches.all())
        current_category = Category.query.order_by(Category.id).first()

        return jsonify({
          'success': True,
          'questions': current_questions,
          'total_questions': total_questions,
          'current_category': {current_category.id: current_category.type}
        })
      else:
        try:
          question = body.get('question', None)
          answer = body.get('answer', None)
          difficulty = body.get('difficulty', None)
          category = body.get('category', None)

          new_question = Question(question=question,answer=answer,category=category,difficulty=difficulty)
          db.session.add(new_question)
          db.session.commit()
        except:
          db.session.rollback()
          abort(422)
        finally:
          new_question_id = new_question.id
          db.session.close()

        return jsonify({
          'success': True,
          'question_id': new_question_id
        })
    
    # Endpoint to return questions in a specified category
    @app.route('/categories/<int:category_id>/questions')
    def retrieve_questions_by_category(category_id):
      selection = Question.query.order_by(Question.id).filter(Question.category == category_id)
      total_questions = len(selection.all())
      current_questions = paginate_questions(request, selection)
      current_category = Category.query.get(category_id)

      if total_questions == 0:
        abort(404)

      return jsonify({
        'success': True,
        'questions': current_questions,
        'total_questions': total_questions,
        'current_category': {current_category.id: current_category.type}
      })


    # Endpoint that will provide the next question to a quiz. The query will get a random question from the database 
    # (by category if specified), not including previous questions. 
    @app.route('/quizzes', methods=['POST'])
    def create_quiz():
      body = request.get_json()

      previous_questions = body.get('previous_questions', None)
      quiz_category = body.get('quiz_category', None)

      if quiz_category['id'] == 0:
        current_question = Question.query.filter(Question.id.notin_(previous_questions)).order_by(func.random()).first()
      else:
        current_question = Question.query.filter(Question.category == quiz_category['id']).filter(Question.id.notin_(previous_questions)).order_by(func.random()).first()

      if current_question:
        current_question = current_question.format()

      return jsonify({
        'success': True,
        'question': current_question
      })  

    @app.errorhandler(400)
    def bad_request(error):
      return jsonify({
        "success": False, 
        "error": 400,
        "message": "bad request"
        }), 400 

    @app.errorhandler(404)
    def not_found(error):
      return jsonify({
        "success": False, 
        "error": 404,
        "message": "resource not found"
        }), 404

    @app.errorhandler(422)
    def unprocessable(error):
      return jsonify({
        "success": False, 
        "error": 422,
        "message": "unprocessable"
        }), 422

    return app

    
Пример #22
0
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from model import *
from user_mngmnt import *
from pre_exam import *
from atm import *
from exam import *
from evm import *
from rvm import *

CORS(application)
api = Api(application)

#=================================================#
#             USER MANAGEMENT MODULE              #
#=================================================#
api.add_resource(UserLogin, '/api/v1/user_login')
api.add_resource(UserLogout, "/api/v1/logout")
api.add_resource(Forgotpassword, "/api/v1/forgotpassword")
api.add_resource(Newpassword, "/api/v1/newpassword")
api.add_resource(Changepassword, "/api/v1/changepassword")
api.add_resource(AdditionalExaminerLogin, "/api/v1/additional_examiner_login")
api.add_resource(CacheClear, "/api/v1/cache_clear")

#=================================================#
#             PRE EXAMINATION MODULE              #
#=================================================#
api.add_resource(ExamCenter_Add, '/api/v1/examcenter_add')
api.add_resource(Designation_Add, "/api/v1/designation_add")
api.add_resource(Role_Add, '/api/v1/role_add')
Пример #23
0
import sys
import os
from flask_cors import CORS, cross_origin

from connections import api
from model import User, Post, Search
from view import view

template_dir = os.path.abspath('templates')
print(template_dir)

static_dir = os.path.abspath('static')
print(static_dir)

app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)
cors = CORS(app)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config['CORS_HEADERS'] = 'Content-Type'
app.config.update(TESTING=True, SECRET_KEY='DevTest')
app.app_context().push()

users = User.users
Last_search = []
Search_Results = []
userPublicData = {'username': ""}

Search_word = 'aaaaaaaaa'


@app.route('/')
@cross_origin()
Пример #24
0
import os
import json
from flask import Flask, request
app = Flask(__name__)

from flask_cors import CORS, cross_origin
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app, resources={r"/": {"origins": os.getenv('FRONTEND_BASE_URL')}})

from datetime import datetime 

import logging
if os.getenv('FLASK_DEBUG') == 'true':
  logging.basicConfig(level=logging.DEBUG) 

# import helper functions 
from helpers import missed_job, error_in_job, send_email

# APScheduler imports and config
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
# import event constants 
from apscheduler.events import EVENT_JOB_MISSED, EVENT_JOB_ERROR

# configure postgres jobstore
POSTGRES_URI = os.getenv('POSTGRES_URI')
jobstore = {
  'default': SQLAlchemyJobStore(url=POSTGRES_URI)
}

scheduler = BackgroundScheduler(
Пример #25
0
class Server:
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
    MATRIX_PATH = Path('gen_data/matrix.npy')
    NEW_META_PATH = Path('gen_data/processed_reddit_data.pth')
    IMAGE_FOLDER = Path('images')
    PAINTING_FOLDER = 'painting'

    matrix = np.load(MATRIX_PATH)
    meta = torch.load(NEW_META_PATH)
    sampler = TextSampler(matrix, meta)
    printer = Printer()

    with open(f'latent_space/{PAINTING_FOLDER}.p', 'rb') as fp:
        paintings = pickle.load(fp)

    app = Flask(__name__, static_folder='static')
    CORS(app)

    isearcher = ISearcher(IMAGE_FOLDER)
    tsearcher = TextSearcher()

    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)

    def run(self, host: str):
        self.app.run(host=host)

    @staticmethod
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in Server.ALLOWED_EXTENSIONS

    @orm.db_session
    def download_images(self):
        self.logger.info('Downloading images...')

        if not self.IMAGE_FOLDER.exists():
            self.IMAGE_FOLDER.mkdir()

        for meme in Meme.select():
            image = self.IMAGE_FOLDER / str(meme.id)

            if not image.exists():
                r = requests.get(meme.image, stream=True)

                if r.status_code == 200:
                    with image.open('wb') as f:
                        for chunk in r:
                            f.write(chunk)

    @staticmethod
    @app.route('/memes')
    @orm.db_session
    def get_memes():
        id_ = request.args.get('id')

        if id_ is not None and Meme.exists(id=int(id_)):
            return jsonify(Server._get_meme_long_desc(Meme.get(id=int(id_))))

        memes = [Server._get_meme_short_desc(meme) for meme in Meme.select()]

        memes.append(Server._get_quiz_desc(1))
        memes.append(Server._get_generator_desc(1))
        memes.append(Server._get_generator_desc(2))

        return jsonify(memes)

    @staticmethod
    @app.route('/isearch', methods=['POST'])
    @orm.db_session
    def image_search():
        file = request.files['file']
        if file and Server.allowed_file(file.filename):
            image = PILImage.open(io.BytesIO(file.read()))
            result = Server.isearcher.search_img(image, top_k=3)
            return jsonify({'results': result})

    @staticmethod
    @app.route('/search')
    @orm.db_session
    def text_search():
        query = request.args.get('q')
        result = list(map(str, Server.tsearcher.search(query)[:3]))
        return jsonify({'results': result})

    @staticmethod
    @app.route('/generate', methods=['POST'])
    def generate_meme():
        id_ = int(request.values['id'])
        file = request.files['file']
        if file and Server.allowed_file(file.filename):
            image = PILImage.open(io.BytesIO(file.read()))

            if id_ == 1:
                text = Server.sampler.sample(image)
                meme = Server.printer.print(image, text)
            else:
                image = np.array(image.convert('RGB'))
                embeddings = face_recognition.face_encodings(image)

                if len(embeddings) > 0:
                    photo = embeddings[0]
                    key = min(Server.paintings.items(),
                              key=lambda x: np.sum(
                                  np.sqrt((photo - np.array(x[1]))**2)))[0]
                else:
                    key = random.choice(list(Server.paintings.keys()))

                folder = '' if key[0] == '1' else ' 2'
                file_to_load = f'dataset_updated/{folder}/training_set/{Server.PAINTING_FOLDER}/{key[1:]}.jpg'
                meme = PILImage.open(file_to_load)

            current_date = datetime.now().strftime('%Y.%m.%d.%H.%M.%S')
            file_name = f'{current_date}.png'
            meme.save(f'static/{file_name}')
            return jsonify({'result': file_name})

    @staticmethod
    @app.route('/quiz')
    @orm.db_session
    def get_quiz():
        id_ = int(request.args.get('id'))
        return jsonify({
            'id':
            id_,
            'questions': [{
                'text': q.text,
                'answer': q.answer,
                'memes': [q.meme_1, q.meme_2, q.meme_3]
            } for q in Question.select(lambda it: it.quiz == id_)]
        })

    @orm.db_session
    def build_text_index(self):
        data = [(it.id, it.about) for it in Meme.select()]
        self.tsearcher.build_index(data)

    @staticmethod
    @orm.db_session
    def _get_meme_long_desc(meme) -> dict:
        return {
            'id':
            meme.id,
            'url':
            meme.image,
            'name':
            meme.name,
            'about':
            meme.about,
            'origin':
            meme.origin,
            'tags':
            meme.type.split(',') if meme.type else [],
            'images':
            list(
                map(lambda it: it.url,
                    Image.select(lambda it: it.meme == meme.id)))
        }

    @staticmethod
    @orm.db_session
    def _get_meme_short_desc(meme) -> dict:
        return {
            'id': meme.id,
            'quiz': None,
            'generator': None,
            'url': meme.image,
            'about': meme.about
        }

    @staticmethod
    @orm.db_session
    def _get_quiz_desc(quiz_id: int) -> dict:
        return {'quiz': quiz_id}

    @staticmethod
    @orm.db_session
    def _get_generator_desc(generator_id: int) -> dict:
        return {'generator': generator_id}
Пример #26
0
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         __init__.py.py
# Description:  
# Author:       [email protected]
# Date:         2020/3/17  23:51
# -------------------------------------------------------------------------------

from flask import Blueprint
from app import Mongodb
from flask_cors import CORS


# create BluePrint object
api = Blueprint("api", __name__)
CORS(api)

from . import demo
from . import microbe
Пример #27
0
from flask import Flask, request, jsonify, Response
from flask_cors import CORS, cross_origin
from generators import get_room_artifacts

app = Flask(__name__)
# cors = CORS(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})



#############################################################
# API
#############################################################

@app.route("/")
def api_root():
  return "Malloci Artifact Generator"

#############################################################
# POST /generate
# 	Returns links of all images uploaded with this service
#############################################################
@app.route("/generate",  methods=['POST'])
@cross_origin(origin="*", headers=['Content-Type','Authorization'])
def parse_doc():
	content = request.json
	
	for room in content['rooms']:
		room['artifacts'] = get_room_artifacts(room['text'])
		if 'subRooms' in room:
			for subroom in room['subRooms']:
Пример #28
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    setup_db(app)
    CORS(app)

    @app.errorhandler(400)
    def handle_bad_request(e):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "bad request"
        }), 400

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    @app.errorhandler(422)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": str(error)
        }), 422

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

    @app.route('/books')
    def retrieve_books():
        selection = Book.query.order_by(Book.id).all()
        current_books = paginate_books(request, selection)

        if len(current_books) == 0:
            abort(404)

        return jsonify({
            'success': True,
            'books': current_books,
            'total_books': len(Book.query.all())
        })

    @app.route('/books/<int:book_id>', methods=['PATCH'])
    def update_book(book_id):

        body = request.get_json()

        try:
            book = Book.query.filter(Book.id == book_id).one_or_none()
            if book is None:
                print('!!!!!!!!!HERE!!!!!!!!!')
                abort(404)

            if 'rating' in body:
                book.rating = int(body.get('rating'))

            book.update()

            return jsonify({
                'success': True,
            })

        except:
            abort(400)

    @app.route('/books/<int:book_id>', methods=['DELETE'])
    def delete_book(book_id):
        try:
            book = Book.query.filter(Book.id == book_id).one_or_none()

            if book is None:
                abort(404)

            book.delete()
            selection = Book.query.order_by(Book.id).all()
            current_books = paginate_books(request, selection)

            return jsonify({
                'success': True,
                'deleted': book_id,
                'books': current_books,
                'total_books': len(Book.query.all())
            })

        except:
            abort(422, description="Unprocessable")

    @app.route('/books', methods=['POST'])
    def create_book():
        body = request.get_json()

        new_title = body.get('title', None)
        new_author = body.get('author', None)
        new_rating = body.get('rating', None)

        try:
            book = Book(title=new_title, author=new_author, rating=new_rating)
            book.insert()

            selection = Book.query.order_by(Book.id).all()
            current_books = paginate_books(request, selection)

            return jsonify({
                'success': True,
                'created': book.id,
                'books': current_books,
                'total_books': len(Book.query.all())
            })

        except:
            abort(422, description="Unprocessable")

    # @TODO: Review the above code for route handlers.
    #        Pay special attention to the status codes used in the aborts since those are relevant for this task!

    # @TODO: Write error handler decorators to handle AT LEAST status codes 400, 404, and 422.

    # TEST: Practice writing curl requests. Write some requests that you know will error in expected ways.
    #       Make sure they are returning as expected. Do the same for other misformatted requests or requests missing data.
    #       If you find any error responses returning as HTML, write new error handlers for them.

    # @app.errorhandler(404)
    # def not_found(error):
    #     return jsonify({
    #         "success": False,
    #         "error": 404,
    #         "message": "Not found"
    #         }), 404

    # @app.errorhandler(422)
    # def resource_not_found(e):
    #     return jsonify(error=str(e)), 422

    # @app.errorhandler(422)
    # def not_found(error):
    #     return jsonify({
    #         "success": False,
    #         "error": 422,
    #         "message": error
    #         }), 422

    return app
Пример #29
0
import datetime
from flask import Flask, request, redirect, jsonify
from flask_cors import CORS
from json import loads
import math
import random
import requests
import twilio.twiml
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client

client = Client("AC4e7890114509da5929a4bc79ebf8bdc0",
                "47ee8d75ad0e2973601122c2a65d7b7c")

app = Flask(__name__)
CORS(app)

database = {}
comments = {}
new_event_id = -1
subscribers = {"+16475153544"}
# This has a sample user.
# They want to be alerted via text, for all crimes that occur.


def distance(loc, event):
    x_loc = loc[0]
    y_loc = loc[1]
    x_event = event[2]
    y_event = event[3]
    sq = lambda x: x * x
Пример #30
0
app = Flask(__name__)
app.secret_key = 'secret'
app.config['FLASK_ADMIN_SWATCH'] = 'cyborg'
app.config['JWT_SECRET_KEY'] = 'super-secret'
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config[
    'JWT_COOKIE_SECURE'] = False  # Set to True in production (for HTTPS)
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config['JWT_ACCESS_COOKIE_PATH'] = '/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = config.config()['accessExpiration']
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = config.config()['refreshExpiration']

cors = CORS(app,
            resources={r"/*": {
                "origins": config.config()['clientOrigin']
            }},
            supports_credentials=True)
api = Api(app)
jwt = JWTManager(app)
admin = Admin(app, name='KLAP4', template_mode='bootstrap3')

#TODO: Make custom model views for each model (like genre)
admin.add_view(GenreModelView(Genre, session))
admin.add_view(ArtistModelView(Artist, session))
admin.add_view(AlbumModelView(Album, session))
admin.add_view(SongModelView(Song, session))
admin.add_view(AlbumReviewModelView(AlbumReview, session))
admin.add_view(AlbumProblemModelView(AlbumProblem, session))
admin.add_view(ProgramFormatModelView(ProgramFormat, session))
admin.add_view(ProgramModelView(Program, session))