def create_app(): app = Flask(__name__) CORS(app) basedir = os.path.abspath(__file__) app.config.update( dict( SECRET_KEY="subscribe secretkey", WTF_CSRF_SECRET_KEY="subscribe csrf secret key", SQLALCHEMY_DATABASE_URI="sqlite:///" + 'aws-ssm-list.db', SQLALCHEMY_TRACK_MODIFICATIONS=False, JSON_SORT_KEYS=False ) ) model.init_app(app) model.create_tables(app) return app
# ------------------------------------------------------------------------------ # This file holds all of the code that interacts with flask. # For instance, it does the geocoding part (address_to_lat_lng) # It dynamically generates the bounds based on the user's start and end location # Gets the crime records # ------------------------------------------------------------------------------ from math import cos, sin, radians from model import db, init_app from gmaps import Directions, Geocoding from shapely.geometry import LineString init_app() api = Directions() geocoding = Geocoding(sensor=False) # start and end coordinates in directions # reminder: results returns a list # results = api.directions((40.728783, -73.7897503), # (40.6497484, -73.97767999999999)) # # pretty formatting on json, it's great # print json.dumps(results, indent=2) def address_to_lat_lng(user_points): """ Generates a dictionary of the user's latitude and longitude based on address passed into json """ user_coords = {}
def load_fake_scores(): """Add scores for each user to db.""" users = User.query.all() for user in users: recipes = UserRecipe.query.filter_by(user_id=user.user_id).all() for recipe in recipes: score = randint(1, 5) upsert_score(recipe.recipe_id, user.user_id, score) def init_app(): # So that we can use Flask-SQLAlchemy, we'll make a Flask app. from flask import Flask app = Flask(__name__) connect_to_db(app) print "Connected to DB." if __name__ == "__main__": init_app() db.create_all() load_food_type() load_fake_users() load_fake_ingredients() load_recipes(INGREDIENTS) load_fake_user_recipes() load_fake_scores()
from services import dicom_service import model from api import api_blueprint from view import view_blueprint __author__ = 'Tung.Luu' _logger = logging.getLogger(__name__) app = Flask(__name__, static_url_path='/static') # config app from file config.py app.config.from_pyfile("config.py", silent=True) # databse setup model.init_app(app) # add blueprint apis app.register_blueprint(api_blueprint) # add blueprint web views app.register_blueprint(view_blueprint) # serve files @app.route('/data/<path:filename>') def download_file(filename): return send_from_directory( app.config['DATA_DIR'], filename, as_attachment=False)
def create_app(config_name='default'): app = Flask(__name__) app.config.from_object(config[config_name]) init_app(app) app.register_blueprint(route_bp) return app
def init(app): with app.app_context(): model.init_app(app) @app.route('/login', methods=['GET', 'POST']) def login(): if 'user_id' in session: return redirect('/') if request.method == 'POST': data = request.form.to_dict(flat=True) result = model.authenticate(data['username'], data['password']) if isinstance(result, model.User): session.permanent = True session['user_id'] = result.id session['user_admin'] = result.admin return redirect('/') else: return router['login'](['invalid']) return router['login']() @app.route('/register', methods=['GET', 'POST']) def register(): if 'user_id' in session: return redirect('/') if request.method == 'POST': data = request.form.to_dict(flat=True) try: model.create_user(data) except ValueError: return router['register'](['invalid']) except Exception: return router['register'](['other']) return router['login'](['success']) return router['register']() @app.route('/') def main(): if 'user_id' not in session: return redirect('/login') if session['user_admin'] is True: return redirect('/reports?type=1') else: return router['main']() @app.route('/reports') def report(): if 'user_id' not in session: return redirect('/login') if not session['user_admin']: return router['main']() report_type = request.args.get('type') if report_type == '2': return router['report_two']([], data=model.get_second_report()) elif report_type == '3': return router['report_three']([], data=model.get_third_report()) else: # assume default report return router['report_one']([], data=model.get_first_report()) @app.route('/reset', methods=['GET', 'POST']) def reset(): if 'user_id' not in session: return redirect('/login') if not session['user_admin']: return router['main']() if request.method == 'POST': model.reset() return redirect('/reports') return router['reset']() @app.route('/details') def details(): if 'user_id' not in session: return redirect('/login') user, usernames = model.details(session['user_id']) return { 'user': convert(user), 'usernames': usernames } @app.route('/gift', methods=['POST']) def gift(): data = request.get_json() try: model.gift(session['user_id'], **data) return jsonify(success=True) except Exception: return abort(400) @app.route('/redeem', methods=['POST']) def redeem(): data = request.get_json() try: model.redeem(session['user_id'], **data) return jsonify(success=True) except Exception: return abort(400) @app.route('/history') def history(): if 'user_id' not in session: return redirect('/login') return router['history']([], data=model.history(session['user_id'])) @app.route('/logout', methods=['POST']) def logout(): if 'user_id' in session: del session['user_id'] del session['user_admin'] session.permanent = False return redirect('/login')
def register(app): with app.app_context(): model.init_app(app) @app.route('/', methods=['GET', 'POST']) def login(): if 'user_id' in session: return redirect(url_for('status')) if request.method == 'POST': data = request.form.to_dict(flat=True) email = data['email'] password = data['password'] result = model.authenticate(email, password) if isinstance(result, model.User): session.permanent = True session['user_id'] = result.id session['user_admin'] = result.admin return redirect(url_for('status')) else: return router['login'](['invalid']) return router['login']([]) @app.route('/admin', methods=['GET', 'POST']) def admin(): if 'user_id' in session: if 'user_admin' in session and session['user_admin'] is True: return redirect(url_for('add_spot')) else: return redirect(url_for('status')) if request.method == 'POST': data = request.form.to_dict(flat=True) email = data['email'] password = data['password'] result = model.admin(email, password) if isinstance(result, model.User): session.permanent = True session['user_id'] = result.id session['user_admin'] = result.admin return redirect(url_for('add_spot')) else: return router['admin'](['invalid']) return router['admin']([]) @app.route('/add_spot', methods=['GET', 'POST']) def add_spot(): if 'user_id' in session: if 'user_admin' not in session or session['user_admin'] is False: return redirect(url_for('status')) else: return redirect(url_for('admin')) if request.method == 'POST': data = request.form.to_dict(flat=True) if not data['location']: return router['add_spot'](['invalid'], data=model.garages()) model.create(model.Spot, data) return router['add_spot'](['success'], data=model.garages()) return router['add_spot']([], data=model.garages()) @app.route('/remove_spot', methods=['GET', 'POST']) def remove_spot(): if 'user_id' in session: if 'user_admin' not in session or session['user_admin'] is False: return redirect(url_for('status')) else: return redirect(url_for('admin')) if request.method == 'POST': data = request.form.to_dict(flat=True) model.remove(data['spot_id']) return router['remove_spot'](['success'], data=model.garages()) return router['remove_spot']([], data=model.garages()) @app.route('/remove_reservation', methods=['GET', 'POST']) def remove_reservation(): if 'user_id' in session: if 'user_admin' not in session or session['user_admin'] is False: return redirect(url_for('status')) else: return redirect(url_for('admin')) if request.method == 'POST': data = request.form.to_dict(flat=True) model.delete(model.Reservation, data['reservation_id']) return router['remove_reservation'](['success'], data=model.reservations()) return router['remove_reservation']([], data=model.reservations()) @app.route('/remove_user', methods=['GET', 'POST']) def remove_user(): if 'user_id' in session: if 'user_admin' not in session or session['user_admin'] is False: return redirect(url_for('status')) else: return redirect(url_for('admin')) if request.method == 'POST': data = request.form.to_dict(flat=True) model.kill(data['user_id']) return router['remove_user'](['success'], data=model.plebs()) return router['remove_user']([], data=model.plebs()) @app.route('/register', methods=['GET', 'POST']) def register(): if 'user_id' in session: return redirect(url_for('status')) if request.method == 'POST': data = request.form.to_dict(flat=True) try: model.register(data) except ValueError as e: return router['register'](['mismatch']) except Exception as e: return router['register'](['invalid']) return router['login'](['success']) return router['register']([]) @app.route('/status') def status(): if 'user_id' not in session: return redirect(url_for('login')) return router['status'](['success']) @app.route('/logout', methods=['POST']) def logout(): if 'user_id' in session: del session['user_id'] del session['user_admin'] session.permanent = False return redirect(url_for('login')) @app.route('/details') def details(): user_id = request.args.get('user_id') if user_id is None: if 'user_id' not in session: return redirect(url_for('login')) else: user_id = session['user_id'] return jsonify(model.inform(user_id)) @app.route('/reserve/<garage_id>', methods=['POST']) def reserve(garage_id): user_id = request.args.get('user_id') if user_id is None: if 'user_id' not in session: return redirect(url_for('login')) else: user_id = session['user_id'] return jsonify(model.reserve(user_id, garage_id)) @app.route('/occupy', methods=['POST']) def occupy(): user_id = request.args.get('user_id') if user_id is None: if 'user_id' not in session: return redirect(url_for('login')) else: user_id = session['user_id'] return jsonify(model.occupy(user_id)) @app.route('/clear', methods=['POST']) def clear(): user_id = request.args.get('user_id') if user_id is None: if 'user_id' not in session: return redirect(url_for('login')) else: user_id = session['user_id'] return jsonify(model.clear(user_id)) @app.route('/info') def info(): return router['info']([]) @app.route('/about') def about(): return router['about']([]) @app.route('/auth', methods=['POST']) def auth(): email = request.args.get('email') password = request.args.get('password') result = model.authenticate(email, password) if isinstance(result, model.User): return jsonify(model.convert(result)) else: return abort(401) @app.route('/signup', methods=['POST']) def signup(): data = request.get_json() try: model.register(data) return jsonify({'result': True}) except Exception as e: return abort(400) return app