from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = '003dfc3d42706900f9d835b807122015'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

from app import routes
from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from datetime import datetime
from math import ceil

application = Flask(__name__)
application.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:12345678@localhost/flask'
db = SQLAlchemy(application)
bcrypt = Bcrypt(application)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    last_name = db.Column(db.String(50), unique=False, nullable=False)
    first_name = db.Column(db.String(50), unique=False, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    status = db.Column(db.String(20), nullable=True)
    date_created = db.Column(db.DateTime,
                             nullable=False,
                             default=datetime.utcnow)

    def __repr__(self):
        return f'id:{self.id}, name:{self.last_name}.{self.first_name}, email:{self.email}\n'


class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    street1 = db.Column(db.String(200), unique=False, nullable=False)
Exemple #3
0
def hash_pass(passwd):
    hashed_passwd = Bcrypt().generate_password_hash(passwd).decode('utf-8')
    return hashed_passwd
Exemple #4
0
import os

from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt

# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)

app.config.from_object('app.configuration.Config')

db = SQLAlchemy(app)  # flask-sqlalchemy
bc = Bcrypt(app)  # flask-bcrypt

lm = LoginManager()  # flask-loginmanager
lm.init_app(app)  # init the login manager


# Setup database
@app.before_first_request
def initialize_database():
    db.create_all()


# Import routing, models and Start the App
from app import views, customer_views, models
Exemple #5
0
def sign_up_save():
    '''
    This function takes POST http request with a URL of "/signup/save". It firstly reads the user submitted username,
    password1 and password2. It then connects to the database to check if there is already an existing username in the
    database. The function also checks whether the user provided all the necessary information; whether the format of
    the username and password are correct and whether the two passwords match. If any of the above condition failed,
    the function will return user with "signup_index.html" with error message. If not, the function will insert the
    user provided information to the database and return "signup_succeed_index.html" page to user indicating the user
    has successfully created a new account.
    :return: "signup_index.html"  or "signup_succeed_index.html"
    '''

    bcrypt = Bcrypt(webapp)
    # need to trim the user name
    username = request.form.get('username', "")
    password1 = request.form.get('password1', "")
    password2 = request.form.get('password2', "")

    # connect to database
    cnx = get_database()
    cursor = cnx.cursor()
    query = "SELECT COUNT(username) FROM user_info WHERE username = %s "
    cursor.execute(query, (username,))
    results = cursor.fetchall()
    numberOfExistUser = results[0][0]

    if username == "" or password1 == "" or password2 == "":
        error_msg = "Error: All fields are required!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if re.findall(r'\s+', username) != []:
        error_msg = "Error: No space allowed in user name!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if numberOfExistUser != 0:
        error_msg = "Error: User name already exist!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if not (password1 == password2):
        error_msg = "Error: Two passwords not matching!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if (len(username) > 20 or len(username) < 1) or not all(c in validUsernameChar for c in username):
        print(len(username))
        error_msg = "Error: Username violation, username must have length between 1 to 20, only letters and numbers allowed"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if len(password1) > 16 or len(password1) < 1:
        error_msg = "Error: Password length violation"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

    password = bcrypt.generate_password_hash(password1).decode("utf-8")

    query = ''' INSERT INTO user_info (username,password,create_date,active)
                       VALUES (%s,%s, %s,1)
    '''

    cursor.execute(query, (username, password, timestamp))
    cnx.commit()

    # Add error catch here for sql

    return render_template("signup_succeed_index.html", title="Sign Up Succeed", username=username, password=password1)
Exemple #6
0
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt

fl_bcrypt = Bcrypt()

db = SQLAlchemy()


def connect_db(app):
    """ Connect to database. """

    db.app = app
    db.init_app(app)


class User(db.Model):
    """ USER. """

    __tablename__ = "users"

    username = db.Column(db.String(20),
                         primary_key=True,
                         nullable=False,
                         unique=True)

    password = db.Column(db.Text, nullable=False)

    email = db.Column(db.String(50), nullable=False, unique=True)

    first_name = db.Column(db.String(30), nullable=False)
def user_register_api():
    '''
    This function takes POST http request with a URL of "/api/register". It firstly reads the user submitted username
    and password. It then connects to the database to check if there is already an existing username in the database.
    The function also checks whether the user provided all the necessary information; whether the format of the
    username and password are correct. If any of the above conditions failed, the function will return user with a
    formatted Json string including the error code and error message. If all the condition check passed, the function
    will create a new entry in the dataset and return a Json string with code 200 indicating request processed
    successfully.
    :return: Json string with status code and information string
    '''

    bcrypt = Bcrypt(webapp)
    # need to trim the user name
    username = request.form.get('username', "")
    password = request.form.get('password', "")

    # connect to database
    cnx = get_database()
    cursor = cnx.cursor()
    query = "SELECT COUNT(username) FROM user_info WHERE username = %s "
    cursor.execute(query, (username, ))
    results = cursor.fetchall()
    numberOfExistUser = results[0][0]

    if numberOfExistUser != 0:
        return http_response(409, "Error: User name already exist!")

    if username == "" or password == "":
        return http_response(400, "Error: All fields are required!")

    if re.findall(r'\s+', username) != []:
        return http_response(400, "Error: No space allowed in user name!")

    if (len(username) > 20
            or len(username) < 1) or not all(c in validUsernameChar
                                             for c in username):
        return http_response(
            400,
            "Error: Username violation, username must have length between 1 to 20, only letters and numbers allowed"
        )

    if len(password) > 16 or len(password) < 1:
        return http_response(400, "Error: Password length violation")

    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')

    password = bcrypt.generate_password_hash(password).decode("utf-8")

    query = ''' INSERT INTO user_info (username,password,create_date,active,upload_counter)
                           VALUES (%s,%s, %s,1,0)
        '''

    cursor.execute(query, (username, password, timestamp))
    cnx.commit()

    # Add error catch here for sql

    return http_response(200, "Registration succeed for the user: " + username)
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_mail import Mail
import logging
from mast.config import Config
import os

db = SQLAlchemy()
bcr = Bcrypt()
csrf = CSRFProtect()
mail = Mail()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'


logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')


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

    try:
        if not os.path.exists(app.config['LANDING_DIR']):
def create_app(config_name):

    from app.models import User, Cart

    app = FlaskAPI(__name__, instance_relative_config=True)
    # overriding Werkzeugs built-in password hashing utilities using Bcrypt.
    bcrypt = Bcrypt(app)

    app.config.from_object(app_config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    @app.route('/')
    def index():
        return "<h1>WSCartAPI</h1>"

    @app.route('/shopping-cart/', methods=['POST', 'GET'])
    def shopping_cart():
        try:
            # get the access token
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                abort(make_response(jsonify(message="Bad Request."), 400))

            access_token = auth_header.split(" ")[1]

            if access_token:
                user_id = User.decode_token(access_token)
                if not isinstance(user_id, str):
                    # Go ahead and handle the request, the user is authed
                    if request.method == "POST":
                        schema_item_chart_data = {
                            "type": "object",
                            "properties": {
                                "item_id": {
                                    "type": "number"
                                },
                                "item_name": {
                                    "type": "string"
                                },
                                "item_price": {
                                    "type": "number"
                                },
                                "amount": {
                                    "type": "number"
                                }
                            },
                        }
                        # Get country based on data user
                        country_iso2 = User.get_user_country(user_id)
                        cart_data = request.data.get('cart_data', '')
                        # Validate the schema and type data input
                        for cdata in cart_data:
                            validate(cdata, schema_item_chart_data)
                        cart = Cart()
                        cart.save(user_id=user_id,
                                  country_iso2=country_iso2,
                                  cart_data=cart_data)
                        response = {'message': 'Cart created successfully.'}
                        data = {
                            'id': cart.id,
                            'date_created': cart.date_created,
                            'date_modified': cart.date_modified,
                            'created_by': cart.created_by,
                            'country_iso2': cart.country_iso2,
                            'status_id': cart.status_id
                        }
                        response['data'] = data
                        return make_response(jsonify(response)), 201

                    else:
                        # GET
                        # get all the cart for this user
                        carts = Cart.get_all(user_id)
                        response = {'message': 'Request success.'}
                        results = []

                        for cart in carts:
                            obj = {
                                'id': cart.id,
                                'date_created': cart.date_created,
                                'date_modified': cart.date_modified,
                                'created_by': cart.created_by,
                                'country_iso2': cart.country_iso2,
                                'status_id': cart.status_id,
                                'items': []
                            }
                            for item in cart.item_carts:
                                icart = {
                                    'id': item.id,
                                    'cart_id': item.cart_id,
                                    'item_id': item.item_id,
                                    'item_name': item.item_name,
                                    'item_price': item.item_price,
                                    'amount': item.amount,
                                }
                                obj['items'].append(icart)
                            results.append(obj)
                        response['data'] = results
                        return make_response(jsonify(response)), 200
                else:
                    # user is not legit, so the payload is an error message
                    message = user_id
                    response = {'message': message}
                    return make_response(jsonify(response)), 401
        except Exception as e:
            response = {
                'message':
                'Request / Input data is not valid. Error in ' + str(e)
            }
            return make_response(jsonify(response)), 500

    @app.route('/shopping-cart/<int:id>', methods=['GET', 'PUT', 'DELETE'])
    def shopping_cart_get(id, **kwargs):

        auth_header = request.headers.get('Authorization')
        if not auth_header:
            abort(make_response(jsonify(message="Bad Request."), 400))

        access_token = auth_header.split(" ")[1]

        if access_token:
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                cart = Cart.get_one(user_id, id)
                if not cart:
                    # Raise an HTTPException with a 404 not found status code
                    abort(
                        make_response(jsonify(message="Cart not found."), 404))

                if request.method == "GET":
                    # GET
                    response = {'message': 'Request success.'}
                    results = {
                        'id': cart.id,
                        'date_created': cart.date_created,
                        'date_modified': cart.date_modified,
                        'created_by': cart.created_by,
                        'country_iso2': cart.country_iso2,
                        'status_id': cart.status_id,
                        'items': []
                    }
                    for item in cart.item_carts:
                        icart = {
                            'id': item.id,
                            'cart_id': item.cart_id,
                            'item_id': item.item_id,
                            'item_name': item.item_name,
                            'item_price': item.item_price,
                            'amount': item.amount,
                        }
                        results['items'].append(icart)
                    response['data'] = results
                    return make_response(jsonify(response)), 200
            else:
                # user is not legit, so the payload is an error message
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401

    # import the authentication blueprint and register it on the app
    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)

    return app
Exemple #10
0
                            x_proto=r_p_count)

# Setup DB with Migrations and bcrypt
DB: SQLAlchemy
DB = SQLAlchemy(APP,
                metadata=MetaData(
                    naming_convention={
                        'pk': 'pk_%(table_name)s',
                        'fk': 'fk_%(table_name)s_%(column_0_name)s',
                        'ix': 'ix_%(table_name)s_%(column_0_name)s',
                        'uq': 'uq_%(table_name)s_%(column_0_name)s',
                        'ck': 'ck_%(table_name)s_%(column_0_name)s',
                    }))

MIGRATE: Migrate = Migrate(APP, DB)
BCRYPT: Bcrypt = Bcrypt(APP)

# Setup JWT
JWT: JWTManager = JWTManager(APP)

# Setup Headers
CORS(APP)

# Setup Celery
# pylint: disable=C0413
from .tasks import make_celery
celery = make_celery(APP)

# Import LoginProviders
# pylint: disable=C0413
from . import auth_providers
Exemple #11
0
 def generate_password_hash(password):
     """
     Returns hash of password
     """
     return Bcrypt().generate_password_hash(password).decode()
Exemple #12
0
import os
from flask import Flask
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from config import basedir
from flask_sqlalchemy import SQLAlchemy

lm = LoginManager()
kingdom = Flask(__name__)
kingdom.config.from_object('config')
db = SQLAlchemy(kingdom)
bcrypt = Bcrypt(kingdom)
lm.init_app(kingdom)
lm.login_view = 'login'
bcrypt = Bcrypt(kingdom)

from kingdom import views, models
Exemple #13
0
 def setUp(self):
     app = flask.Flask(__name__)
     app.config['BCRYPT_LOG_ROUNDS'] = 6
     self.bcrypt = Bcrypt(app)
Exemple #14
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__,
                static_folder="../../frontend/build",
                static_url_path="")
    setup_db(app)
    bcrypt = Bcrypt(app)

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

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

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def index(path):
        if path != "" and os.path.exists(app.static_folder + '/' + path):
            file_name = path.split("/")[-1]
            dir_name = os.path.join(app.static_folder,
                                    "/".join(path.split("/")[:-1]))
            return send_from_directory(dir_name, file_name)
        return send_from_directory(app.static_folder, 'index.html')

# Add endpoints
# Register User

    @app.route('/register', methods=['POST'])
    def register_user():
        print("Registering a user")
        data = request.json
        if ((data.get('email') == '') or (data.get('password') == '')):
            abort(422)
        user = User.query.filter_by(email=data.get('email')).first()
        if not user:
            try:
                user = User(name=data.get('name'),
                            email=data.get('email'),
                            password=bcrypt.generate_password_hash(
                                data.get('password'),
                                BCRYPT_LOG_ROUNDS).decode(),
                            admin=True if data.get('admin') else False)

                # insert the user
                user.insert()
                # generate the auth token
                auth_token = user.encode_auth_token(user.id)
                responseObject = {
                    'status': 'success',
                    'message': 'Successfully registered.',
                    'auth_token': auth_token.decode()
                }
                return jsonify(responseObject), 201
            except Exception as e:
                abort(401)
        else:
            responseObject = {
                'status': 'fail',
                'message': 'User already exists. Please Log in.',
            }
            return jsonify(responseObject), 202

    # except Exception:
    #     abort(422)

        return jsonify({'message': 'success', 'id': system.id})

    @app.route('/login', methods=['POST'])
    def login_user():
        print("Login a user")
        data = request.json
        if ((data.get('email') == '') or (data.get('password') == '')):
            abort(422)
        user = User.query.filter_by(email=data.get('email')).first()
        if not user:
            return jsonify({
                'status': 'fail',
                'message': 'User does not exist.'
            }), 404

        if not bcrypt.check_password_hash(user.password, data.get('password')):
            abort(401)

        try:
            # fetch the user data
            auth_token = user.encode_auth_token(user.id)
            if auth_token:
                responseObject = {
                    'status': 'success',
                    'message': 'Successfully logged in.',
                    'auth_token': auth_token.decode()
                }
                return jsonify(responseObject), 200
        except Exception as e:
            print(e)
            responseObject = {'status': 'fail', 'message': 'Try again'}
            return jsonify(responseObject), 500

    @app.route('/status', methods=['GET'])
    def user_token_status():
        print("User status")
        auth_header = request.headers.get('Authorization')
        if auth_header:
            try:
                auth_token = auth_header.split(" ")[1]
            except IndexError:
                responseObject = {
                    'status': 'fail',
                    'message': 'Bearer token malformed.'
                }
                return jsonify(responseObject), 401
        else:
            auth_token = ''
        if auth_token:
            resp = User.decode_auth_token(auth_token)
            if not isinstance(resp, str):
                user = User.query.filter_by(id=resp).first()
                responseObject = {
                    'status': 'success',
                    'data': {
                        'user_id': user.id,
                        'email': user.email,
                        'admin': user.admin,
                        'registered_on': user.registered_on
                    }
                }
                return jsonify(responseObject), 200
            responseObject = {'status': 'fail', 'message': resp}
            return jsonify(responseObject), 401
        else:
            responseObject = {
                'status': 'fail',
                'message': 'Provide a valid auth token.'
            }
            return jsonify(responseObject), 401

    @app.route('/logout', methods=['POST'])
    @requires_auth
    def logout_user():
        print("User status")
        auth_header = request.headers.get('Authorization')
        auth_token = auth_header.split(" ")[1]
        # mark the token as blacklisted
        blacklist_token = BlacklistToken(token=auth_token)
        try:
            # insert the token
            blacklist_token.insert()
            responseObject = {
                'status': 'success',
                'message': 'Successfully logged out.'
            }
            return jsonify(responseObject), 200
        except Exception as e:
            responseObject = {'status': 'fail', 'message': e}
            return jsonify(responseObject), 200

    @app.route('/users', methods=['GET'])
    @requires_auth
    @requires_admin
    def get_users():
        print("User status")
        users = User.query.order_by(asc(User.registered_on)).all()
        result = []
        for user in users:
            user = user.format()
            result.append(user)
        return jsonify({'data': result, 'status': 'success'})

    @app.route('/users/<int:user_id>', methods=['DELETE'])
    @requires_auth
    @requires_admin
    def delete_users(user_id):
        print("User Delete")
        user = User.query.get(user_id)
        if not user:
            abort(404)
        try:
            user.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": user_id})

# add system

    @app.route('/systems', methods=['POST'])
    def add_system():
        print("adding systems")
        data = request.json
        print(data)
        if ((data.get('name') == '')):
            abort(422)

    # try:
        system = System(name=data.get('name'))
        system.rank = data.get('rank')
        system.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': system.id})

    @app.route('/systems', methods=['PUT'])
    def update_system():
        print("updating systems")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)

    # try:
        system = System.query.get(data.get('id'))
        system.name = data.get('name')
        system.rank = data.get('rank')
        system.update()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': system.id})

# Add Education level

    @app.route('/educations', methods=['POST'])
    def add_education():
        data = request.json
        print(data)
        if ((data.get('name', '') == '') or (data.get('system_id', '') == '')):
            abort(422)
        try:
            education = Education(name=data.get('name'))
            education.system_id = data.get('system_id')
            education.rank = data.get('rank')
            education.insert()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': education.id})

    @app.route('/educations', methods=['PUT'])
    def update_educations():
        print("updating educations")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)

    # try:
        education = Education.query.get(data.get('id'))
        education.name = data.get('name')
        education.rank = data.get('rank')
        education.update()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': education.id})

# Add Category level

    @app.route('/categories', methods=['POST'])
    def add_category():
        data = request.json
        if ((data.get('name', '') == '') or (data.get('class_id', '') == '')):
            abort(422)
        try:
            category = Category(name=data.get('name'))
            category.class_id = data.get('class_id')
            category.rank = data.get('rank')
            category.insert()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': category.id})

    @app.route('/categories', methods=['PUT'])
    def update_categories():
        print("updating categories")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)

    # try:
        category = Category.query.get(data.get('id'))
        category.name = data.get('name')
        category.rank = data.get('rank')
        category.update()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': category.id})

# Add Sub Category level

    @app.route('/sub_categories', methods=['POST'])
    def add_sub_category():
        data = request.json
        education_id = data.get('education_id', None)

        if ((data.get('name', '') == '')
                or (data.get('education_id', '') == '')):
            abort(422)
        try:
            sub_category = SubCategory(name=data.get('name'))
            sub_category.education_id = data.get('education_id')
            sub_category.rank = data.get('rank')
            sub_category.insert()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': sub_category.id})

    # Add Sub Category level

    @app.route('/sub_categories', methods=['PUT'])
    def update_subub_category():
        data = request.json

        if ((data.get('name', '') == '') or (data.get('id', '') == '')):
            abort(422)
        try:
            sub_category = SubCategory.query.get(data.get('id'))
            sub_category.name = data.get('name')
            sub_category.rank = data.get('rank')
            sub_category.update()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': sub_category.id})

# Add Class level

    @app.route('/class', methods=['POST'])
    def add_class():
        data = request.json
        education_id = data.get('education_id', None)
        sub_category_id = data.get('sub_category_id', None)

        if ((data.get('name', '') == '')):
            abort(422)
        try:
            classes = Classes(name=data.get('name'))
            classes.rank = data.get('rank')
            if education_id or sub_category_id:
                if education_id:
                    classes.education_id = int(data.get('education_id'))
                if sub_category_id:
                    classes.sub_category_id = int(data.get('sub_category_id'))
            else:
                abort(422)
        except Exception:
            abort(422)
        classes.insert()

        return jsonify({'message': 'success', 'id': classes.id})

    @app.route('/class', methods=['PUT'])
    def update_class():
        print("updating class")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)

    # try:
        classes = Classes.query.get(data.get('id'))
        classes.name = data.get('name')
        classes.rank = data.get('rank')
        classes.update()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': classes.id})

# Exams level

    @app.route('/exams', methods=['POST'])
    def add_exams():
        data = request.json
        education_id = data.get('education_id', None)
        sub_category_id = data.get('sub_category_id', None)

        if ((data.get('name', '') == '')):
            abort(422)
        try:
            exams = Exams(name=data.get('name'))
            exams.rank = data.get('rank')
            if education_id or sub_category_id:
                if education_id:
                    exams.education_id = int(data.get('education_id'))
                if sub_category_id:
                    exams.sub_category_id = int(data.get('sub_category_id'))
            else:
                abort(422)
        except Exception:
            abort(422)
        exams.insert()

        return jsonify({'message': 'success', 'id': exams.id})

    @app.route('/exams', methods=['PUT'])
    def update_exams():
        print("updating exams")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)
        try:
            exams = Exams.query.get(data.get('id'))
            exams.name = data.get('name')
            exams.rank = data.get('rank')
            exams.update()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': exams.id})

    @app.route('/exams', methods=['GET'])
    def get_exams():
        education_id = request.args.get('education_id')
        sub_category_id = request.args.get('sub_category_id')

        if sub_category_id:
            exams = Exams.query.order_by(asc(
                Exams.rank)).filter(Exams.sub_category_id == sub_category_id)
        elif education_id:
            exams = Exams.query.order_by(asc(
                Exams.rank)).filter(Exams.education_id == education_id)
        else:
            exams = Exams.query.order_by(asc(Exams.rank)).all()
        result = []
        for an_exam in exams:
            an_exam = an_exam.format()
            exam_type = an_exam.get('exam_type', [])
            e_type_list = []
            vid_list = []
            for e_type in exam_type:
                e_type = e_type.format()
                e_type.pop('revision_videos')
                e_type.pop('timetables')
                e_type_list.append(e_type)
            for v in an_exam.get('revision_videos'):
                v = v.format()
                vid_list.append(v)
            an_exam['exam_type'] = e_type_list
            an_exam['exam_levels'] = an_exam.pop('exam_type')
            an_exam['revision_videos'] = vid_list
            result.append(an_exam)
            print(result)
        return jsonify({'data': result, 'message': 'success'})

# Add Exam level

    @app.route('/exam_level', methods=['POST'])
    def add_exam_level():
        data = request.json
        if ((data.get('name', '') == '') or (data.get('exam_id', '') == '')):
            abort(422)
        try:
            exam_level = ExamType(name=data.get('name'))
            exam_level.exam_id = data.get('exam_id')
            exam_level.rank = data.get('rank')
            exam_level.insert()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': exam_level.id})

    @app.route('/exam_level', methods=['PUT'])
    def update_exam_level():
        print("updating exam_level")
        data = request.json
        print(data)
        if ((data.get('name') == '') or (data.get('id') == '')):
            abort(422)

    # try:
        exam_level = ExamType.query.get(data.get('id'))
        exam_level.name = data.get('name')
        exam_level.rank = data.get('rank')
        exam_level.update()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': exam_level.id})

    @app.route('/exam_level', methods=['GET'])
    def get_exam_level():
        exam_id = request.args.get('exam_id')
        if exam_id:
            exam_level = ExamType.query.order_by(asc(
                ExamType.rank)).filter(ExamType.exam_id == exam_id)
        else:
            exam_level = ExamType.query.order_by(asc(ExamType.rank)).all()
        result = []
        for an_exam_level in exam_level:
            an_exam_level = an_exam_level.format()
            videos = an_exam_level.get('revision_videos', [])
            an_exam_level.pop('timetables')
            video_list = []
            for video in videos:
                video = video.format()
                video_list.append(video)
            an_exam_level['revision_videos'] = video_list
            result.append(an_exam_level)
        return jsonify({'data': result, 'message': 'success'})

# Add Category level

    @app.route('/subject', methods=['POST'])
    def add_subject():
        data = request.json
        if ((data.get('name', '') == '') or (data.get('class_id', '') == '')):
            abort(422)
        try:
            subject = Subject(name=data.get('name'))
            subject.class_id = data.get('class_id')
            subject.rank = data.get('rank')
            subject.insert()
        except Exception:
            abort(422)

        return jsonify({'message': 'success', 'id': subject.id})

    @app.route('/video', methods=['POST'])
    def add_video():
        from datetime import datetime
        data = request.form
        data = data.to_dict(flat=False)
        print(request.files)
        print(data)
        if ('file' not in request.files) and (data.get('link', '')[0] == ''):
            abort(400)
        link = data.get('link', '')
        if ((data.get('description', '')[0] == '')):
            abort(422)
        description = data.get('description', '')
        date = data.get('time', '')
        link = link[0].replace("watch?v=", "embed/")
        # try:
        date = datetime.now()
        up_video = Video(name=data.get('name')[0],
                         link=link,
                         description=description[0],
                         date=date)
        if (data.get('class_id')[0] != '' and data.get('class_id')[0] != '0'):
            class_id = int(data.get('class_id')[0])
            up_class = Classes.query.filter(Classes.id == class_id).one()
            if up_class.categories and not (data.get('category_id')[0] != ''
                                            and
                                            data.get('category_id')[0] != '0'):
                abort(422, description="Please select a level or Cycle")
        up_video.class_id = data.get('class_id')[0] if (
            data.get('class_id')[0] != ''
            and data.get('class_id')[0] != '0') else None
        up_video.category_id = data.get('category_id')[0] if (
            data.get('category_id')[0] != ''
            and data.get('category_id')[0] != '0') else None
        if up_video.class_id == None and up_video.category_id == None:
            abort(422, description="Please select a Class or level/Cycle")
        up_video.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': up_video.id})

    @app.route('/revision_video', methods=['POST'])
    def add_revision_video():
        from datetime import datetime
        data = request.form
        data = data.to_dict(flat=False)
        print(request.files)
        print(data)
        if ('file' not in request.files) and (data.get('link', '')[0] == ''):
            abort(400)
        link = data.get('link', '')
        if ((data.get('description', '')[0] == '')):
            abort(422)
        description = data.get('description', '')
        date = data.get('time', '')
        link = link[0].replace("watch?v=", "embed/")
        # try:
        date = datetime.now()
        exam_id = None
        up_video = Video(name=data.get('name')[0],
                         link=link,
                         description=description[0],
                         date=date)
        if (data.get('exam_id')[0] != '' and data.get('exam_id')[0] != '0'):
            exam_id = int(data.get('exam_id')[0])
            up_exam = Exams.query.filter(Exams.id == exam_id).one()
            if up_exam.exam_type and not (data.get('exam_type_id')[0] != '' and
                                          data.get('exam_type_id')[0] != '0'):
                abort(422, description="Please select a level or Cycle")
        up_video.exam_id = exam_id
        up_video.exam_type_id = data.get('exam_type_id')[0] if (
            data.get('exam_type_id')[0] != ''
            and data.get('exam_type_id')[0] != '0') else None
        if up_video.exam_id == None and up_video.exam_type_id == None:
            abort(422, description="Please select a Exam Type or level/Cycle")
        up_video.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success', 'id': up_video.id})

# Get endpoints

    @app.route('/educations', methods=['GET'])
    def get_education():
        system_id = request.args.get('system_id')
        if system_id:
            educations = Education.query.order_by(asc(
                Education.rank)).filter(Education.system_id == system_id)
        else:
            educations = Education.query.order_by(asc(Education.rank)).all()
        result = []
        # print(educations)
        for education in educations:
            sm_edu = education.format()
            category_lists = sm_edu.get('category_list')
            result.append(sm_edu)
            classes = sm_edu.get('class_list', [])
            exams = sm_edu.get('exam_list', [])
            class_list = []
            exam_list = []
            for s_class in classes:
                s_class = s_class.format()
                s_class.pop('categories')
                class_list.append(s_class)
            sub_categories = sm_edu.get('sub_categories', [])
            sub_categories = []
            for s_category in sub_categories:
                s_category = s_category.format()
                s_category.pop('class_list')
                sub_categories.append(s_category)
            sm_edu['class_list'] = class_list
            sm_edu['sub_categories'] = sub_categories
            for exam in exams:
                exam = exam.format()
                exam.pop('exam_type')
                exam.pop('revision_videos')
                exam_list.append(exam)
            sm_edu['exam_list'] = exam_list
        from pprint import pprint
        pprint(educations)

        return jsonify({'data': result, 'message': 'success'})

    @app.route('/categories', methods=['GET'])
    def get_categories():
        class_id = request.args.get('class_id')
        if class_id:
            categories = Category.query.order_by(asc(
                Category.rank)).filter(Category.class_id == class_id)
        else:
            categories = Category.query.order_by(asc(Category.rank)).all()
        result = []
        for category in categories:
            category = category.format()
            videos = category.get('videos', [])
            videos = []
            for sub_cat in videos:
                sub_cat = sub_cat.format()
                videos.append(sub_cat)
            category['videos'] = videos
            result.append(category)
        return jsonify({'data': result, 'message': 'success'})

    @app.route('/sub_categories', methods=['GET'])
    def get_sub_categories():
        education_id = request.args.get('education_id')
        if education_id:
            categories = SubCategory.query.order_by(asc(
                SubCategory.rank)).filter(
                    SubCategory.education_id == education_id)
        else:
            categories = SubCategory.query.order_by(asc(
                SubCategory.rank)).all()
        result = []
        for category in categories:
            category = category.format()
            classes = category.get('class_list', [])
            class_list = []
            for s_class in classes:
                s_class = s_class.format()
                s_class.pop('categories')
                class_list.append(s_class)
            category['class_list'] = class_list
            result.append(category)
            print(category)
        return jsonify({'data': result, 'message': 'success'})

    @app.route('/class', methods=['GET'])
    def get_classes():
        education_id = request.args.get('education_id')
        sub_category_id = request.args.get('sub_category_id')

        if sub_category_id:
            classes = Classes.query.order_by(asc(Classes.rank)).filter(
                Classes.sub_category_id == sub_category_id)
        elif education_id:
            classes = Classes.query.order_by(asc(
                Classes.rank)).filter(Classes.education_id == education_id)
        else:
            classes = Classes.query.order_by(asc(Classes.rank)).all()
        result = []
        for some_class in classes:
            some_class = some_class.format()
            categories = some_class.get('categories', [])
            cat_list = []
            vid_list = []
            for cat in categories:
                cat = cat.format()
                cat.pop('videos')
                cat_list.append(cat)
            some_class['categories'] = cat_list
            result.append(some_class)

        return jsonify({'data': result, 'message': 'success'})

    @app.route('/subject', methods=['GET'])
    def get_subject():
        class_id = request.args.get('class_id')

        if class_id:
            subjects = Subject.query.order_by(asc(
                Subject.name)).filter(Subject.class_id == class_id)
        else:
            subjects = Subject.query.all()
        result = []
        for some_subject in subjects:
            some_subject = some_subject.format()
            some_subject.pop('videos')
            result.append(some_subject)

        return jsonify({'data': result, 'message': 'success'})

    def get_videos_by_education_id(education_id, revision=False):
        education = Education.query.get(education_id)
        video_list = []
        if not revision:
            for a_class in education.class_list:
                videos = Video.query.filter(
                    Video.class_id == a_class.id).order_by(asc(Video.date))
                video_list += videos
        else:
            for exam in education.exam_list:
                videos = Video.query.filter(Video.exam_id == exam.id).order_by(
                    asc(Video.date))
                video_list += videos
        video_list = video_list[:10] if len(video_list) > 10 else video_list
        return video_list

    @app.route('/videos', methods=['GET'])
    def get_video():
        class_id = request.args.get('class_id')
        category_id = request.args.get('category_id')
        # adding code that gets all videos based on a particular education id
        education_id = request.args.get('education_id')
        exam_id = request.args.get('exam_id')
        exam_type_id = request.args.get('exam_level_id')
        revision = request.args.get('revision')
        revision = True if revision == 'true' else False
        if education_id:
            videos = get_videos_by_education_id(education_id, revision)
        elif category_id:
            videos = Video.query.filter(Video.category_id == category_id)
        elif class_id:
            videos = Video.query.filter(Video.class_id == class_id)
        elif exam_id:
            videos = Video.query.filter(Video.exam_id == exam_id)
        elif exam_type_id:
            videos = Video.query.filter(Video.exam_type_id == exam_type_id)
        else:
            videos = Video.query.all()
        result = []
        links = []
        for some_video in videos:
            some_video = some_video.format()
            if some_video.get('link') in links:
                continue
            links.append(some_video.get('link'))
            result.append(some_video)

        return jsonify({'data': result, 'message': 'success'})

    @app.route('/systems', methods=['GET'])
    def get_systems():
        systems = System.query.order_by(asc(System.rank)).all()
        result = []
        for system in systems:
            edu = []
            for ed in system.education_list:
                s_ed = ed.format()
                s = s_ed.pop('class_list')
                s_ed.pop('exam_list')
                sub_cat = []
                for item in s_ed['sub_categories']:
                    t = item.format()
                    t.pop('class_list')
                    sub_cat.append(t)
                s_ed['sub_categories'] = sub_cat
                edu.append(s_ed)
            result.append({
                'name': system.name,
                'id': system.id,
                'rank': system.rank,
                'education_list': edu
            })

        return jsonify({'data': result, 'message': 'success'})

    @app.route('/systems/<int:system_id>', methods=['DELETE'])
    def delete_system(system_id):
        system = System.query.get(system_id)
        if not system:
            abort(404)
        try:
            system.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": system_id})

    @app.route('/educations/<int:education_id>', methods=['DELETE'])
    def delete_education(education_id):
        education = Education.query.get(education_id)
        if not education:
            abort(404)
        try:
            education.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, 'deleted': education_id})

    @app.route('/categories/<int:category_id>', methods=['DELETE'])
    def delete_category(category_id):
        category = Category.query.get(category_id)
        if not category:
            abort(404)
        try:
            category.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, 'deleted': category_id})

    @app.route('/sub_categories/<int:sub_category_id>', methods=['DELETE'])
    def delete_sub_category(sub_category_id):
        sub_category = SubCategory.query.get(sub_category_id)
        if not sub_category:
            abort(404)
        try:
            sub_category.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": sub_category_id})

    @app.route('/class/<int:class_id>', methods=['DELETE'])
    def delete_class(class_id):
        classes = Classes.query.get(class_id)
        if not classes:
            abort(404)
        try:
            classes.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": class_id})

    @app.route('/subject/<int:subject_id>', methods=['DELETE'])
    def delete_subject(subject_id):
        subject = Subject.query.get(subject_id)
        if not subject:
            abort(404)
        try:
            subject.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": subject_id})

    @app.route('/video/<int:video_id>', methods=['DELETE'])
    def delete_video(video_id):
        video = Video.query.get(video_id)
        if not video:
            abort(404)
        try:
            video.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": video_id})

    @app.route('/exams/<int:exams_id>', methods=['DELETE'])
    def delete_exams(exams_id):
        exams = Exams.query.get(exams_id)
        if not exams:
            abort(404)
        try:
            exams.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": exams_id})

    @app.route('/exam_level/<int:exams_type_id>', methods=['DELETE'])
    def delete_exam_type(exams_type_id):
        exam_level = ExamType.query.get(exams_type_id)
        if not exam_level:
            abort(404)
        try:
            exam_level.delete()
        except Exception:
            abort(500)
        return jsonify({'success': True, "deleted": exams_type_id})

    # @app.route('/system', methods=['GET'])
    # def get_categories():
    #     categories = Category.query.all()
    #     result = {}
    #     for category in categories:
    #         result[category.id] = category.type

    #     return jsonify({'categories': result})

    # def question_get_return(page, category_id=None, search_term=None):
    #     """
    #     Generic question search and formatter, that always return the
    #     first page of the results if no page number is specified
    #     """
    #     num_quest = 10
    #     if category_id:
    #         # here we are handling the case where we need questions
    #         # on a particular category
    #         questions = Question.query.filter(
    #             Question.category == category_id).paginate(
    #             max_per_page=num_quest, page=page)
    #         category = Category.query.get(category_id)
    #         if not category:
    #             abort(404)
    #         category_type = category.type
    #     elif search_term:
    #         # Here we are handling the search for a question not
    #         # case sensitive search if the term is a substring of the question
    #         questions = Question.query.filter(
    #             func.lower(Question.question).contains(
    #                 search_term.lower())).paginate(
    #             max_per_page=num_quest, page=page)
    #         category_type = ' '
    #     else:
    #         questions = Question.query.paginate(
    #             max_per_page=num_quest, page=page)
    #         category_type = ' '

    #     questions = [dict(question.format()) for question in questions.items]
    #     categories = Category.query.all()
    #     category_result = {}
    #     for category in categories:
    #         category_result[category.id] = category.type

    #     result = {
    #         "questions": questions,
    #         "total_questions": len(questions),
    #         "current_category": category_type,
    #         'categories': category_result
    #     }

    #     return result

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

        video_id = request.args.get('video_id', int)

        if not video_id:
            abort(422)

        result = Question.query.filter(Question.video_id == video_id).order_by(
            asc(Question.date)).all()

        result_list = []
        for question in result:
            question = question.format()
            answer_list = []
            for ans in question.pop('answers'):
                ans = ans.format()
                answer_list.append(ans)
            question['answers'] = answer_list
            result_list.append(question)

        print(result_list)

        return jsonify({'data': result_list, 'message': 'success'})

    @app.route('/questions/<int:question_id>', methods=['DELETE'])
    def delete_question(question_id):
        question = Question.query.get(question_id)
        if not question:
            abort(404)
        try:
            question.delete()
        except Exception:
            abort(500)
        return jsonify({'message': "Delete Successful"})

    def sms_notif(message):
        from twilio.rest import Client

        # Your Account Sid and Auth Token from twilio.com/console
        # DANGER! This is insecure. See http://twil.io/secure
        account_sid = 'AC60a17f8d85005353a7012cac4e749ae6'
        auth_token = 'e4721530aaf8ce3eec025255586bf827'
        client = Client(account_sid, auth_token)

        message = client.messages.create(body=message,
                                         from_='+12058097816',
                                         to='+237679904987')
        print('successfully sent the message')

    @app.route('/questions', methods=['POST'])
    def add_question():
        data = request.json
        if (data.get('question') == '') or (data.get('video_id') == ''):
            abort(422)

        video = Video.query.get(data.get('video_id'))
        message = f"video:{video.name} has question:{data.get('question', '')}"
        try:
            date = datetime.now()
            question = Question(question=data.get('question', ''),
                                date=date,
                                video_id=data.get('video_id'))
            question.insert()
        except Exception:
            abort(422)
        sms_notif(message)

        return jsonify({'message': 'success'})

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

        question_id = request.args.get('question_id', int)

        if not question_id:
            abort(422)

        result = Answer.query.order_by(asc(Answer.date)).all()

        result_list = []
        for answer in result:
            answer = answer.format()
            result_list.append(answer)

        return jsonify({'data': result_list, 'message': 'success'})

    @app.route('/answers/<int:answer_id>', methods=['DELETE'])
    def delete_answer(answer_id):
        answer = Answer.query.get(answer_id)
        if not answer:
            abort(404)
        try:
            answer.delete()
        except Exception:
            abort(500)
        return jsonify({'message': "Delete Successful"})

    @app.route('/answers', methods=['POST'])
    def add_answer():
        data = request.json
        if (data.get('answer') == '') or (data.get('question_id') == ''):
            abort(422)

    # try:
        date = datetime.now()
        answer = Answer(answer=data.get('answer', ''),
                        date=date,
                        question_id=data.get('question_id'))
        answer.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success'})

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

        question_id = request.args.get('question_id', int)

        if not question_id:
            abort(422)

        result = Number.query.get().one_or_none()

        if result:
            result = result.format()
            result['message'] = 'success'
        else:
            result['message'] = 'fail'

        return jsonify(result)

    @app.route('/number/<int:number_id>', methods=['DELETE'])
    def delete_number(number_id):
        number = Number.query.get(number_id)
        if not number:
            abort(404)
        try:
            number.delete()
        except Exception:
            abort(500)
        return jsonify({'message': "Delete Successful"})

    @app.route('/number', methods=['POST'])
    def add_nuber():
        data = request.json
        if (data.get('number') == '') or (data.get('question_id') == ''):
            abort(422)

    # try:
        date = datetime.now()
        number = Number(number=data.get('number', ''))
        number.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'message': 'success'})

    @app.route('/timetable', methods=['POST'])
    def add_timetable():
        data = request.json
        if (data.get('name') == '') or (data.get('link') == '')\
                or (data.get('time') == '') or (data.get('teacher_id') == '')\
                    or (data.get('start_time') == '') or (data.get('end_time') == '')\
                        or (data.get('signup_time')) == '':
            abort(422)
        date = datetime.strptime(data.get('time'), "%Y-%m-%d %H:%M")
        signup_time = datetime.strptime(data.get('signup_time'),
                                        "%Y-%m-%d %H:%M")
        name = data.get('name')
        link = data.get('link')
        exam_id = data.get('exam_id')
        teacher_id = data.get('teacher_id')
        start_time = data.get('start_time')
        end_time = data.get('end_time')
        studio = data.get('studio')
        exam_type_id = data.get('exam_level_id') if data.get(
            'exam_level_id') else None
        # try:
        timetable = TimeTable(name=name,
                              link=link,
                              time=date,
                              teacher_id=teacher_id,
                              exam_id=exam_id,
                              exam_type_id=exam_type_id,
                              start_time=start_time,
                              end_time=end_time,
                              signup_time=signup_time,
                              studio=studio)
        timetable.insert()
        # except Exception:
        #     abort(422)

        return jsonify({'status': 'success', 'id': timetable.id})

    @app.route('/timetable', methods=['GET'])
    def get_timetable():
        params = request.args
        exam_id = params.get('exam_id', type=int, default=None)
        exam_type_id = params.get('exam_level_id', type=int, default=None)
        teacher_id = params.get('teacher_id', type=int, default=None)
        accepted = params.get('accepted', type=bool, default=None)
        print(params.get('time', type=str, default=None))
        date = datetime.strptime(params.get('time', type=str),
                                 timetable_time_format) if params.get(
                                     'time', type=str) else None

        if teacher_id:
            teacher = User.query.get(teacher_id)
            teacher_id = None if teacher.format()['admin'] else teacher_id
        if teacher_id and exam_id and exam_type_id and accepted:
            timetable = TimeTable.query.filter(
                TimeTable.teacher_id == teacher_id,
                TimeTable.exam_type_id == exam_type_id,
                TimeTable.accepted == accepted)
        elif teacher_id and exam_id and accepted and not exam_type_id:
            timetable = TimeTable.query.filter(
                TimeTable.teacher_id == teacher_id,
                TimeTable.exam_id == exam_id, TimeTable.accepted == accepted)
        elif teacher_id and exam_id and not accepted and not exam_type_id:
            timetable = TimeTable.query.filter(
                TimeTable.teacher_id == teacher_id,
                TimeTable.exam_id == exam_id)
        elif teacher_id and exam_type_id and not accepted and not exam_id:
            timetable = TimeTable.query.filter(
                TimeTable.teacher_id == teacher_id,
                TimeTable.exam_type_id == exam_type_id)
        elif accepted and exam_type_id and not teacher_id and not exam_id:
            timetable = TimeTable.query.filter(
                TimeTable.accepted == accepted,
                TimeTable.exam_type_id == exam_type_id)
        elif accepted and exam_id and not teacher_id and not exam_type_id:
            timetable = TimeTable.query.filter(TimeTable.accepted == accepted,
                                               TimeTable.exam_id == exam_id)
        elif exam_type_id:
            timetable = TimeTable.query.filter(
                TimeTable.exam_type_id == exam_type_id)
        elif exam_id:
            timetable = TimeTable.query.filter(TimeTable.exam_id == exam_id)
        elif teacher_id:
            timetable = TimeTable.query.filter(
                TimeTable.teacher_id == teacher_id)
        else:
            abort(422)
        timetable = timetable.filter(
            TimeTable.time >= date,
            TimeTable.time <= date + timedelta(hours=23, minutes=59))

        result = []
        for a_timetable in timetable:
            ttable = a_timetable.format()
            # students = []
            # for student in ttable.get('students', []):
            #     students.append(student.format())
            # ttable['students'] = students
            result.append(ttable)
        return jsonify({
            'data': result,
            'status': 'success',
        })

    @app.route('/timetable/accept', methods=['PUT'])
    @requires_auth
    def accept_timetable():
        data = request.json
        if (data.get('id') == ''):
            abort(422)
        timetable = TimeTable.query.filter(
            TimeTable.id == data.get('id')).first()

        try:
            timetable.accepted = True if not timetable.accepted else False
            timetable.update()
        except Exception:
            abort(422)

        return jsonify({'status': 'success'})

    @app.route('/timetable', methods=['PUT'])
    @requires_auth
    def update_timetable():
        data = request.json
        if (data.get('id') == ''):
            abort(422)
        timetable = TimeTable.query.filter(
            TimeTable.id == data.get('id')).first()

        try:
            timetable.name = data.get('name') if data.get(
                'name') else timetable.name
            timetable.link = data.get('link') if data.get(
                'link') else timetable.link
            timetable.start_time = data.get('start_time') if data.get(
                'start_time') else timetable.start_time
            timetable.end_time = data.get('end_time') if data.get(
                'end_time') else timetable.end_time
            timetable.signup_time = datetime.strptime(
                data.get('signup_time'), "%Y-%m-%d %H:%M") if data.get(
                    'signup_time') else timetable.signup_time
            timetable.studio = data.get('studio') if data.get(
                'studio') else timetable.studio
            timetable.update()
        except Exception:
            abort(422)

        return jsonify({'status': 'success'})

    @app.route('/timetable/<int:timetable_id>', methods=['DELETE'])
    @requires_auth
    @requires_admin
    def delete_timetable(timetable_id):
        timetable = TimeTable.query.get(timetable_id)
        if not timetable:
            abort(404)
        try:
            timetable.delete()
        except Exception:
            abort(500)
        return jsonify({'message': "Delete Successful"})

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

        timetable_id = request.args.get('timetable_id', int)

        if not timetable_id:
            abort(422)

        students = Student.query.get().one_or_none()

        result = []
        if students:
            for student in students:
                result.append(result.format())
        else:
            return jsonify({'students': result, 'status': 'fail'})

        return jsonify({'students': result, 'status': 'pass'})

    @app.route('/student/<int:student_id>', methods=['DELETE'])
    def delete_student(student_id):
        student = Student.query.get(student_id)
        if not student:
            abort(404)
        try:
            student.delete()
        except Exception:
            abort(500)
        return jsonify({'message': "Delete Successful"})

    @app.route('/student', methods=['POST'])
    def add_student():
        data = request.json
        print(data)
        if (data.get('student') == '') or (data.get('timetable_id') == ''):
            abort(422)
        student = Student.query.get(data.get('student'))
        if student:
            return jsonify({
                'message':
                'You are already signedup / Vous êtes déjà inscrit'
            })
        try:
            student = Student(student=data.get('student'),
                              timetable_id=data.get('timetable_id'))
            student.insert()
        except Exception:
            abort(422)

        return jsonify({
            'message':
            "Vous vous êtes inscrit avec succès / You have successfully signed Up"
        })

    # @app.route('/questions/search', methods=['POST'])
    # def search_question():
    #     search_term = request.json.get('searchTerm', '')
    #     result = question_get_return(1, search_term=search_term)
    #     if not result.get('questions'):
    #         abort(404)

    #     return jsonify(result)

    # @app.route("/categories/<int:category_id>/questions", methods=['GET'])
    # def get_question_per_category(category_id):
    #     result = question_get_return(1, category_id=category_id)
    #     if not result:
    #         abort(404)

    #     return jsonify(result)

    # @app.route('/quizzes', methods=['POST'])
    # def quizes():
    #     data = request.json
    #     previous_questions_list = data.get('previous_questions')
    #     quiz_category = data.get('quiz_category')

    #     if not quiz_category:
    #         abort(422)

    #     question = Question.query.filter(
    #         Question.category == quiz_category.get('id')).filter(
    #         Question.id.notin_(previous_questions_list)).order_by(
    #         func.random()).limit(1).all()

    #     if question:
    #         question = dict(question[0].format())
    #     return jsonify({'question': question})

    @app.errorhandler(404)
    def not_found(error):
        if request.path.startswith("/api/"):
            return jsonify({'status': 'fail', 'message': 'Not Found'}), 404
        return send_from_directory(app.static_folder, 'index.html')

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            'status': 'fail',
            'message': f'Unprocessable {str(error)}'
        }), 422

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({'status': 'fail', 'message': 'Bad Request'}), 400

    @app.errorhandler(401)
    def unauthorized(error):
        return jsonify({
            'status': 'fail',
            'message': 'Your password is not correct.'
        }), 401

    @app.errorhandler(500)
    def sever_error(error):
        return jsonify({'status': 'fail', 'message': 'Sever Error'}), 500

    return app
def upload_file_api():
    '''
    This function provides users with an api to upload an image together with given username and password.
    The function will first check if the user info is correct and if it's correct, the function will keep a record
    of the image and an OpenCV-processed image in the database, with the proper naming scheme.
   The function can raise exceptions if there are any of the following problems: no file selected; filename too long;
   wrong extension type; file too large.
   If the uploaded is valid then we will connect to the database and create a record. First, we assign systematic names
   to the image and its processed image depending on the user id and their upload counter. Second, we save the image
   to the cloud, process it through OpenCV and then save the processed image to the cloud. Third, we gather all
   information and update our file name table in the database.
   Last we increase the upload counter by 1 and update it.
    :return: Json string with status code and information string
    '''
    bcrypt = Bcrypt(webapp)
    try:
        username = request.form['username']
        password = request.form['password']

        if request.method == 'POST':

            # check if the post request has the file part
            if 'file' not in request.files:
                return http_response(404, "No file upload in the request!")

            try:
                file = request.files['file']
            except RequestEntityTooLarge:
                return http_response(
                    413, "Image too large, file cannot larger than 5mb")

            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                return http_response(404, "No file selected!")
            if len(file.filename) >= 50:
                return http_response(400, "File name too long")
            if file and allowed_file(file.filename):

                #===================================================#
                #======Till this step the file is good to process===#
                # ===================================================#

                #rename the upload img as: userpid_useruploadcounter_imagename.extention
                userFileName = secure_filename(
                    file.filename)  # example: example.jpg

                # connect to database
                cnx = get_database()
                cursor = cnx.cursor()
                query1 = "SELECT password, uid, upload_counter FROM user_info WHERE username = %s and active = 1"
                cursor.execute(query1, (username, ))
                results = cursor.fetchall()

                if len(results) != 1:
                    return http_response(400, "Invalid username or password")

                correctPwd = bcrypt.check_password_hash(
                    results[0][0], password)
                if correctPwd:

                    uid = results[0][1]
                    upload_counter = results[0][2]

                    cloudSaveFilename = str(uid) + "_" + str(
                        upload_counter
                    ) + "_" + userFileName  #example: 12_1_example.jpg
                    cloudProcessedFileName = "p_" + cloudSaveFilename
                    userDownloadFileName = "processed_" + userFileName

                    # save uploaded img to cloud drive
                    file.save(
                        os.path.join(webapp.config['UPLOAD_FOLDER'],
                                     cloudSaveFilename))

                    #process the img from cloud drive, it will process the img in (img_path) and save processed img in same path
                    Opencv.imageProcess(UPLOAD_FOLDER, cloudSaveFilename,
                                        cloudProcessedFileName)

                    #prepare for values for sql
                    fileName = userFileName
                    processedFileName = "processed_" + userFileName
                    uploadImagePath = UPLOAD_FOLDER + cloudSaveFilename
                    processedImagePath = UPLOAD_FOLDER + cloudProcessedFileName
                    ts = time.time()
                    timeStamp = datetime.datetime.fromtimestamp(ts).strftime(
                        '%Y-%m-%d %H:%M:%S')

                    #update file_name table
                    query2 = "INSERT INTO file_info (uid, file_name, upload_image_path, cloud_image_name, processed_image_path, cloud_processed_image_name, create_time) VALUES (%s, %s, %s, %s, %s , %s, %s)"
                    data = (uid, fileName, uploadImagePath, cloudSaveFilename,
                            processedImagePath, cloudProcessedFileName,
                            timeStamp)
                    cursor.execute(query2, data)
                    cnx.commit()

                    #get the newest user upload counter for database
                    query3 = "SELECT upload_counter FROM user_info WHERE username = %s and active = 1"
                    cursor.execute(query3, (username, ))
                    results = cursor.fetchall()
                    upload_counter = results[0][0]

                    #update user_table
                    query4 = "UPDATE user_info SET upload_counter = %s WHERE uid = %s"
                    cursor.execute(query4, (upload_counter + 1, uid))
                    cnx.commit()

                    print("==>process succeed")
                    # get the image path for both image_before and image_after
                    return http_response(200, "Image Successfully Processed!")

                else:
                    return http_response(400, "Invalid username or password")

            else:
                return http_response(
                    400, "Not a Correct File Type!" +
                    str(file and allowed_file(file.filename)) + "|" +
                    file.filename)
        return http_response(123, "Unsupported method!")

    except Exception as ex:
        if '413' in str(ex):
            return http_response(
                413, "Image too large, file cannot larger than 5mb")
        return http_response(400, str(ex))
Exemple #16
0
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy


db = SQLAlchemy()    #database initialization
bcrypt = Bcrypt()   #for encryption
def create_app():
    """Set up the application."""
    flask_app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    flask_app.config.from_object(__name__)
    flask_app.config['LOCAL'] = local
    flask_app.debug = CONFIG_SERVICES['debug']
    flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    flask_app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    SesEmail.SIGNING_KEY = CONFIG_BROKER['email_token_key']
    SesEmail.is_local = local
    if SesEmail.is_local:
        SesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = flask_app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id")
    else:
        CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
             allow_headers="*", expose_headers="X-Session-Id")
    # Enable DB session table handling
    flask_app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(flask_app)

    @flask_app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @flask_app.before_request
    def before_request():
        # Set global value for local
        g.is_local = local
        sess = GlobalDB.db().session
        # setup user
        g.user = None
        if session.get('name') is not None:
            g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none()

    # Root will point to index.html
    @flask_app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @flask_app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @flask_app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(flask_app, bcrypt)

    add_file_routes(flask_app, CONFIG_BROKER['aws_create_temp_credentials'], local, broker_file_path)
    add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(flask_app)
    add_exception_handlers(flask_app)
    return flask_app
Exemple #18
0
def create(db):

    from interNect.models import User, Post, Pending, Company
    from flask_bcrypt import Bcrypt
    db.create_all()

    bcrypt = Bcrypt()
    password = bcrypt.generate_password_hash('1234').decode('utf-8')

    user = User(username='******',
                email='*****@*****.**',
                password=password,
                lname="Aman",
                fname="aman",
                gender='male')
    u = User(username='******',
             email='*****@*****.**',
             password=password,
             lname="Aman",
             fname="aman",
             gender='male')

    c = Company(company_name="Google", email="*****@*****.**", password=password)
    company = Company(company_name="Microsoft",
                      email="*****@*****.**",
                      password=password)

    db.session.add(user)
    db.session.add(u)
    db.session.add(c)
    db.session.add(company)

    db.session.commit()
    post = Post(
        title="IT intern",
        content=
        "Our Software Engineering company known for innovative technology seeks a self-directed IT intern with a passion for technology, collaboration, and creative problem-solving. The intern will actively contribute to meaningful projects and work closely with a mentor and with senior leadership.",
        company_id=1)
    post2 = Post(
        title="Software Engineering Intern",
        content=
        "Our Company seeks an intern with experience in software design, coding and debugging. The intern will gain exciting real-world software engineering experience at a thriving company. We frequently work in small teams to solve problems, explore new technologies, and learn from one another. The ideal intern for this environment will be enthusiastic and collaborative.",
        company_id=2)
    post3 = Post(
        title="Manufacturing Intern Job",
        content=
        "Our Company, an intense and exciting company, is looking for interns to join our creative team of engineers working to develop systems and analysis for a wide variety of companies and industries. Our engineers are hard-working, smart, goal-oriented and creative, and they are looking for interns to train to participate in every level of system design and orientation. The interns hired for this position should expect to learn all facets of manufacturing, and will leave this position with invaluable skills and industry knowledge. Also, this internship program is highly regarded in our field, so successful participation will be a great addition to your resume.",
        company_id=2)
    post4 = Post(
        title="Graphic Design Intern",
        content=
        "Are you a student interested in building real-world graphic design experience with an award-winning team? We’re a forward-thinking advertising agency looking for a talented and knowledgeable designer with fresh, creative ideas and an excellent eye for detail. Come work for one of the area’s leading advertising agencies and learn from some of the best in the business.",
        company_id=2)
    post5 = Post(
        title="HR (Human Resources) Intern",
        content=
        "Fast-growing marketing agency seeks a personable and highly motivated HR intern to support the HR manager in day-to-day administrative tasks and activities. If you’re ready to kickstart your career in Human Resources and build real-world experience with recruiting, payroll, employee development, and the coordination of HR policies and procedures, this is the internship for you.",
        company_id=2)
    db.session.add(post)
    db.session.add(post2)
    db.session.add(post3)
    db.session.add(post4)
    db.session.add(post5)
    db.session.commit()
    print("\n")
    print(Post.query.all())
Exemple #19
0

# noinspection PyUnusedLocal
def generate_session_key(length):
    return ''.join([
        random.choice(
            'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
        for i in range(length)
    ])


auth = LoginManager()
auth.login_view = "home.index.login"
auth.session_protection = "strong"

auth_hasher = Bcrypt()


@auth.user_loader
def load_user(session_token):
    return User.query.filter_by(token=session_token).first()


def do_login(username, password):
    user = User.query.filter_by(username=username).first()

    if user is None:
        return False

    if not auth_hasher.check_password_hash(user.passhash, password):
        return False
Exemple #20
0
from _import import postprocess_move
from commands import AddUser, ImportMove, DeleteMove, ListMoves
from filters import register_filters, register_globals, radian_to_degree, get_city
from login import login_manager, load_user, LoginForm
from model import db, Move, Sample, MoveEdit, UserPreference, AlembicVersion

try:
    from urllib.parse import quote_plus
except ImportError:
    from urllib import quote_plus as __quote_plus
    quote_plus = lambda x: __quote_plus(x.encode('utf-8'))

app = Flask('openmoves')
fujs = FlaskUtilJs(app)

app_bcrypt = Bcrypt()
migrate = Migrate(app, db)

register_filters(app)
register_globals(app)


def _parse_revision(filename):
    pattern = re.compile(r"revision = '(\d+)'")
    with open(filename, 'r') as f:
        for line in f:
            match = pattern.match(line)
            if match:
                return int(match.group(1))

    raise RuntimeError("Failed to parse revision from %s" % filename)
Exemple #21
0
from flask import Flask, render_template, request, redirect, session, flash
from flask_bcrypt import Bcrypt
from datetime import datetime
import re
from mysqlconnection import connectToMySQL

app = Flask(__name__)
app.secret_key = "Welcome to the thunder dome"
bcrpyt = Bcrypt(app)
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/create_user', methods=['POST'])
def create_user():
    is_valid = True
    SpecialSym = ['$', '@', '#', '%']

    if len(request.form['fname']) < 2:
        is_valid = False
        flash("Please enter a first name")

    if len(request.form['lname']) < 2:
        is_valid = False
        flash("Please enter a last name")

    if not EMAIL_REGEX.match(request.form['email']):
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt

app = Flask(__name__)
app.config['SECRET_KEY'] = "3184cf50b884fd2828b2a084ac04d518f7c4f4e8f22f416a"
# app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@localhost/project-2"
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@ec2-54-225-118-55.compute-1.amazonaws.com:5432/d96rrep6atbc84"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # added just to suppress a warning
UPLOAD_FOLDER = './app/static/uploads'
DEFAULT_BIO = 'This person has not entered a bio.'


db = SQLAlchemy(app)
bcryptHash = Bcrypt(app)

# Flask-Login login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

app.config.from_object(__name__)
from app import views
Exemple #23
0
def createApp():
    """Set up the application."""
    app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    app.config.from_object(__name__)
    app.config['LOCAL'] = local
    app.debug = CONFIG_SERVICES['server_debug']
    app.config['REST_TRACE'] = CONFIG_SERVICES['rest_trace']
    app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    sesEmail.SIGNING_KEY =  CONFIG_BROKER['email_token_key']
    sesEmail.isLocal = local
    if sesEmail.isLocal:
        sesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    # When runlocal is true, assume Dynamo is on the same server
    # (should be false for prod)
    JsonResponse.debugMode = app.config['REST_TRACE']

    if CONFIG_SERVICES['cross_origin_url'] ==  "*":
        cors = CORS(app, supports_credentials=False, allow_headers = "*", expose_headers = "X-Session-Id")
    else:
        cors = CORS(app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
                    allow_headers = "*", expose_headers = "X-Session-Id")
    # Enable AWS Sessions
    app.session_interface = DynamoInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(app)

    @app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @app.before_request
    def before_request():
        GlobalDB.db()

    # Root will point to index.html
    @app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    # Add routes for modules here
    add_login_routes(app, bcrypt)

    add_file_routes(app, CONFIG_BROKER['aws_create_temp_credentials'],
        local, broker_file_path, bcrypt)
    add_user_routes(app, app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(app, local, bcrypt)

    SessionTable.LOCAL_PORT = CONFIG_DB['dynamo_port']

    SessionTable.setup(app, local)

    if local:
        checkDynamo()
    else:
        SessionTable.DYNAMO_REGION = CONFIG_BROKER['aws_region']

    return app
Exemple #24
0
from flask_blog.models import Users, Post
from flask import render_template, url_for, redirect, flash, request, abort
from flask_bcrypt import Bcrypt
from flask_blog.forms import (Registration_form, Log_in_form, Update_acc_form,
                              Post_form, RequestResetForm, ResetPasswordForm)
from flask_blog import app, db, mail
from flask_login import login_user, current_user, logout_user
import os
import secrets
from flask_mail import Message

title = 'ABOUT'
bcrypt = Bcrypt(app) #For encryption of password...


@app.route("/")
@app.route("/home", endpoint='home')
def home():
    return render_template('home.html')


@app.route("/about", endpoint='about')
def about():
    if current_user.is_authenticated:
        posts = Post.query.all()
        return render_template('about.html', posts=posts, title= title)
    else:
        flash(f'Not logged in!', 'info')
        return redirect(url_for('Register'))

@app.route("/login", methods=['GET', 'POST'])
from flask import Flask  #importing Flask class from flask package to use flask function and class
from flask_sqlalchemy import SQLAlchemy  #importing SQLAlchemy to manage our database
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)  #instanciating imported flask class
app.config[
    'SECRET_KEY'] = '51790f49aa35845942c29ff82df9f8c8'  #Secret key to secure our app like modifying cookies etc
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'  # specify the relative route of the database
db = SQLAlchemy(app)  #Creating SQLAlchemy instance
bcrypt = Bcrypt(app)  #Creating Bcrypt instance to manage hashing password
login_manager = LoginManager(app)  # to manage user's session
login_manager.login_view = 'login'  #allow us to force the user to login before access to different pages
login_manager.login_message_category = 'info'  #change the apparence of different info message

from webapp import routes
Exemple #26
0
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
# from app.main.util.flask_qiniu import Qiniu
from app.main.util.flask_s3 import S3Upload

db = SQLAlchemy()

flask_bcrypt = Bcrypt()

# qiniu_store = Qiniu()
s3_store = S3Upload()
Exemple #27
0
config = configparser.ConfigParser()
config.read('config.ini')


class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, datetime.datetime):
            return str(o)
        return json.JSONEncoder.default(self, o)


app = Flask(__name__)

app.config[
    'MONGO_URI'] = config['MONGODB']['URI'] + config['MONGODB']['DATABASE']
app.config['JWT_SECRET_KEY'] = config['JWT']['SECRET']
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=1)
mongo = PyMongo(app)

flask_bcrypt = Bcrypt(app)
jwt = JWTManager(app)
app.json_encoder = JSONEncoder

CORS(app)

# noinspection PyPep8
from app.controllers import *
Exemple #28
0
from PIL import Image

# imports para formularios
from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
#import os
#from werkzeug import secure_filename

app = Flask(__name__)
#app.config['UPLOAD_FOLDER'] = './static/images'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///databases/brioche.db'
app.config['SECRET_KEY'] = 'ABCDEFGHI'
db = SQLAlchemy(app)
bcrypt = Bcrypt()

login_manager = LoginManager(app)


@login_manager.user_loader
def load_user(user_id):
    return Usuario.query.get(int(user_id))


class Usuario(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    nombreUsuario = db.Column(db.String(30), nullable=False)
    apellidoUsuario = db.Column(db.String(30), nullable=False)
    correoElectronico = db.Column(db.String(30), nullable=False, unique=True)
    password = db.Column(db.String(30), nullable=False)
Exemple #29
0
from flask import Flask
from flask_sqlalchemy import Model, SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = '2b3b0653a9d3c42948bd5edce8fd84cb'
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'  #creating a local SQlite Database
app.config[
    'SQLALCHEMY_TRACK_MODIFICATIONS'] = False  #Removes tracking of changes to the database
db = SQLAlchemy(app)  #Assigning our database to SQLAlchemey
bcrypt = Bcrypt(app)  ##Flask library used to hash passwords
login_manager = LoginManager(
    app)  #Flask library to manage login on our web application
login_manager.login_view = 'login_page'
login_manager.login_message_category = 'info'

from cardealer import routes