def settings():
    """ Create the app config """

    # Cords Settings App
    CORS(_app)

    # validate JSON data
    JsonSchema(_app)

    todo_list_router(_app)

    return _app
Пример #2
0
from flask_cors import CORS
import sqlite3
import logging


app = Flask(__name__)

formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("escolaapp.log")
handler.setFormatter(formatter)
logger = app.logger
logger.addHandler(handler)
logger.setLevel(logging.INFO)


schema=JsonSchema()
schema.init_app(app)

schema_endereco = {
    'required': ['logradouro', 'complemento',  'bairro', 'cep', 'numero'],
    'properties': {
        'logradouro': {'type': 'string'},
        'complemento': {'type': 'string'},
        'bairro': {'type': 'string'},
        'cep': {'type': 'string'},
        'numero': {'type': 'integer'}
    }
}

schema_escola = {
    'required': ['nome', 'id_endereco', 'id_campus'],
Пример #3
0
from flask_json_schema import JsonSchema, JsonValidationError

schema = JsonSchema()
Пример #4
0
    value = os.getenv(envVarName)
    if not value:
        raise "Must set the " + envVarName + " environment variable (have you created a .env file during local development?)"
    return value


dbPassword = getEnvVarOrDie("DB_PASS")
dbUrl = getEnvVarOrDie("DB_URL")
dbName = getEnvVarOrDie("DB_NAME")
dbUser = getEnvVarOrDie("DB_USER")

app = Flask(__name__, static_folder=None)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['JWT_SECRET_KEY'] = getEnvVarOrDie("JWT_KEY")
jwt = JWTManager(app)
schema = JsonSchema(app)

logger = app.logger

db = db.PortalDb(dbPassword, dbUrl, dbName, dbUser)


@app.route('/api/login', methods=['POST'])
def login():
    email = request.json.get('email')
    logger.info('User with email %s logging in', email)
    loginHandler = LoginHandler(db, logger, create_access_token)
    token = loginHandler.generateUserToken(email, request.json.get('password'))

    if token is None:
        return Response(status=401)
Пример #5
0
import uuid
from logging.handlers import RotatingFileHandler

import tensorflow as tf
import yaml
from flask import Flask, request, Response
from flask_json_schema import JsonSchema, JsonValidationError

import deploy
import predict
import train
from lime_utils import visualization, visualization_2
from schema import TRAIN_SCHEMA, PREDICT_SCHEMA, DEPLOY_SCHEMA, LIME_SCHEMA, LIME_SCHEMA_2

APP = Flask(__name__)
SCHEMA = JsonSchema(APP)


def read_yaml():
    """
    Reads the config file to variables

    Returns:
        A dict containing configurations
    """
    with open("config/config_file.yaml", 'r') as ymlfile:
        return yaml.load(ymlfile)


def get_job_link():
    """
Пример #6
0
####################################################################################
# Allows access to fetch at 'http://localhost:5000/' from origin 'app://obsidian.md'
obsidian_origin = "app://obsidian.md"
cors = CORS(app, origins=obsidian_origin)
app.config['CORS_HEADERS'] = 'Content-Type'

####################################################################################
# Schema
####################################################################################
# Input schema example:
# {
#   vaultPath: "/home/cvasquez/obsidian/development",
#   notePath: "snippets-plugin/Test1.md"
#   text: "Some selected text",
# }
validator = JsonSchema(app)
input_schema = {
    'required': ['vaultPath'],
    'properties': {
        'vaultPath': {
            'type': 'string'
        },
        'notePath': {
            'type': 'string'
        },
        'text': {
            'type': 'string'
        },
        'script': {
            'type': 'string'
        },
Пример #7
0
import json

from flask import jsonify, Blueprint, request, current_app
from db.postgres import db
from flask_cors import cross_origin
from sqlalchemy import Sequence
from flask_json_schema import JsonSchema
from models.department import Department
from models.location import Location
from models.category import Category
from models.sub_category import Subcategory
import pdb
category_api = Blueprint('category_api', __name__)
category_api.config = {}
schema = JsonSchema(category_api)


@category_api.route("/api/v1/category", methods=['POST'])
@cross_origin("*")
def create():

    try:
        input_json_data = request.get_json()
        db.create_all()
        db.session.commit()
        if not input_json_data:
            return {"message": "No input data provided"}, 400
        new_category = input_json_data['category']
        new_subcategory = input_json_data['subcategory']
        category_results = Category.query.filter(
            Category.category == new_category)
Пример #8
0
import json

from flask import jsonify, Blueprint, request, current_app
from models.location import Location
from db.postgres import db
from flask_json_schema import JsonSchema
from flask_cors import cross_origin
from sqlalchemy import Sequence
import pdb
location_api = Blueprint('location_api', __name__)
location_api.config = {}
schema = JsonSchema(location_api)


@location_api.route("/api/v1/location", methods=['POST'])
@cross_origin("*")
def create():

    try:
        input_json_data = request.get_json()
        if not input_json_data:
            return {"message": "No input data provided"}, 400
        new_location = input_json_data['location']
        new_department = input_json_data['department']
        location_results = Location.query.filter(
            Location.location == new_location)
        #   validation of location
        for temp in location_results:
            string_val = temp.serialize()
            if (new_location == string_val.get('location')
                    and new_department == string_val.get('department')):
Пример #9
0
import json

from flask import jsonify, Blueprint, request, current_app
from db.postgres import db
from flask_cors import cross_origin
from sqlalchemy import Sequence
from flask_json_schema import JsonSchema
from models.department import Department
from models.location import Location
from models.category import Category
from models.sub_category import Subcategory
import pdb

sub_category_api = Blueprint('sub_category_api', __name__)
sub_category_api.config = {}
schema = JsonSchema(sub_category_api)


@sub_category_api.route("/api/v1/subcategory", methods=['POST'])
@cross_origin("*")
def create():

    try:
        input_json_data = request.get_json()

        db.create_all()
        db.session.commit()
        if not input_json_data:
            return {"message": "No input data provided"}, 400
        subcategory_1 = input_json_data['subcategory']
        category_1 = input_json_data['category']
Пример #10
0
def create_app(args):
    """
    Creates and configures flask api and app.
    Adds resources defined in app.resources.

    :return: preconfigured api
    """

    logger.debug("Creating Api")
    app = Flask(__name__, instance_relative_config=True)

    # register json validation schema
    # NOTE: needs to be passed to different views and register specific schema
    schema = JsonSchema(app)

    # Environment configuration from instance directory
    app.config.from_pyfile("config.py")

    sslify = SSLify(app)

    # views rules
    app.add_url_rule(rule="/", endpoint="index", view_func=index)

    # custom error handler for json validation errors
    app.register_error_handler(JsonValidationError, json_validation_error)

    # Add webpage to app
    app = webpage(app)

    api = Api(app)

    db_handler = database_handler()
    channels = _init_channels(db_handler)
    message_handler = Message_handler(channels=channels,
                                      _database_handler=db_handler)

    jwt = JWTManager(app)
    blacklist = set()

    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(token):
        jti = token['jti']
        return jti in blacklist

    api.add_resource(UserLogin,
                     "/api/user-login",
                     resource_class_kwargs={
                         'db_handler': db_handler,
                         'jwt': jwt
                     })
    api.add_resource(
        RefreshLogin,
        "/api/re-login",  #Maybe change this to something that might be more suitable? Patch request to login?
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt
        },
    )
    api.add_resource(
        Logout,
        "/api/logout",
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt,
            'blacklist': blacklist
        },
    )
    api.add_resource(
        RefreshLogout,
        "/api/re-logout",
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt,
            'blacklist': blacklist
        },
    )
    api.add_resource(
        Users,
        "/api/users",
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt
        },
    )
    api.add_resource(UserSingle,
                     "/api/users/<string:user_id>",
                     resource_class_kwargs={
                         'db_handler': db_handler,
                         'jwt': jwt
                     })
    api.add_resource(
        Messages,
        "/api/messages",
        resource_class_kwargs={
            'db_handler': db_handler,
            'message_handler': message_handler,
            'jwt': jwt
        },
    )
    api.add_resource(
        MessageSingle,
        "/api/messages/<string:message_id>",
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt
        },
    )
    api.add_resource(
        MessageSeen,
        "/api/messages/<string:message_id>/<string:seen_id>",
        resource_class_kwargs={
            'db_handler': db_handler,
            'jwt': jwt
        },
    )
    # enpoint to update messages to database
    api.add_resource(
        Update,
        "/api/channels/update",
        resource_class_kwargs={
            'handler': db_handler,
            "channels": channels
        },
    )

    logger.info("Init channels is done")

    return app
Пример #11
0
import json

from flask import jsonify, Blueprint, request, current_app
from db.postgres import db
from flask_cors import cross_origin
from sqlalchemy import Sequence
from flask_json_schema import JsonSchema
from models.department import Department
from models.location import Location
from models.category import Category
import pdb
department_api = Blueprint('department_api', __name__)
department_api.config = {}
schema = JsonSchema(department_api)


@department_api.route("/api/v1/department", methods=['POST'])
@cross_origin("*")
def create():

    try:
        input_json_data = request.get_json()
        db.create_all()
        db.session.commit()
        if not input_json_data:
            return {"message": "No input data provided"}, 400
        new_category = input_json_data['category']
        new_department = input_json_data['department']
        department_results = Department.query.filter(
            Department.department == new_department)
        #   validation of department details