def create_app(config_name): app = Flask(__name__) app.host = 'localhost' api = Api() flask_bcrypt = Bcrypt() CORS(app) jwt = JWTManager() app.config.from_object(config_by_name[config_name]) app.config['JWT_TOKEN_LOCATION'] = ['cookies'] app.config['JWT_COOKIE_SECURE'] = False app.config['JWT_COOKIE_CSRF_PROTECT'] = True app.config['JWT_SECRET_KEY'] = os.getenv('JWT_ENV_FILE') app.config['JWT_ACCESS_COOKIE_PATH'] = '/user/login/' app.config['DYNAMO_TABLES'] = [ dict( TableName='Users', KeySchema=[dict(AttributeName='username', KeyType='HASH')], AttributeDefinitions=[ dict(AttributeName='password', AttributeType='S'), dict(AttributeName='firstname', AttributeType='S'), dict(AttributeName='lastname', AttributeType='S') ] # ProvisionedThroughput = dict(ReadCapacityUnits=5, WriteCapacityUnits=5) ) ] dynamo = Dynamo() with app.app_context(): # cors.init_app(app) dynamo.init_app(app) from app.controllers.user_controller import api as user_ns api.add_namespace(user_ns, path='/user') api.init_app(app) flask_bcrypt.init_app(app) jwt.init_app(app) socket.init_app(app, cors_allowed_origins="*") return app
from flask_dynamo import Dynamo from flask_security import login_required from flask_jsglue import JSGlue from flask_cors import CORS, cross_origin #---------------------------------------------------------------------------- # APPLICATION SETUP # Flask application = Flask(__name__) # Flask Configuration application.config.from_pyfile('config.py') # Application database connection (for user management only) application_db = flask_sqlalchemy.SQLAlchemy(application) # Remote database (for operational data) dynamo_db = Dynamo(application) # Expose Flask Routes to client-side jsglue = JSGlue(application) # Enable CORS on select routes. cors = CORS(application, resources={r"/api/*": {"origins": "*"}}) logging.getLogger('flask_cors').level = logging.ERROR # application imports (these use the Flask "application" object, so get imported here) from .admin import admin_blueprint from .api import api_blueprint from .api.db_interface import get_all_fishfries, get_one_fishfry, hide_one_fishfry, make_one_fishfry, update_one_fishfry, delete_one_fishfry from .models import FishFryFeature, FishFryProperties, FishFryEvent, FishFryMenu, Feature from .forms import FishFryForm, EventForm, postprocess_events from .forms import postprocess_boolean as postbool from .forms import preprocess_boolean as prebool from .utils import sort_records, handle_utc
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', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) boto_sess = Session( region_name='us-east-2', aws_access_key_id='AKIA2XEGOWGBGB36SBA2', aws_secret_access_key='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') app.config['DYNAMO_SESSION'] = boto_sess dynamo = Dynamo() dynamo.init_app(app) beerReviews = dynamo.tables['beerReviews'] wineReviews = dynamo.tables['wineReviews'] 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 # a simple page that says hello @app.route("/") def home(): return render_template("index.html") @app.route("/addBeer") def addBeer(): return render_template("addBeer.html") @app.route("/searchBeer") def searchBeer(): return render_template("searchBeer.html", data=[]) @app.route("/addWine") def addWine(): return render_template("addWine.html") @app.route("/searchWine") def searchWine(): return render_template("searchWine.html", data=[]) @app.route('/wines') def get_wines(): query = '''SELECT * FROM Wine ORDER BY RANDOM() LIMIT 500''' wines = queryDB(query) if len(wines) == 0: abort(404) return jsonify({'success': True, 'wines': wines}) @app.route('/beers') def get_beers(): query = '''SELECT * FROM Beer ORDER BY RANDOM() LIMIT 500''' beers = queryDB(query) if len(beers) == 0: abort(404) return jsonify({'success': True, 'beers': beers}) @app.route('/beers/search', methods=['POST']) def search_beers(): searchName = request.form['name'] if len(searchName) == 0: query = '''SELECT beer.id , beer.brewery_id , beer.name , beer.style , beer.abv , brewery.name , brewery.city , brewery.state FROM Beer beer, Brewery brewery WHERE beer.brewery_id = brewery.id ORDER BY RANDOM() LIMIT 500''' beers = queryDB(query) else: query = '''SELECT beer.id , beer.brewery_id , beer.name , beer.style , beer.abv , brewery.name , brewery.city , brewery.state FROM Beer beer, Brewery brewery WHERE beer.brewery_id = brewery.id AND beer.name LIKE ? ORDER BY RANDOM() LIMIT 500''' query_params = ('%' + searchName + '%', ) beers = queryDB(query, query_params) if len(beers) == 0: abort(404) return render_template("searchBeer.html", data=beers) @app.route('/wines/search', methods=['POST']) def search_wines(): searchName = request.form['name'] if len(searchName) == 0: query = '''SELECT wine.id , wine.winery_id , wine.name , wine.variety , wine.rating , winery.name , winery.city , winery.state FROM Wine wine, Winery winery WHERE wine.winery_id = winery.id ORDER BY RANDOM() LIMIT 500''' wines = queryDB(query) else: query = '''SELECT wine.id , wine.winery_id , wine.name , wine.variety , wine.rating , winery.name , winery.city , winery.state FROM Wine wine, Winery winery WHERE wine.winery_id = winery.id AND wine.name LIKE ? ORDER BY RANDOM() LIMIT 500''' query_params = ('%' + searchName + '%', ) wines = queryDB(query, query_params) if len(wines) == 0: abort(404) return render_template("searchWine.html", data=wines) @app.route('/beers/<int:beer_id>', methods=['GET']) def get_beer(beer_id): beer = queryBeerByID(beer_id) if len(beer) == 0: abort(404) return render_template("updateBeer.html", data=beer_id) @app.route('/wines/<int:wine_id>', methods=['GET']) def get_wine(wine_id): wine = queryWineByID(wine_id) if len(wine) == 0: abort(404) return render_template("updateWine.html", data=wine_id) @app.route('/deleteWine/<int:wine_id>', methods=['POST']) def delete_wine(wine_id): query = '''DELETE FROM wine WHERE id = ?''' query_params = (wine_id, ) try: queryDB(query, query_params) return jsonify({'success': True, 'deleted': wine_id}) except Exception: abort(422) @app.route('/deleteBeer/<int:beer_id>', methods=['POST']) def delete_beer(beer_id): query = '''DELETE FROM beer WHERE id = ?''' query_params = (beer_id, ) try: queryDB(query, query_params) return jsonify({'success': True, 'deleted': beer_id}) except Exception: abort(422) @app.route('/wines', methods=['POST']) def create_wine(): data = request.form name = data.get('name') or None variety = data.get('variety') or None winery_name = data.get('winery') or None rating = data.get('rating') or None city = data.get('city') or None state = data.get('state') or None try: existing_wine = '''SELECT * FROM wine WHERE name = ? AND variety = ? ''' wine_params = ( name, variety, ) existing_data = queryDB(existing_wine, wine_params) if len(existing_data) == 0: existing_winery = '''SELECT id FROM winery WHERE wname = ? AND city = ? AND state = ? ''' winery_params = ( winery_name, city, state, ) existing_data = queryDB(existing_winery, winery_params) if len(existing_data) > 0: winery_id = existing_data[0][0] else: id_query = '''SELECT MAX(id) AS max_id FROM winery''' winery_id = queryDB(id_query)[0][0] + 1 query = '''INSERT INTO winery (id, name, city, state, country) VALUES (?,?,?,?,?) ''' params = ( winery_id, winery_name, city, state, 'US', ) queryDB(query, params) id_query = '''SELECT MAX(id) AS max_id FROM wine''' new_wine_id = queryDB(id_query)[0][0] + 1 query = '''INSERT INTO wine (id, name, variety, rating, winery_id) VALUES (?,?,?,?,?) ''' params = ( new_wine_id, name, variety, rating, winery_id, ) queryDB(query, params) return jsonify({'success': True, 'created': new_wine_id}) except Exception: abort(422) @app.route('/beers', methods=['POST']) def create_beer(): data = request.form name = data.get('name') or None style = data.get('style') or None brewery_name = data.get('brewery') or None abv = data.get('alcoholContent') or None city = data.get('city') or None state = data.get('state') or None try: existing_beer = '''SELECT * FROM beer WHERE name = ? AND style = ? ''' beer_params = ( name, style, ) existing_data = queryDB(existing_beer, beer_params) if len(existing_data) == 0: existing_brewery = '''SELECT id FROM brewery WHERE name = ? AND city = ? AND state = ? ''' brewery_params = ( brewery_name, city, state, ) existing_data = queryDB(existing_brewery, brewery_params) if len(existing_data) > 0: brewery_id = existing_data[0][0] else: id_query = '''SELECT MAX(id) AS max_id FROM brewery''' brewery_id = queryDB(id_query)[0][0] + 1 query = '''INSERT INTO brewery (id, name, city, state, country) VALUES (?,?,?,?,?) ''' params = ( brewery_id, brewery_name, city, state, 'US', ) queryDB(query, params) id_query = '''SELECT MAX(id) AS max_id FROM beer''' new_beer_id = queryDB(id_query)[0][0] + 1 query = '''INSERT INTO beer (id, name, style, abv, brewery_id) VALUES (?,?,?,?,?) ''' params = ( new_beer_id, name, style, abv, brewery_id, ) queryDB(query, params) return jsonify({'success': True, 'created': new_beer_id}) except Exception: abort(422) @app.route('/wines/<int:wine_id>', methods=['POST']) def edit_wine(wine_id): existing_data = queryWineByID(wine_id) data = request.form name = data.get('name') variety = data.get('variety') rating = data.get('rating') if name or variety or rating: if len(name) == 0: name = existing_data[0][0] if len(variety) == 0: variety = existing_data[0][1] if len(rating) == 0: rating = existing_data[0][2] query = '''UPDATE wine SET name = ?, variety = ?, rating = ? WHERE id = ?''' params = ( name, variety, rating, wine_id, ) queryDB(query, params) winery_id = existing_data[0][7] winery_name = data.get('winery_name') city = data.get('city') state = data.get('state') if winery_name or city or state: if len(winery_name) == 0: winery_name = existing_data[0][3] if len(city) == 0: city = existing_data[0][4] if len(state) == 0: state = existing_data[0][5] query = '''UPDATE winery SET name = ?, city = ?, state = ? WHERE id = ?''' params = ( winery_name, city, state, winery_id, ) queryDB(query, params) return jsonify({'success': True, 'updated': winery_id}) @app.route('/beers/<int:beer_id>', methods=['POST']) def edit_beer(beer_id): existing_data = queryBeerByID(beer_id) data = request.form try: name = data.get('name') style = data.get('style') abv = data.get('alcoholContent') if name or style or abv: if len(name) == 0: name = existing_data[0][0] if len(style) == 0: style = existing_data[0][1] if len(abv) == 0: abv = existing_data[0][2] query = '''UPDATE beer SET name = ?, style = ?, abv = ? WHERE id = ?''' params = ( name, style, abv, beer_id, ) queryDB(query, params) brewery_id = existing_data[0][7] brewery_name = data.get('brewery_name') city = data.get('city') state = data.get('state') if brewery_name or city or state: if len(brewery_name) == 0: brewery_name = existing_data[0][3] if len(city) == 0: city = existing_data[0][4] if len(state) == 0: state = existing_data[0][5] query = '''UPDATE brewery SET name = ?, city = ?, state = ? WHERE id = ?''' params = ( brewery_name, city, state, brewery_id, ) queryDB(query, params) return jsonify({'success': True, 'updated': beer_id}) except Exception: abort(422) @app.route('/localbeers') def localBeers(): query = '''SELECT * FROM local_beers LIMIT 500''' local_beers = queryDB(query) if len(local_beers) == 0: abort(404) return render_template("localBeers.html", data=local_beers) @app.route('/heatmap') def heatMap(): map = folium.Map(location=[38, -98], zoom_start=5) locations = getLocations() address_latlng = [] for location in locations: address = geocoder.osm(location[0] + ', ' + location[1]) if address.lat and address.lng: address_latlng.append([address.lat, address.lng]) HeatMap(address_latlng).add_to(map) return map._repr_html_() @app.route('/beers/<int:beer_id>/reviews', methods=['GET']) def get_beer_reviews(beer_id): query = '''SELECT * FROM beer WHERE id = ?''' param = (beer_id, ) name = queryDB(query, param)[0][1] reviews = beerReviews.query( KeyConditionExpression=Key('beer_id').eq(beer_id))['Items'] return render_template("beerReviews.html", data={ 'id': beer_id, 'name': name, 'reviews': reviews }) @app.route('/beers/<int:beer_id>/reviews/add') def addBeerReview(beer_id): return render_template("addBeerReviews.html", id=beer_id) @app.route('/beers/<int:beer_id>/reviews', methods=['POST']) def add_beer_review(beer_id): data = request.form review = {} review['beer_id'] = beer_id review['username'] = data.get('username') review['date'] = date.today().strftime("%Y-%m-%d") attributes = ['text', 'taste', 'smell', 'look', 'feel', 'overall'] for attribute in attributes: if data.get(attribute): review[attribute] = data.get(attribute) try: beerReviews.put_item(Item=review) return jsonify({'success': True}) except Exception: abort(422) @app.route('/wines/<int:wine_id>/reviews', methods=['GET']) def get_wine_reviews(wine_id): query = '''SELECT * FROM wine WHERE id = ?''' param = (wine_id, ) name = queryDB(query, param)[0][1] reviews = wineReviews.query( KeyConditionExpression=Key('wine_id').eq(wine_id))['Items'] return render_template("wineReviews.html", data={ 'id': wine_id, 'name': name, 'reviews': reviews }) @app.route('/wines/<int:wine_id>/reviews/add') def addWineReview(wine_id): return render_template("addWineReviews.html", id=wine_id) @app.route('/wines/<int:wine_id>/reviews', methods=['POST']) def add_wine_review(wine_id): data = request.form review = {} review['wine_id'] = wine_id review['reviewers'] = data.get('username') review['date'] = date.today().strftime("%Y-%m-%d") attributes = ['text', 'taste', 'smell', 'look', 'feel', 'overall'] for attribute in attributes: if data.get(attribute): review[attribute] = data.get(attribute) try: wineReviews.put_item(Item=review) return jsonify({'success': True}) except Exception: abort(422) def getLocations(): query = '''SELECT city , state FROM brewery UNION ALL SELECT city , state FROM winery LIMIT 100''' locations = queryDB(query) return locations def queryDB(query, params=None): with sqlite3.connect(DATABASE) as conn: try: cursor = conn.cursor() if params: cursor.execute(query, params) result = cursor.fetchall() else: cursor.execute(query) result = cursor.fetchall() cursor.close() except Exception: conn.rollback() finally: return result def queryWineByID(wine_id): query = '''SELECT wine.name , wine.variety , wine.rating , winery.name AS winery_name , winery.city , winery.state , wine.id , wine.winery_id FROM Wine wine, Winery winery WHERE wine.winery_id = winery.id AND wine.id = ?''' return queryDB(query, (wine_id, )) def queryBeerByID(beer_id): query = '''SELECT beer.name , beer.style , beer.abv , brewery.name AS brewery_name , brewery.city , brewery.state , beer.id , beer.brewery_id FROM Beer beer, Brewery brewery WHERE beer.brewery_id = brewery.id AND beer.id = ?''' return queryDB(query, (beer_id, )) @app.errorhandler(404) def not_found(error): return jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "bad request" }), 400 @app.errorhandler(500) def server_error(error): return jsonify({ "success": False, "error": 500, "message": "internal server error" }), 500 from . import db db.init_app(app) return app
from uuid import uuid4 from flask import Blueprint, current_app, Flask, jsonify, redirect, render_template, request, session, url_for from flask_dynamo import Dynamo from flask_login import login_required, login_user, logout_user, LoginManager, UserMixin from flask_wtf import FlaskForm from flask_wtf.csrf import generate_csrf from wtforms import PasswordField, StringField, SubmitField, TextAreaField from wtforms.validators import InputRequired # # application objects and factory # blueprint = Blueprint('app', __name__) # pylint: disable=invalid-name dynamo = Dynamo() # pylint: disable=invalid-name login_manager = LoginManager() # pylint: disable=invalid-name TABLE_NAME = 'bmarks_links' def create_app(): """application factory""" app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or os.urandom(32) app.config['DYNAMO_TABLES'] = [{ 'TableName': TABLE_NAME, 'KeySchema': [{ 'AttributeName': 'id', 'KeyType': 'HASH'
def test_valid_local_settings(local_app): local_app.config['DYNAMO_LOCAL_PORT'] = 8000 local_app.config['DYNAMO_LOCAL_HOST'] = 'localhost' Dynamo(local_app)
def test_local_settings_missing_local_host(local_app): local_app.config['DYNAMO_LOCAL_PORT'] = 8000 with pytest.raises(ConfigurationError): Dynamo(local_app)
def test_local_settings_missing_local_port(local_app): local_app.config['DYNAMO_LOCAL_HOST'] = 'localhost' with pytest.raises(ConfigurationError): Dynamo(local_app)
'TableName': 'ItemTable', 'AttributeDefinitions': [{ 'AttributeName': 'name', 'AttributeType': 'S' }], 'KeySchema': [{ 'AttributeName': 'name', 'KeyType': 'HASH' }], 'BillingMode': 'PAY_PER_REQUEST' }] application.config['DYNAMO_SESSION'] = boto_sess dynamo = Dynamo(application) with application.app_context(): dynamo.create_all() class Item(Resource): # parses json in incoming http request # we only want price in the json body # name is provided in the route parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help="Cannot be left blank")
def dynamo(app, request): dynamo = Dynamo(app) return dynamo
def test_can_share_contexts(app, dynamo): with app.app_context(): d = Dynamo() assert d.tables is not None assert d.connection is not None
from flask_jwt_extended import JWTManager, create_access_token #from pymongo import MongoClient from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_httpauth import HTTPBasicAuth import boto3 apis = Flask(__name__) auth = HTTPBasicAuth() ## pymongo Config # client = MongoClient('mongodb://localhost:27017/') # db = client.viralinDB ## flask_dynamo dynamo = Dynamo(apis) ## DynamoDB Config # client dbsession = boto3.Session(profile_name='admin-db') dynamo_client = dbsession.client('dynamodb') # # resource dynamo_resource = dbsession.resource('dynamodb') sellers = dynamo_resource.Table('sellers') promotors = dynamo_resource.Table('promotors') contents = dynamo_resource.Table('contents') contentpromo = dynamo_resource.Table('content-promotor') ## flask-JWT-extended apis.debug = True apis.config['JWT_SECRET_KEY'] = 'laskarkalong2019'
def init_app(app): dynamo = Dynamo(app) dynamo.create_all() return app
def create_app(test_config=None): """Create and configure an instance of the Flask dndtools application. Args: test_config: dict containing pytest configuration settings """ app = Flask(__name__, instance_relative_config=True) # for sqlite backend # app.config.from_mapping( # DATABASE=os.path.join(app.instance_path, 'spells.sql') # ) if os.environ.get('FLASK_ENV', None) == 'development': app.config['DYNAMO_ENABLE_LOCAL'] = True app.config['DYNAMO_LOCAL_HOST'] = 'localhost' app.config['DYNAMO_LOCAL_PORT'] = 8000 app.config['DYNAMO_TABLES'] = [{ 'TableName': 'spells', 'KeySchema': [dict(AttributeName='name', KeyType='HASH')], 'AttributeDefinitions': [dict(AttributeName='name', AttributeType='S')], 'ProvisionedThroughput': dict(ReadCapacityUnits=5, WriteCapacityUnits=5) }] if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) app.config['SLACK_VERIFICATION_TOKEN'] = os.environ.get( 'SLACK_VERIFICATION_TOKEN', None) app.config['SLACK_TEAM_ID'] = os.environ.get('SLACK_TEAM_ID', None) app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', None) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from . import db db.init_app(app) from . import condition app.register_blueprint(condition.bp) from . import roll app.register_blueprint(roll.bp) from . import spellbook app.register_blueprint(spellbook.bp) dynamo = Dynamo() dynamo.init_app(app) return app
from flask import Flask from app.main.config import config_by_name from flask_dynamo import Dynamo dynamo = Dynamo() def create_app(config_name): app = Flask(__name__) app.config.from_object(config_by_name[config_name]) # Initalize dynamodb dynamo.init_app(app) return app
def test_local_settings_missing_local_configs(local_app): with pytest.raises(ConfigurationError): Dynamo(local_app)
MTA_API_KEY = "a7274011-3c23-4fd2-9641-dcbe0d873f47" app = Flask(__name__) ask = Ask(app, "/") logging.getLogger("flask_ask").setLevel(logging.DEBUG) # DynamoDB config app.config['DYNAMO_TABLES'] = [ { 'TableName': 'buses', 'KeySchema': [dict(AttributeName='user_id', KeyType='HASH')], 'AttributeDefinitions': [dict(AttributeName='user_id', AttributeType='S')], 'ProvisionedThroughput': dict(ReadCapacityUnits=5, WriteCapacityUnits=5) } ] dynamo = Dynamo(app) # create tables if doesn't exist with app.app_context(): dynamo.create_all() @ask.launch def welcome(): # check if user already has a saved bus response = dynamo.tables['buses'].get_item(Key={'user_id': session.user.userId }) if 'Item' in response and 'bus_stop' in response['Item']: item = response['Item'] session.attributes['bus_route'] = item['bus_route']
def dynamo(app): dynamo = Dynamo(app) return dynamo