예제 #1
0
def run_application():
    from routes.StoreApis import StoreApi, StoreListApi
    from routes.ProductApis import ProductApi

    api.add_resource(StoreListApi, '/store')
    api.add_resource(StoreApi, '/store/<string:store_id>')
    api.add_resource(ProductApi, '/product')

    from routes.AuthApi import UserRegistration
    from routes.AuthApi import UserLogin
    from routes.AuthApi import TokenRefresh
    from routes.AuthApi import AllUsers
    from routes.AuthApi import SecretResource
    from routes.AuthApi import GetStoresFromUser

    api.add_resource(UserRegistration, '/registration')
    api.add_resource(UserLogin, '/login')
    api.add_resource(TokenRefresh, '/token/refresh')
    api.add_resource(AllUsers, '/users')
    api.add_resource(SecretResource, '/secret')

    api.add_resource(GetStoresFromUser, '/getStores/<string:user_id>')

    from routes.RatingApi import RantingApi

    api.add_resource(RantingApi, '/rate/<int:user_id>')

    heroku = Heroku(app)
    return app
예제 #2
0
def load_extensions(app):
    Bootstrap(app)
    AppConfig(app)
    Heroku(app)
    CORS(app)
    DebugToolbarExtension(app)
    CSRFProtect(app)
    SSLify(app)
예제 #3
0
def create_app(config_name):
    app = Flask(__name__,static_url_path="/app/main/templates/statics")
    app.config.from_object(config_by_name[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    print(f"current env : {config_name}")
    if config_name=="prod":
        heroku = Heroku(app)
    db.init_app(app)
    flask_bcrypt.init_app(app)

    return app
예제 #4
0
def create_app(env_name):
    app = Flask(__name__)

    app.config.from_object(app_config[env_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    if env_name == 'production':
        CORS(app)
        Heroku(app)

    # register blueprints

    bcrypt.init_app(app)
    db.init_app(app)

    return app
예제 #5
0
파일: __init__.py 프로젝트: consaceves/cctr
def create_app():
    app = Flask(__name__)
    db.init_app(app)

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    heroku = Heroku(app)

    with app.app_context():
        from . import models
        db.drop_all()
        db.create_all()

    from . import api
    app.register_blueprint(api.home.app)
    app.register_blueprint(api.dashboard.app)
    app.register_blueprint(api.user.app)
    app.register_blueprint(api.workout.app)
    app.register_blueprint(api.sms.app)

    return app
예제 #6
0
class create_app():
    app = Flask(__name__, root_path=os.path.abspath(os.path.join(".")))
    cors = CORS(app)
    migrate = Migrate(app, db, compare_type=True)
    heroku = Heroku(app)
    env = os.getenv("ENV")
    app.config.from_object(config.get(env))
    db.init_app(app)
    guard.init_app(app, User, is_blacklisted=is_blacklisted)
    conn = redis.from_url(environ.get('REDIS_URL',
                                      app.config.get('REDIS_URL')))
    q = Queue(connection=conn)
    manager = Manager(app)

    def __init__(self):
        ##    # Register Jinja template functions
        ##    from .utils import register_template_utils
        ##    register_template_utils(app)
        ##
        ##    # Set up asset pipeline
        ##    assets_env = Environment(app)
        ##    dirs = ['assets/styles', 'assets/scripts']
        ##    for path in dirs:
        ##        assets_env.append_path(os.path.join(basedir, path))
        ##    assets_env.url_expire = True
        ##
        ##    assets_env.register('app_css', app_css)
        ##    assets_env.register('app_js', app_js)
        ##    assets_env.register('vendor_css', vendor_css)
        ##    assets_env.register('vendor_js', vendor_js)
        ##
        ##    # Configure SSL if platform supports it
        ##    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        ##        from flask_sslify import SSLify
        ##        SSLify(app)
        # Create app blueprints
        from .main import main as main_blueprint
        self.app.register_blueprint(main_blueprint)
        from .job import job as job_blueprint
        self.app.register_blueprint(job_blueprint)
예제 #7
0
def config_app():
    app = Flask(__name__,
                template_folder="../application/templates",
                static_folder='../application/static')
    app.config.from_object(config.get('development'))
    config.get('development').init_app(app)
    db.init_app(app)
    mail.init_app(app)
    environment_debug = os.environ.get("ENV", default='development')
    if environment_debug == 'development':
        with app.app_context():
            app.logger.debug('development')
            CORS(app)
            app.debug = app.config['DEBUG']
            # app.logger.debug("before delete database")
            # if database_exists(app.config['SQLALCHEMY_DATABASE_URI']):
            #     app.logger.debug('Deleting database.')
            #     drop_database(app.config['SQLALCHEMY_DATABASE_URI'])
            if not database_exists(app.config['SQLALCHEMY_DATABASE_URI']):
                app.logger.debug('Creating database.')
                create_database(app.config['SQLALCHEMY_DATABASE_URI'])
            app.logger.debug('Creating tables.')
            app.logger.debug("before create")
            try:
                create_tables()
            except BaseException as e:
                app.logger.debug(e)
            app.logger.debug('Shiny!')
    else:
        app.config.from_object(config.get('production'))
        app.debug = False
        heroku = Heroku(app)
        with app.app_context():
            db.init_app(app)
            mail.init_app(app)
            app.logger.warning('Creating tables. heroku')
            create_tables()
            app.logger.warning('Shiny! heroku')
    register_blueprints(app)
    return app
예제 #8
0
    def __init__(self, config_filename='../configs/production.py'):
        self.app = Flask(__name__)

        Heroku(self.app)
        self.app.config.from_pyfile(config_filename)

        babel = Babel(self.app)

        self.__config_database_and_security()
        self.__config_flask_admin()
        self.__config_blueprints()

        @babel.localeselector
        def get_locale():
            return 'pt_BR'

        @user_registered.connect_via(self.app)
        def user_registered_sighandler(sender, **extra):
            """Adds the end-user role to the user upon registering."""
            user = extra.get('user')
            role = user_datastore.find_or_create_role('end-user')
            user_datastore.add_role_to_user(user, role)
            db.session.commit()
예제 #9
0
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_heroku import Heroku
from flask_cors import CORS

from app.api import blueprint as api

web_app = Flask("KUT scheduler API")
web_app.config.from_object('config')

web_app.register_blueprint(api, url_prefix='/api/v1')

db = SQLAlchemy(web_app)
heroku = Heroku(web_app)
cors = CORS(web_app, resources={r"/api/*": {"origins": "*"}})

if __name__ == "__main__":
    web_app.run("0.0.0.0", 8080)
예제 #10
0
파일: app.py 프로젝트: amarssadal/bbcf
def create_app():
    app = Flask(__name__,
                instance_relative_config=True,
                template_folder="templates",
                static_url_path="")

    app.config.from_pyfile("default.py")
    app.config.from_envvar("APP_CONFIG_FILE", silent=True)

    heroku = Heroku()
    heroku.init_app(app)

    db.init_app(app)

    migrate = Migrate(compare_type=True)
    migrate.init_app(app, db)

    admin = Admin(app)
    admin.add_view(AdminModelView(Event, db.session))
    admin.add_link(MenuLink(name="Website", endpoint="index"))
    admin.add_link(MenuLink(name="Login", url="/login"))
    admin.add_link(MenuLink(name="Logout", url='/logout'))

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    @app.context_processor
    def inject_now():
        return {'now': datetime.utcnow()}

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    get_url=url_for,
                    h=helpers)

    @app.before_first_request
    def create_user():
        role = user_datastore.find_or_create_role("admin")
        # password = os.environ.get('ADMIN_PASSWORD')
        if not User.query.filter_by(email=ADMIN_EMAIL).first():
            user = user_datastore.create_user(email=ADMIN_EMAIL,
                                              password=ADMIN_PASSWORD)
            user_datastore.add_role_to_user(user, role)
        db.session.commit()

    @app.route('/')
    @app.route('/index')
    def index():
        events = Event.query.filter(Event.date > datetime.utcnow()).order_by(
            Event.date)
        return render_template('index.html', events=events)

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

    @app.route('/signup', methods=['POST'])
    def signup():
        email = request.form.get('email')
        api_key = os.environ.get('MAILCHIMP_API_KEY')
        if not api_key or not email:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
            return redirect(url_for('index'))
        server_number = api_key[-4:]
        url = f"https://{server_number}.api.mailchimp.com/3.0/lists/{LIST_ID}/members"
        headers = {
            'content-type': 'application/json',
            'Authorization': f"Basic {api_key}"
        }
        data = {'email_address': email, 'status': 'subscribed'}
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if response.ok or response.json().get('title') == 'Member Exists':
            flash('Thanks for signing up to our newsletter!')
        else:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
        return redirect(url_for('index'))

    return app
예제 #11
0
from flask_wtf.file import FileField
from flask_bootstrap import Bootstrap
from flask_socketio import SocketIO
import requests
from werkzeug import secure_filename, formparser
from wtforms import SubmitField

from celery_utils import make_celery
from flask_heroku import Heroku
from services.tools import S3Helper

template_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            'templates')

app = Flask(__name__, template_folder=template_dir)
app = Heroku(app).app
app.config.from_object('config')

REDIS_URL = 'redis://localhost:6379/0'
#REDIS_URL = None
Bootstrap(app)
socketio = SocketIO(app, async_mode='eventlet', message_queue=REDIS_URL)

s3 = S3Helper(app.config)
celery = make_celery(app)


class UploadForm(Form):
    upload = FileField('Upload File')
    submit_button = SubmitField('Upload')
예제 #12
0
from flask import jsonify
from flask import request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_heroku import Heroku
from flask_cors import CORS, cross_origin

from flask import Flask
app = Flask(__name__)
CORS(app)
database = SQLAlchemy(app)
marshmallow = Marshmallow(app)

if 'DYNO' in os.environ:
    import psycopg2
    hr = Heroku(app)
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///local.db'

#############
## SCHEMA  ##
#############


class Light(database.Model):
    __tablename__ = "lights"

    lightID = database.Column(database.Integer, primary_key=True)
    lightName = database.Column(database.String)
    lightLatitude = database.Column(database.Float)
    lightLongitude = database.Column(database.Float)
예제 #13
0
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from flask_heroku import Heroku

app = Flask(__name__)

app.config[
    "SQLALCHEMY_DATABASE_URI"] = "postgres://*****:*****@ec2-3-210-23-22.compute-1.amazonaws.com:5432/d2r6ifa666j6u3"

db = SQLAlchemy(app)
ma = Marshmallow(app)

CORS(app)
Heroku(app)


class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String, nullable=False, unique=True)

    def __init(self, text):
        self.text = text


class QuestionSchema(ma.Schema):
    class Meta:
        fields = ("id", "text")

예제 #14
0
def create_app(test_config=None):
    '''
    Create your application
    Load configuration files
    Import / register blueprints
    Register your database
    '''

    # Configuration loaded from instance/ directory when set to true
    app = Flask(__name__, instance_relative_config=True)

    # Secret_key is used to sign cookies so session info can't be modified
    # use a random_number for deployment
    # Database is the path to your database (in the instance folder here)
    app.config.from_mapping(
        SECRET_KEY='dev',
        #DATABASE = os.path.join(app.instance_path, 'nickdb.sqlite')
        MYSQL_HOST='sql9.freemysqlhosting.net',
        MYSQL_USER='******',
        MYSQL_PASSWORD='******',
        MYSQL_DB='sql9249883',
        MYSQL_CURSORCLASS='DictCursor')
    #[email protected]
    #VyK^gPRirq*Q)&TV

    # Use configuration from config.py unless a testing config is supplied
    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    # If instance folder doesn't exist, make it
    # Will usually make it one directory above __init__.py so that it is not
    # available to clients
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Create a simple test routes / easter eggs
    @app.route('/hello')
    def hello():
        return "You should not be here.<br><br>How did you find this, please leave immediately."

    @app.route('/hayley')
    def hayley():
        return "Hi my darling <3"

    @app.route('/imupset')
    def upset():
        return "Ligma"

    '''
    THE BELOW IS DEPRECIATED FOR THE TIME BEING
    # Register Database for teardown context / CLI command
    # Local import (checks within package first to avoid using wrong lib)
    #import dbmysq
    #dbmysq.init_it(app)

    #import dbmysq 
    #dbmysq.init_app(app)

    # Reguster blueprints
    import auth
    app.register_blueprint(auth.bp)

    import posts
    app.register_blueprint(posts.bp)
    '''

    import home.home
    app.register_blueprint(home.home.bp)

    @app.route('/')
    def home():
        return redirect(url_for('home.home_index'))

    import lunchbreak.lunchbreak
    app.register_blueprint(lunchbreak.lunchbreak.bp)

    #
    #import thai restauraunt stuff
    #
    import silk_thai.checkout
    app.register_blueprint(silk_thai.checkout.bp)

    import silk_thai.homepage
    app.register_blueprint(silk_thai.homepage.bp)

    import silk_thai.menu
    app.register_blueprint(silk_thai.menu.bp)

    import silk_thai.pdp
    app.register_blueprint(silk_thai.pdp.bp)

    import silk_thai.admin
    app.register_blueprint(silk_thai.admin.bp)
    #
    #End thai restaurunt stuff
    #

    socker.init_app(app)

    import test_pong.pong
    app.register_blueprint(test_pong.pong.bp)  #test_pong.pong.bp)

    import stay_alive.stay_alive
    import stay_alive.s_events
    app.register_blueprint(stay_alive.stay_alive.bp)

    heroku = Heroku(app)

    return app
예제 #15
0
def create_app(test_config=None):
    # create and configure the app

    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='dev',
                            SQLALCHEMY_TRACK_MODIFICATIONS=False)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    heroku = Heroku(app)

    # from flaskr.model import db
    db.init_app(app)

    bucketName = "indivprojcht116"
    remoteDirectoryName = "model"
    util.downloadDirectoryFroms3(bucketName, remoteDirectoryName)

    # HEROKU
    @app.route('/news-items', methods=['GET'])
    def get_news_items():
        articles = batch_utils.get_latest_batch_articles()
        data = []
        for article in articles:
            a = copy.copy(article.__dict__)
            del a["_sa_instance_state"]
            data.append(a)

        response = jsonify(data)
        response.headers.add('Access-Control-Allow-Origin', '*')

        return response

    # LOCAL
    # @app.route('/news-items', methods=['GET'])
    # def get_news_items():
    #     rec = recommender.Recommender()
    #     recs = rec.get_recommendations()

    #     response = jsonify(recs)
    #     response.headers.add('Access-Control-Allow-Origin', '*')
    #     # response.headers.add(
    #     #     'Access-Control-Allow-Headers', 'Authorization, Content-Type')
    #     # response.headers.add('Access-Control-Allow-Methods', '*')
    #     return response

    @app.route('/ratings', methods=['OPTIONS', 'POST', 'GET'])
    def add_rating():

        if request.method == 'OPTIONS':
            data = request.json
            response = jsonify(data)
            response.headers.add('Access-Control-Allow-Origin', '*')
            response.headers.add('Access-Control-Allow-Headers',
                                 'Authorization, Content-Type')
            response.headers.add('Access-Control-Allow-Methods', '*')
            return response
        elif request.method == 'POST':
            ratingVal = request.json['ratingVal']
            user_email = request.json['userEmail']
            article_id = request.json['article_id']

            rating = Rating(ratingVal=ratingVal,
                            user_email=user_email,
                            article_id=article_id)

            try:
                db.session.add(rating)
                db.session.commit()
            except Exception as e:
                # print("\n FAILED entry: {}\n".format(json.dumps(data)))
                print(e)
                # sys.stdout.flush()

            data = request.json
            response = jsonify(data)
            response.headers.add('Access-Control-Allow-Origin', '*')
            response.headers.add('Access-Control-Allow-Headers',
                                 'Authorization, Content-Type')
            response.headers.add('Access-Control-Allow-Methods', '*')

            return response
        elif request.method == 'GET':
            data = []
            for rating in Rating.query.all():
                r = copy.copy(rating.__dict__)
                del r["_sa_instance_state"]
                data.append(r)

            response = jsonify(data)
            response.headers.add('Access-Control-Allow-Origin', '*')
            response.headers.add('Access-Control-Allow-Headers',
                                 'Authorization, Content-Type')
            response.headers.add('Access-Control-Allow-Methods', '*')

            return response

    return app
예제 #16
0
def create_app(config_name):
    from app.models import User
    from app.models import Recipes
    from app.models import RecipeCategory

    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    app.secret_key = '*****@*****.**'
    app.config['SWAGGER'] = {
        "swagger":
        "2.0",
        "info": {
            "version": "1.0",
            "title": "Recipe Challenge Api",
            "description":
            "A recipe web application api.\n Useful resources include\n'https://github.com/sir3n-sn/Api-challenge-3'\n",
            "contact": {
                "email": "*****@*****.**"
            },
            "termsOfService": "https://opensource.org/ToS",
            "license": {
                "name": "Apache 2.0",
                "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
            }
        },
        "schemes": ["http", "https"],
        "host":
        "api-recipe-challenge.herokuapp.com",
        "tags": [{
            "name":
            "auth",
            "description":
            "All functionality about authention of the user"
        }, {
            "name": "Categories",
            "description": "All functionality on the categories endpoint"
        }, {
            "name": "Recipes",
            "description": "All functionality on the Recipes endpoint"
        }]
    }
    Swagger(app)  # This creates a swagger ui documentation
    Heroku(app)
    # The views for the application

    @app.route('/')
    def index():
        return redirect('apidocs')

    @swag_from('docs/Categories_get.yml', methods=['GET'])
    @swag_from('docs/Categories_post.yml', methods=['POST'])
    @app.route('/api-1.0/categories', methods=['GET', 'POST'])
    def categories():
        # Get the access token from the header
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please Provide an access token"}, 300
        if access_token:
            # Attempt to decode and the user id
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                page = int(request.args.get('page', 1))
                per_page = int(request.args.get('per_page', 20))
                #  Go ahead and process the request
                if request.method == 'POST':
                    name = str(request.data.get('name', ''))
                    detail = str(request.data.get('detail', ''))
                    if name and detail:
                        category = RecipeCategory(name=name,
                                                  detail=detail,
                                                  created_by=user_id)
                        category.save()
                        response = jsonify({
                            "id":
                            category.id,
                            "Recipe Category Name":
                            category.name,
                            "Recipe Category Detail":
                            category.detail,
                            "Date Created":
                            category.date_created,
                            "Date Modified":
                            category.date_modified
                        })
                        response.status_code = 201
                        return response
                    else:
                        response = jsonify(
                            {"Message": "please use keys name and detail"})
                        response.status_code = 203
                        return response
                else:
                    # GET
                    category = RecipeCategory.query.filter_by(
                        created_by=user_id).paginate(page=page,
                                                     per_page=per_page)
                    result = []
                    for each_category in category.items:
                        obj = {
                            "id": each_category.id,
                            "Recipe Category Name": each_category.name,
                            "Recipe Category Detail": each_category.detail,
                            "Date Created": each_category.date_created,
                            "Date Modified": each_category.date_modified
                        }
                        result.append(obj)
                    response = jsonify(
                        {
                            'Next page': category.next_num,
                            'Prev page': category.prev_num,
                            'Has next': category.has_next,
                            'Has prev': category.has_prev,
                        }, result)
                    response.status_code = 200
                    return response
            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    @swag_from('docs/Category_id_get.yml', methods=['GET'])
    @swag_from('docs/Categories_id_delete.yml', methods=['DELETE'])
    @swag_from('docs/Categories_id_edit.yml', methods=['PUT'])
    @app.route('/api-1.0/categories/<int:id>',
               methods=['GET', 'PUT', 'DELETE'])
    def categories_manipulation(id):
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please provide an access token"}, 300
        # retrieve a category by it's id
        if access_token:
            user_id = User.decode_token(access_token)
            category = RecipeCategory.query.filter_by(id=id).first()
            if not isinstance(user_id, str):
                if category:
                    if request.method == 'DELETE':
                        category.delete()
                        return {
                            "Message":
                            'Category {} was deleted successfully'.format(
                                category.id)
                        }, 200

                    elif request.method == 'PUT':
                        name = str(request.data.get('name', ''))
                        detail = str(request.data.get('detail', ''))
                        if name and detail:
                            category.name = name
                            category.detail = detail
                            category.save()
                            response = jsonify({
                                "id":
                                category.id,
                                "Recipe Category Name":
                                category.name,
                                "Recipe Category Detail":
                                category.detail,
                                "Date Created":
                                category.date_created,
                                "Date Modified":
                                category.date_modified
                            })
                            response.status_code = 200
                            return response
                        else:
                            response = jsonify({
                                "Message":
                                "Please use the keys name and detail"
                            })
                            response.status_code = 203
                            return response
                    # Get
                    else:
                        response = jsonify({
                            "id":
                            category.id,
                            "Recipe Category Name":
                            category.name,
                            "Recipe Category Detail":
                            category.detail,
                            "Date Created":
                            category.date_created,
                            "Date Modified":
                            category.date_modified
                        })
                        response.status_code = 200
                        return response
                else:
                    # abort early with an error four oh four if not in found
                    return {
                        "Message":
                        "The category does not exist, Would you like to create one?"
                    }, 404
            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    @swag_from('docs/Categories_search_get.yml', methods=['GET'])
    @app.route('/api-1.0/categories/search', methods=['GET'])
    def search_item():
        """This searches the category for items with similar or equal names to the get
        parameter q"""
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please provide an access token"}, 300
        if access_token:
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                page = int(request.args.get('page', 1))
                per_page = int(request.args.get('per_page', 20))
                q = request.values.get('q', '')
                if q:
                    search_result = RecipeCategory.query.filter_by(
                        created_by=user_id).paginate(page=page,
                                                     per_page=per_page)
                    # GET
                    result = []
                    for each_category in search_result.items:
                        if q in each_category.name or q in each_category.detail:
                            obj = {
                                "id": each_category.id,
                                "Recipe Category Name": each_category.name,
                                "Recipe Category Detail": each_category.detail,
                                "Date Created": each_category.date_created,
                                "Date Modified": each_category.date_modified
                            }
                            result.append(obj)
                    if not result:
                        message = {
                            "Message":
                            "Sorry we could not find what you are looking for"
                        }, 403
                        result.append(message)
                    response = jsonify(
                        {
                            'Next Page': search_result.next_num,
                            'Prev Page': search_result.prev_num,
                            'Has next': search_result.has_next,
                            'Has previous': search_result.has_prev
                        }, result)
                    response.status_code = 200
                    return response

                else:
                    message = {"Message": "Please provide a search query"}
                    response = jsonify(message)
                    response.status_code = 404
                    return response

            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    @swag_from('docs/Recipes_get.yml', methods=['GET'])
    @swag_from('docs/Recipes_post.yml', methods=['POST'])
    @app.route('/api-1.0/categories/<int:id>/recipes', methods=['GET', 'POST'])
    def recipes(id):
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please provide an access token"}, 300
        category = RecipeCategory.query.filter_by(id=id).first()
        result = []
        if access_token:
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                page = int(request.args.get('page', 1))
                per_page = int(request.args.get('per_page', 20))
                if category:
                    if request.method == 'GET':
                        if category.recipes:
                            recipe_object = category.recipes.paginate(
                                page=page, per_page=per_page)
                            for recipe in recipe_object.items:
                                obj = {
                                    "id": recipe.id,
                                    "name": recipe.name,
                                    "Recipe": recipe.recipe,
                                    "Date Created": recipe.date_created,
                                    "Date Modified": recipe.date_modified
                                }
                                result.append(obj)
                            response = jsonify(
                                {
                                    'Next Page': recipe_object.next_num,
                                    'Prev Page': recipe_object.prev_num,
                                    'Has next': recipe_object.has_next,
                                    'Has previous': recipe_object.has_prev
                                }, result)
                            response.status_code = 200
                            return response
                        else:
                            response = jsonify(
                                {"Message": "No recipes added yet"})
                            response.status_code = 404
                            return response

                    elif request.method == 'POST':
                        name = request.data.get('name', '')
                        recipe = request.data.get('recipe', '')
                        if name and recipe:
                            the_recipes = Recipes(name=name,
                                                  recipe=recipe,
                                                  belonging_to=category)
                            the_recipes.save()
                            for recipe in category.recipes.all():
                                obj = {
                                    "id": recipe.id,
                                    "name": recipe.name,
                                    "Recipe": recipe.recipe,
                                    "Date created": recipe.date_created,
                                    "Date modified": recipe.date_modified
                                }
                                result.append(obj)
                                response = jsonify(result)
                                response.status_code = 201
                                return response
                        else:
                            return {
                                "Message": "Please use keys name and recipe"
                            }, 203
                else:
                    return {"Message": "Category does not exist"}, 405

            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    @swag_from('docs/Recipes_search_get.yml', methods=['GET'])
    @app.route('/api-1.0/categories/<int:id>/recipes/search', methods=['GET'])
    def search_recipe_item(id):
        """This searches the recipes for items with similar or equal names to the get
        parameter q"""
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please provide an access token"}, 300
        if access_token:
            user_id = User.decode_token(access_token)
            category = RecipeCategory.query.filter_by(id=id).first()
            if not isinstance(user_id, str):
                page = int(request.args.get('page', 1))
                per_page = int(request.args.get('per_page', 20))
                if category:
                    if category.recipes:
                        q = request.values.get('q', '')
                        if q:
                            search_result = category.recipes.paginate(
                                page=page, per_page=per_page)
                            # GET
                            result = []
                            for each_recipe in search_result.items:
                                if q in each_recipe.name or q in each_recipe.recipe:
                                    obj = {
                                        "id": each_recipe.id,
                                        "Name": each_recipe.name,
                                        "Recipe": each_recipe.recipe,
                                        "Date Created":
                                        each_recipe.date_created,
                                        "Date Modified":
                                        each_recipe.date_modified
                                    }
                                    result.append(obj)
                            if not result:
                                message = {
                                    "Message":
                                    "Sorry we could not find what you are looking for"
                                }, 403
                                result.append(message)
                            response = jsonify(
                                {
                                    'Next Page': search_result.next_num,
                                    'Prev Page': search_result.prev_num,
                                    'Has next': search_result.has_next,
                                    'Has previous': search_result.has_prev
                                }, result)
                            response.status_code = 200
                            return response

                        else:
                            message = {
                                "Message": "Please provide a search query"
                            }
                            response = jsonify(message)
                            response.status_code = 404
                            return response
                else:
                    # abort early with an error four oh four if not in found
                    return {"Message": "Category does not exist"}, 405
            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    @swag_from('docs/Recipe_id_get.yml', methods=['GET'])
    @swag_from('docs/Recipes_id_edit.yml', methods=['PUT'])
    @swag_from('docs/Recipes_id_delete.yml', methods=['DELETE'])
    @app.route("/api-1.0/categories/<int:val>/recipes/<int:res>",
               methods=['GET', 'PUT', 'DELETE'])
    def recipe_manipulation(val, res):
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]
        else:
            return {"Message": "Please provide and access token"}, 300
        category = RecipeCategory.query.filter_by(id=val).first()
        if access_token:
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                if category:
                    current_recipe = category.recipes.filter_by(id=res).all(
                    )  # Access the recipe related to the category
                    if current_recipe:
                        if request.method == 'DELETE':
                            for each_recipe in current_recipe:
                                each_recipe.delete()
                                return {
                                    "Message":
                                    'Recipe {} was deleted successfully'.
                                    format(res)
                                }, 200

                        elif request.method == 'PUT':
                            name = request.data.get('name', '')
                            recipe = request.data.get('recipe', '')
                            if name and recipe:
                                for the_recipe in current_recipe:
                                    the_recipe.name = name
                                    the_recipe.recipe = recipe
                                    the_recipe.save()
                                    response = jsonify({
                                        "Recipe Name":
                                        the_recipe.name,
                                        "Recipe":
                                        the_recipe.recipe,
                                        "Date Created":
                                        the_recipe.date_created,
                                        "Date Modified":
                                        the_recipe.date_modified,
                                    })
                                    response.status_code = 201
                                    return response
                            else:
                                return {
                                    "Message":
                                    "name and recipe cannot be empty"
                                }, 203

                        elif request.method == 'GET':
                            for the_recipe in current_recipe:
                                response = jsonify({
                                    "Recipe Name":
                                    the_recipe.name,
                                    "Recipe":
                                    the_recipe.recipe,
                                    "Date Created":
                                    the_recipe.date_created,
                                    "Date Modified":
                                    the_recipe.date_modified,
                                })
                                response.status_code = 200
                                return response
                    else:
                        return {"Message": "The recipe does not exist"}, 404
                else:
                    return {"Message": "The category does not exist"}, 405
            else:
                #  Token is not legit so return the error message
                message = user_id
                response = jsonify({"Message": message})
                response.status_code = 401
                return response

    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)
    return app
예제 #17
0
import datetime

import bcrypt
from flask import Flask, render_template, request, jsonify, flash, session, redirect, url_for
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_heroku import Heroku
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
heroku = Heroku(app)
heroku.init_app(app)
db = SQLAlchemy(app)
from app import models
db.create_all([None])
username = ""


@app.route('/')
def index():
    if 'username' in session:
        features = models.Feature.query.filter(
            models.Feature.assigned == session['username']).order_by(
                models.Feature.clientPriority.asc())
        return render_template('home.html',
                               name=session['username'],
                               features=features)
    return render_template('index.html')


@app.route('/login', methods=['POST'])
예제 #18
0
def create_app(test_config=None):

    app = Flask(__name__)
    api = Api(app, errors=errors)
    heroku = Heroku(app)
    setup_db(app)
    initialize_routes(api)

    CORS(app)

    @app.route('/')
    def get_greeting():
        excited = os.getenv('EXCITED')
        greeting = "My Capstone Project"
        if excited == 'true':
            greeting = greeting + "!!!!!"
        return greeting

    # Error Handling

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

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

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

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

    @app.errorhandler(500)
    def server_error(error):
        return jsonify({
            'success': False,
            'error': 500,
            'message': 'SERVER ERROR'
        }), 500

    @app.errorhandler(AuthError)
    def authentication_error(error):
        print(error)
        error_status_code = error.status_code
        error_description = error.error['description']
        return jsonify({
            'success': False,
            'error': error_status_code,
            'message': error_description
        })

    return app
def create_app(config=None):
    """Create a Flask applicationlicaction.
    """
    # Instantiate Flask
    application = Flask(__name__)

    # Load application Config settings
    if config is not None:
        application.config.from_object('config.Config')

    # Setup Flask-SQLAlchemy
    db.init_app(application)

    # Setup Flask-Migrate
    migrate.init_app(application, db)
    
    # Setup Heroku
    heroku = Heroku(application)

    # Setup Flask-Mail
    mail.init_app(application)
    
    # Setup Flask-Principal
    principal.init_app(application)
    
    # Setup WTForms CSRFProtect
    csrf_protect.init_app(application)
        
    # Setup Flask-Blogging
    with application.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
        blog_engine.init_app(application, storage)
        
    from application.models.user_models import User
    @blog_engine.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))       

    @identity_loaded.connect_via(application)
    def on_identity_loaded(sender, identity):
        identity.user = current_user
        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))
        # Shortcut to the give admins "blogger" role.
        #if hasattr(current_user, "is_admin"):
            #if current_user.is_admin:
                #identity.provides.add(RoleNeed("blogger"))
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))
    # Register blueprints
    from application.views.misc_views import main_blueprint
    application.register_blueprint(main_blueprint)

    # Define bootstrap_is_hidden_field for flask-bootstrap's bootstrap_wtf.html
    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    application.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter

    # Setup an error-logger to send emails to application.config.ADMINS
    init_email_error_handler(application)

    # Setup Flask-User to handle user account related forms
    from .models.user_models import User, Role, MyRegisterForm

    db_adapter = SQLAlchemyAdapter(db, User)  # Setup the SQLAlchemy DB Adapter
    user_manager = UserManager(db_adapter, application,  # Init Flask-User and bind to application
                               register_form=MyRegisterForm)
    # Create admin
    global admin
    admin = flask_admin.Admin(application, 'Admin manager', template_mode='bootstrap3',)
    from .models.user_models import UserModelView,PostModelView, RoleModelView
    Post = storage.post_model
    admin.add_view(UserModelView(User, db.session))
    #admin.add_view(RoleModelView(Role, db.session))
    #admin.add_view(sqla.ModelView(Role, db.session))
    admin.add_view(PostModelView(Post, db.session))  
    admin.add_link(MenuLink(name='Index', category='Index', url='../'))  
    
    return application
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import register_renderer
from flask_nav.elements import Navbar, View, Subgroup
from flask_heroku import Heroku

from .nav import nav
from .nav import CustomRenderer

srp = Flask(__name__)
Bootstrap(srp)
Heroku(srp)
nav.init_app(srp)
register_renderer(srp, 'custom', CustomRenderer)
nav.register_element(
    'navbar',
    Navbar(
        View('Home', '.index'),
        Subgroup(
            'Character',
            View('Character Creation', '.startingCharacterCreation'),
            View('Stats', '.stats'),
            View('Advantages and Disadvantages',
                 '.advantagesAndDisadvantages'),
            View('Character Growth', '.characterGrowth'),
        ),
        Subgroup(
            'Combat',
            View('Combat Flow', '.combat'),
            View('Weapons', '.weapons'),
            View('Armor', '.armor'),
예제 #21
0
from app.decommissions.routes_decommissions import decommissions
from app.import_export.routes import import_export
from app.instances.routes_instances import instances
from app.logging.routes_logging import logs
from app.models.routes_models import models
from app.permissions.routes_permissions import permissions
from app.racks.racks_routes import racks
from app.stats.routes_stats import stats
from app.users.authentication import AuthManager
from app.users.routes_users import users
from flask import Flask, jsonify, render_template
from flask_heroku import Heroku
from settings import TEST_DB_URL

application = Flask(__name__)
heroku = Heroku(app=application)
AUTH_MANAGER = AuthManager()


class FlaskApp(Flask):
    def make_response(self, rv):
        if isinstance(rv, dict):
            rv = jsonify(rv)
        elif (
            isinstance(rv, tuple)
            and isinstance(rv[0], dict)
            and isinstance(rv[1], HTTPStatus)
        ):
            rv[0]["status"] = rv[1]
            rv = jsonify(rv[0]), rv[1]
        elif isinstance(rv, HTTPStatus):
예제 #22
0
from flask_heroku import Heroku
from flask_redis import Redis
from flask_sslify import SSLify
from flask_sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
from werkzeug.contrib.fixers import ProxyFix

from freight.api.controller import ApiController
from freight.constants import PROJECT_ROOT
from freight.utils.celery import ContextualCelery

api = ApiController(prefix='/api/0')
db = SQLAlchemy(session_options={})
celery = ContextualCelery()
heroku = Heroku()
redis = Redis()
sentry = Sentry(logging=True, level=logging.WARN)


def configure_logging(app):
    logging.getLogger().setLevel(getattr(logging, app.config['LOG_LEVEL']))


def create_app(_read_config=True, **config):
    from kombu import Queue

    app = flask.Flask(__name__,
                      static_folder=None,
                      template_folder=os.path.join(PROJECT_ROOT, 'templates'))
예제 #23
0
import telebot
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_heroku import Heroku

from server import plotting, messages
from server.models import Plot, Settings

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

bot = telebot.TeleBot(os.environ.get('API_TOKEN'))

server = Flask(__name__)
server.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
heroku = Heroku(server)
db = SQLAlchemy(server)


@bot.message_handler(commands=['start'])
def start(message):
    db.session.query(Settings).filter(
        Settings.chat_id == message.chat.id).delete()
    db.session.query(Plot).filter(Plot.chat_id == message.chat.id).delete()
    settings = Settings(message.chat.id)
    db.session.add(settings)
    db.session.commit()
    bot.send_message(message.chat.id, messages.hello)


@bot.message_handler(commands=['help'])
예제 #24
0
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from flask_heroku import Heroku
from environs import Env
import psycopg2
import json
import os

app = Flask(__name__)
CORS(app)
heroku = Heroku(app)

conn = psycopg2.connect(dbname="Capstone",
                        user="******",
                        password="******",
                        host="localhost",
                        port="5432")

S = "SELECT job, company, salary FROM scraped_info"

cur = conn.cursor()
res = cur.execute(S)
list_info = cur.fetchall()
print(S)

ENV = 'dev'
if ENV == 'dev':
    app.debug = True
    app.config["SQLALCHEMY_DATABASE_URI"] = conn
예제 #25
0
def get_heroku(app):
    heroku = Heroku(app)
    return heroku