class mount_file_function(object): def __init__(self, function, host='0.0.0.0', port=5000, path='/model/predict'): debug_mode = False if 'PYTHON_DEBUG' in os.environ: if os.environ['PYTHON_DEBUG'].lower() == 'true': debug_mode = True self.app = FlaskAPI(__name__) self.app.config['debug'] = debug_mode self.app.config['function'] = function self.host = host self.port = port self.path = path if check_file_function_is_valid(self.app.config['function']): #define the class we're mounting onto post tool = filesAPI #if we're in debug mode we will need to collect usage statistics if True: tool.debug_mode = True tool.collection_tool = usage_collection() else: tool.debug_mode = False #store a link to the app in tool tool.app = self.app #create the rule for /model/predict self.app.add_url_rule(self.path, view_func=tool.as_view('UserAPI')) #run the app self.app.run(host=self.host, port=self.port, debug=self.app.config['debug']) else: #if the function has bad inputs reject it raise Exception("BAD ARGUMENTS SENT TO FUNCTION")
def create_app(config_name): 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) from . import routes app.add_url_rule('/bucketlists', methods=['GET', 'POST'], view_func=routes.bucketlists) app.add_url_rule('/bucketlists/<int:id>', methods=['GET', 'PUT', 'DELETE'], view_func=routes.manipulations) return app
def create_app(config_filename=None): """create app.""" app = FlaskAPI(__name__) per_page = int( os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE))) per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE app.config['BUKUSERVER_PER_PAGE'] = per_page url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE) if url_render_mode not in ('full', 'netloc'): url_render_mode = views.DEFAULT_URL_RENDER_MODE app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode app.config['SECRET_KEY'] = os.getenv( 'BUKUSERVER_SECRET_KEY') or os.urandom(24) app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE']) app.app_context().push() setattr(flask.g, 'bukudb', bukudb) @app.shell_context_processor def shell_context(): """Shell context definition.""" return {'app': app, 'bukudb': bukudb} app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc # pylint: disable=no-member Bootstrap(app) admin = Admin(app, name='Buku Server', template_mode='bootstrap3', index_view=views.CustomAdminIndexView( template='bukuserver/home.html', url='/')) # routing # api app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET']) app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT']) app.add_url_rule('/api/network_handle', 'networkk_handle', network_handle_detail, methods=['POST']) app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE']) app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmarks', refresh_bookmarks, methods=['POST']) app.add_url_rule('/api/bookmarks/<id>', 'bookmark_api', bookmark_api, methods=['GET', 'PUT', 'DELETE']) app.add_url_rule('/api/bookmarks/<id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST']) app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET']) app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET']) app.add_url_rule('/api/bookmarks/<starting_id>/<ending_id>', 'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE']) app.add_url_rule('/api/bookmarks/search', 'search_bookmarks', search_bookmarks, methods=['GET', 'DELETE']) # non api admin.add_view( views.BookmarkModelView(bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode)) admin.add_view(views.TagModelView(bukudb, 'Tags', page_size=per_page)) admin.add_view( views.StatisticView(bukudb, 'Statistic', endpoint='statistic')) return app
def create_app(db_file=None): """create app.""" app = FlaskAPI(__name__) per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE))) per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE app.config['BUKUSERVER_PER_PAGE'] = per_page url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE) if url_render_mode not in ('full', 'netloc'): url_render_mode = views.DEFAULT_URL_RENDER_MODE app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24) disable_favicon = os.getenv('BUKUSERVER_DISABLE_FAVICON', 'false') app.config['BUKUSERVER_DISABLE_FAVICON'] = \ False if disable_favicon.lower() in ['false', '0'] else bool(disable_favicon) open_in_new_tab = os.getenv('BUKUSERVER_OPEN_IN_NEW_TAB', 'false') app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \ False if open_in_new_tab.lower() in ['false', '0'] else bool(open_in_new_tab) app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') or db_file bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE']) app.app_context().push() setattr(flask.g, 'bukudb', bukudb) @app.shell_context_processor def shell_context(): """Shell context definition.""" return {'app': app, 'bukudb': bukudb} app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc # pylint: disable=no-member Bootstrap(app) admin = Admin( app, name='Buku Server', template_mode='bootstrap3', index_view=views.CustomAdminIndexView( template='bukuserver/home.html', url='/' ) ) # routing # api tag_api_view = ApiTagView.as_view('tag_api') app.add_url_rule('/api/tags', defaults={'tag': None}, view_func=tag_api_view, methods=['GET']) app.add_url_rule('/api/tags/<tag>', view_func=tag_api_view, methods=['GET', 'PUT']) bookmark_api_view = ApiBookmarkView.as_view('bookmark_api') app.add_url_rule('/api/bookmarks', defaults={'rec_id': None}, view_func=bookmark_api_view, methods=['GET', 'POST', 'DELETE']) app.add_url_rule('/api/bookmarks/<int:rec_id>', view_func=bookmark_api_view, methods=['GET', 'PUT', 'DELETE']) app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmark', refresh_bookmark, defaults={'rec_id': None}, methods=['POST']) app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST']) app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET']) app.add_url_rule('/api/network_handle', 'network_handle', handle_network, methods=['POST']) bookmark_range_api_view = ApiBookmarkRangeView.as_view('bookmark_range_api') app.add_url_rule( '/api/bookmarks/<int:starting_id>/<int:ending_id>', view_func=bookmark_range_api_view, methods=['GET', 'PUT', 'DELETE']) bookmark_search_api_view = ApiBookmarkSearchView.as_view('bookmark_search_api') app.add_url_rule('/api/bookmarks/search', view_func=bookmark_search_api_view, methods=['GET', 'DELETE']) # non api admin.add_view(views.BookmarkModelView( bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode)) admin.add_view(views.TagModelView( bukudb, 'Tags', page_size=per_page)) admin.add_view(views.StatisticView( bukudb, 'Statistic', endpoint='statistic')) return app
def create_app(db_file=None): """create app.""" app = FlaskAPI(__name__) per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE))) per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE app.config['BUKUSERVER_PER_PAGE'] = per_page url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE) if url_render_mode not in ('full', 'netloc'): url_render_mode = views.DEFAULT_URL_RENDER_MODE app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24) app.config['BUKUSERVER_DISABLE_FAVICON'] = \ get_bool_from_env_var('BUKUSERVER_DISABLE_FAVICON', True) app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \ get_bool_from_env_var('BUKUSERVER_OPEN_IN_NEW_TAB', False) app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') or db_file reverse_proxy_path = os.getenv('BUKUSERVER_REVERSE_PROXY_PATH') if reverse_proxy_path: if not reverse_proxy_path.startswith('/'): print('Warning: reverse proxy path should include preceding slash') if reverse_proxy_path.endswith('/'): print('Warning: reverse proxy path should not include trailing slash') app.config['REVERSE_PROXY_PATH'] = reverse_proxy_path if ReverseProxyPrefixFix: ReverseProxyPrefixFix(app) else: raise ImportError('Failed to import ReverseProxyPrefixFix') bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE']) app.app_context().push() setattr(flask.g, 'bukudb', bukudb) @app.shell_context_processor def shell_context(): """Shell context definition.""" return {'app': app, 'bukudb': bukudb} app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc # pylint: disable=no-member Bootstrap(app) admin = Admin( app, name='buku server', template_mode='bootstrap3', index_view=views.CustomAdminIndexView( template='bukuserver/home.html', url='/' ) ) # routing # api tag_api_view = ApiTagView.as_view('tag_api') app.add_url_rule('/api/tags', defaults={'tag': None}, view_func=tag_api_view, methods=['GET']) app.add_url_rule('/api/tags/<tag>', view_func=tag_api_view, methods=['GET', 'PUT']) bookmark_api_view = ApiBookmarkView.as_view('bookmark_api') app.add_url_rule('/api/bookmarks', defaults={'rec_id': None}, view_func=bookmark_api_view, methods=['GET', 'POST', 'DELETE']) app.add_url_rule('/api/bookmarks/<int:rec_id>', view_func=bookmark_api_view, methods=['GET', 'PUT', 'DELETE']) app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmark', refresh_bookmark, defaults={'rec_id': None}, methods=['POST']) app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST']) app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET']) app.add_url_rule('/api/network_handle', 'network_handle', handle_network, methods=['POST']) bookmark_range_api_view = ApiBookmarkRangeView.as_view('bookmark_range_api') app.add_url_rule( '/api/bookmarks/<int:starting_id>/<int:ending_id>', view_func=bookmark_range_api_view, methods=['GET', 'PUT', 'DELETE']) bookmark_search_api_view = ApiBookmarkSearchView.as_view('bookmark_search_api') app.add_url_rule('/api/bookmarks/search', view_func=bookmark_search_api_view, methods=['GET', 'DELETE']) bookmarklet_view = BookmarkletView.as_view('bookmarklet') app.add_url_rule('/bookmarklet', view_func=bookmarklet_view, methods=['GET']) # non api admin.add_view(views.BookmarkModelView( bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode)) admin.add_view(views.TagModelView( bukudb, 'Tags', page_size=per_page)) admin.add_view(views.StatisticView( bukudb, 'Statistic', endpoint='statistic')) return app
def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config=True) # overriding Werkzeugs built-in password hashing utilities using Bcrypt. bcrypt = Bcrypt(app) schema = graphene.Schema(query=Query) app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True)) app.config.from_object(app_config[config_name]) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) @app.route('/api/areas/create', methods=['POST']) def create_areas(): # get the access token name = request.data.get('name', '') geodata = request.data.get('geodata', '') center_lat = request.data.get('center_lat') center_lng = request.data.get('center_lng') zoom = request.data.get('zoom') area = Area(name=name, geodata=geodata, center_lat=center_lat, center_lng=center_lng, zoom=zoom) area.save() response = jsonify({ 'id': area.id, 'name': area.name, 'geodata': area.geodata, 'center_lat' : area.center_lat, 'center_lng' : area.center_lng, 'zoom' : area.zoom, 'date_created': area.date_created, 'date_modified': area.date_modified }) return make_response(response), 201 @app.route('/api/areas/delete', methods=['POST']) def delete_areas(): # get the access token id = request.data.get('id', 0) area = Area.query.filter_by(id=id).first() if (area is not None): area.delete() return make_response(jsonify({'id':id})), 200 @app.route('/api/sightingsperhour', methods=['GET']) def get_sightingsperhour(): # get all the areas sightings = SightingsPerHourPerCountry.query.all() results = [] for sighting in sightings: results.append({'country' : sighting.country, 'hour' : sighting.hour, 'count' : sighting.count}) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sightingsnew', methods=['POST']) def sightingsnew(): sightings = db.session.query(SightingsBase.site_id, SightingsBase.country, func.count(SightingsBase.roundedtoday))\ .filter(SightingsBase.site_id.in_(request.data['selectedRow']))\ .filter(SightingsBase.roundedtoday.between(request.data['selectedDates'][0], request.data['selectedDates'][1]))\ .group_by(SightingsBase.site_id, SightingsBase.country)\ .order_by(SightingsBase.site_id, func.count(SightingsBase.roundedtoday).desc())\ results = [] for sighting in sightings.all(): results.append({'country' : sighting.country, 'site_id' : sighting.site_id, 'count' : sighting[2]}) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/widesightingsnew', methods=['POST', 'GET']) def widesightingsnew(): sightings = db.session.query(WideSighting.site_id, WideSighting.gender, func.count(WideSighting.gender))\ .filter(WideSighting.site_id.in_([138, 134]))\ .group_by(WideSighting.site_id, WideSighting.gender) results = [] for sighting in sightings.all(): #gender = sighting.gender if len(sighting.gender) else 'unknown' results.append({'site_id' : sighting.site_id, 'gender' : sighting.gender, 'count' : sighting[2]}) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/widesightings', methods=['GET']) def widesightings(): sightings = WideSighting.get_all() results = [] for sighting in sightings: results.append(sighting.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sites', methods=['GET']) def get_sites(): # get all the areas sites = Site.get_all() results = [] for site in sites: results.append(site.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/dates', methods=['GET']) def get_dates(): # get all the areas dates = Date.get_all() results = [] for date in dates: results.append(date.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/areas', methods=['GET']) def get_areas(): # get all the areas areas = Area.get_all() allSmallCells = SmallCell.get_all() results = [] for area in areas: smallcellInArea = [] for smallcell in allSmallCells: smallcellInArea.append(smallcell.serialise()) obj = { 'id': area.id, 'name': area.name, 'date_created': area.date_created, 'date_modified': area.date_modified, 'center_lat' : area.center_lat, 'center_lng' : area.center_lng, 'zoom' : area.zoom, 'geodata': area.geodata, 'smallcells' : smallcellInArea } results.append(obj) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/smallcells', methods=['GET']) def get_smallcells(): allSmallCells = SmallCell.query.order_by(SmallCell.id).all() results = [] for smallcell in allSmallCells: results.append(smallcell.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/smallcells/update', methods=['POST']) def update_smallcell(): smallcell_id = request.data.get('id', '') site_id = request.data.get('site_id', '') smallcell = SmallCell.query.filter_by(id=smallcell_id).first() smallcell.site_id = site_id smallcell.save() return make_response(jsonify({ 'smallcell_id' : smallcell.id, 'site_id' : smallcell.site_id })), 200 @app.route('/api/sighting/byarea/<areaid>', methods=['GET']) def get_sighting(areaid): import string area = Area.query.filter_by(id=areaid).first() if area is None : return make_response(jsonify({ 'list' : [] })), 200 sites = [] for site in Site.get_all(): if area.contains(site): sites.append(str(site.id)) def generate_random_data(num_rows): import random latitude = 51.51451110408478 longitude = -0.12620388576521444 result = [] for _ in range(num_rows): dec_lat = random.random()/10 dec_lon = random.random()/10 result.append({'lat' : latitude + dec_lat, 'lng' : longitude + dec_lon}) return result results = [] if (len(sites) > 0): for row in db.session.execute('select * from get_gender_crossfilter(ARRAY[' + ','.join(sites) + '])'): results.append(({ 'geos': generate_random_data(5), 'gender' : row['__gender'], 'age_range' : row['__age_range'], 'timestamp' : row['__sighting_date'], 'count' : row['__count'] })) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sighting/getgender/', methods=['POST']) def get_gender(): site_ids = str(request.data.get('site_ids', '')) from_sighting_date = request.data.get('selectedDates')[0] to_sighting_date = request.data.get('selectedDates')[1] import string results = [] for row in db.session.execute("select * from get_gender(ARRAY[" + site_ids + "]," + "'" + from_sighting_date + "'" + "," + "'" + to_sighting_date + "'" + ")"): results.append(({ 'site_id' : row['__site_id'], 'date_month' : row['__date_month'], 'gender' : row['__gender'], 'age_range' : row['__age_range'], 'perc_visits' : row['__perc_visits'], 'scaled_visits' : row['__scaled_visits'] })) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sighting/getgendertotals/', methods=['POST']) def get_gender_age_totals(): site_ids = str(request.data.get('site_ids', '')) from_sighting_date = request.data.get('selectedDates')[0] to_sighting_date = request.data.get('selectedDates')[1] import string results = [] for row in db.session.execute("select * from get_gender_age_totals(ARRAY[" + site_ids + "]," + "'" + from_sighting_date + "'" + "," + "'" + to_sighting_date + "'" + ")"): results.append(({ 'site_id' : row['__site_id'], 'gender' : row['__gender'], 'age_range' : row['__age_range'], '__visits' : row['__visits'] })) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sighting', methods=['GET']) def get_sightings(): results = [] for sighting in LTESighting.get_all(): results.append(sighting.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/sitescomparison', methods=['POST']) def get_sitescomparison(): sightings = LTESighting.query\ .filter(LTESighting.smallcell.has(SmallCell.site_id.in_(request.data['selectedRow'])))\ .filter(LTESighting.timestamp.between(request.data['selectedDates'][0], request.data['selectedDates'][1])) return make_response(jsonify({ 'list' : [sighting.serialise() for sighting in sightings] })), 200 @app.route('/api/sighting/bysite', methods=['GET']) def get_sightings_by_site(): site_ids = (request.args.getlist('site_id')) results = [] #should do this better with joins! for sighting in LTESighting.query: if (str(sighting.smallcell.site_id)) in site_ids : results.append(sighting.serialise()) return make_response(jsonify({ 'list' : results })), 200 @app.route('/api/origindestination/all', methods=['GET']) def get_all(): journeys = Journey.query.all() thing = {} for journey in journeys: if (journey.origin_id not in thing) : thing[journey.origin_id] = {} if (journey.destination_id not in thing[journey.origin_id] and journey.destination_id != journey.origin_id) : thing[journey.origin_id][journey.destination_id] = journey.data['total'] return make_response(jsonify(thing)), 200 @app.route('/api/origindestination/<origin_id>', methods=['GET']) def get_od(origin_id): journeys = Journey.query.all()#.filter_by(origin_id=origin_id).all() _j = [] for journey in journeys: _j.append({'origin_id' : journey.origin_id, 'destination_id' : journey.destination_id, 'total' : journey.data['total']}) #_j.append({'origin_id' : journey.origin_id, 'data' : (journey.data)}) return make_response(jsonify({ 'list' : _j })), 200 @app.route('/api/ng_event/purchase/<home_district_name>/<type_visitor>', methods=['GET']) def purchase(home_district_name, type_visitor): days_sql = db.session.query(PurchDistrict.start_dow, func.count(PurchDistrict.start_dow))\ .group_by(PurchDistrict.start_dow)\ .filter(PurchDistrict.home_district_name.in_([home_district_name]))\ .filter(PurchDistrict.type_visitor.in_([type_visitor]))\ .order_by(func.count(PurchDistrict.start_dow).desc())\ .all() gender_sql = db.session.query(PurchDistrict.gender, func.count(PurchDistrict.gender))\ .group_by(PurchDistrict.gender)\ .filter(PurchDistrict.home_district_name.in_([home_district_name]))\ .filter(PurchDistrict.type_visitor.in_([type_visitor])).all() gender_age_sql = db.session.query(PurchDistrict.gender, PurchDistrict.age, func.count(PurchDistrict.gender))\ .group_by(PurchDistrict.gender, PurchDistrict.age)\ .filter(PurchDistrict.gender.isnot(None))\ .filter(PurchDistrict.age.isnot(None))\ .filter(PurchDistrict.home_district_name.in_([home_district_name]))\ .filter(PurchDistrict.type_visitor.in_([type_visitor])).all() gender_age_rent_sql = db.session.query(PurchDistrict.gender, PurchDistrict.age, PurchDistrict.rent, func.count(PurchDistrict.gender))\ .group_by(PurchDistrict.gender, PurchDistrict.age, PurchDistrict.rent)\ .filter(PurchDistrict.gender.isnot(None))\ .filter(PurchDistrict.age.isnot(None))\ .filter(PurchDistrict.type_visitor.in_([type_visitor])).all() days_total = sum(i[1] for i in days_sql) gender_total = sum(i[1] for i in gender_sql) gender_age_total = sum(i[2] for i in gender_age_sql) days_results = [] for result in days_sql: days_results.append({ 'start_dow' : result.start_dow, 'count' : result[1], 'percent' : float(result[1])/float(days_total), 'total' : days_total}) gender_results = [] for result in gender_sql: gender_results.append({'gender' : result.gender, 'count' : result[1], 'percent' : float(result[1])/float(gender_total)}) gender_age_results = [] for result in gender_age_sql: gender_age_results.append({'gender' : result.gender, 'age' : result.age, 'count' : result[2], 'percent' : float(result[2])/float(gender_age_total)}) return make_response(jsonify({'days' : days_results, 'gender' : gender_results, 'gender_age' : gender_age_results})), 200 @app.route('/api/ng_event/purchase_affluence/<type_visitor>', methods=['GET']) def purchase_rent(type_visitor): gender_sql = db.session.query(PurchDistrict.gender, func.count(PurchDistrict.gender))\ .group_by(PurchDistrict.gender)\ .filter(PurchDistrict.type_visitor.in_([type_visitor])).all() gender_age_rent_sql = db.session.query(PurchDistrict.gender, PurchDistrict.age, PurchDistrict.rent, func.count(PurchDistrict.gender))\ .group_by(PurchDistrict.gender, PurchDistrict.age, PurchDistrict.rent)\ .filter(PurchDistrict.gender.isnot(None))\ .filter(PurchDistrict.age.isnot(None))\ .filter(PurchDistrict.type_visitor.in_([type_visitor])).all() gender_total = sum(i[1] for i in gender_sql) gender_results = [] for result in gender_sql: gender_results.append({'gender' : result.gender, 'count' : result[1], 'percent' : float(result[1])/float(gender_total)}) gender_age_rent_results = [] for result in gender_age_rent_sql: gender_age_rent_results.append({'gender' : result.gender, 'age' : result.age, 'rent' : result.rent, 'count' : result[3]}) return make_response(jsonify({'gender' : gender_results, 'gender_age_rent' : gender_age_rent_results})), 200 @app.route('/api/ng_event/districts', methods=['GET']) def districts(): home_results = [] for result in db.session.query(ZoneDistrict.home_district_code, ZoneDistrict.home_district_name, func.sum(ZoneDistrict.visitors)).group_by(ZoneDistrict.home_district_code, ZoneDistrict.home_district_name).all(): home_results.append({'district_code' : result.home_district_code, 'district_name' : result.home_district_name, 'visitors' : result[2]}) work_results = [] for result in db.session.query(ZoneDistrict.work_district_code, ZoneDistrict.work_district_name, func.sum(ZoneDistrict.visitors)).group_by(ZoneDistrict.work_district_code, ZoneDistrict.work_district_name).all(): work_results.append({'district_code' : result.work_district_code, 'district_name' : result.work_district_name, 'visitors' : result[2]}) return make_response(jsonify({'work' : { 'list' : work_results }, 'home' : { 'list' : home_results }})), 200 @app.route('/api/ng_event/attractiontotals', methods=['GET']) def attractiontotals(): results = [] for result in db.session.query(AttractionTotal.zone_visitors, AttractionTotal.num_visitors).all(): results.append({'zone_visitors' : result.zone_visitors, 'num_visitors' : result.num_visitors}) return make_response(jsonify({'totals' : { 'list' : results }})), 200 @app.route('/api/ng_event/profiles', methods=['GET']) def profiles(): results = [] for result in db.session.query(Profile.country, Profile.nationality, Profile.name_province, Profile.gender, Profile.age, Profile.rent, Profile.type_visitor, Profile.date, Profile.day, Profile.period, Profile.name_tur_zone).limit(10000): district = '' if result.name_tur_zone == 'Zone 1' : district = 'Chamartin' if result.name_tur_zone == 'Zone 2' : district = 'Chamberi' if result.name_tur_zone == 'Zone 3' : district = 'Salamanca' day = '' if result.day == 'Monday' : day = 'Mon' if result.day == 'Tuesday' : day = 'Tue' if result.day == 'Wednesday' : day = 'Wed' if result.day == 'Thursday' : day = 'Thu' if result.day == 'Friday' : day = 'Fri' if result.day == 'Saturday' : day = 'Sat' if result.day == 'Sunday' : day = 'Sun' results.append({'country' : result.country, 'nationality' : result.nationality, 'name_province' : district, 'gender' : result.gender, 'age' : result.age, 'rent' : result.rent, 'type_visitor' : result.type_visitor, 'date' : result.date, 'day' : day, 'period' : result.period, 'zone' : result.name_tur_zone }) return make_response(jsonify(results)), 200 @app.route('/api/ng_event/dowfreq', methods=['GET']) def dowfreq(): results = [] for result in db.session.query(DOWFrequency.type_visitor, DOWFrequency.start_dow, DOWFrequency.start_hour, DOWFrequency.count).all(): results.append({'type_visitor' : result.type_visitor, 'start_dow' : result.start_dow, 'start_hour' : result.start_hour, 'count' : result.count }) return make_response(jsonify(results)), 200 return app
def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config=True) CORS(app) 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.config['SWAGGER'] = { "title": "Yummy Recipes API", "securityDefinitions": { "APIKeyHeader": { "type": "apiKey", "name": "x-access-token", "in": "header" }, }, } Swagger(app) from classes.categories import filtered_category, non_filtered_category from classes.recipes import non_filtered_recipes, filtered_recipes from classes.auth.users import user_creation, reset_password, reset_password_token from classes.auth.login import user_login, user_logout # All the routes are handled here # user endpoints app.add_url_rule('/auth/register', methods=['POST'], view_func=user_creation) app.add_url_rule('/auth/login', methods=['POST'], view_func=user_login) app.add_url_rule('/auth/logout', methods=['POST'], view_func=user_logout) app.add_url_rule('/auth/send_reset_password_token', methods=['POST'], view_func=reset_password_token) app.add_url_rule('/auth/reset_password', methods=['PUT'], view_func=reset_password) # category endpoints app.add_url_rule('/categories/', methods=['GET', 'POST'], view_func=non_filtered_category) app.add_url_rule('/category/<int:category_id>', methods=['GET', 'PUT', 'DELETE'], view_func=filtered_category) # recipes endpoints app.add_url_rule('/category/<int:category_id>/recipes/', methods=['GET', 'POST'], view_func=non_filtered_recipes) app.add_url_rule('/category/<int:category_id>/recipe/<int:recipe_id>', methods=['GET', 'PUT', 'DELETE'], view_func=filtered_recipes) return app
def make_app(config_name): from app.models import Categories from app.classes import categories app = FlaskAPI(__name__, instance_relative_config=True) app.config.from_object(app_config['testing']) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) app.config['SWAGGER'] = { "swagger": "2.0", "title": "Yummy Recipes", "info": { "title": "Yummy Recipes API documentation", "description": "Yummy Recipes provides a way to create recipes and their categories" " and to manipulate them ", "version": "1.0.0", "basepath": '/', "uiversion": 3, }, "securityDefinitions": { "TokenHeader": { "type": "apiKey", "name": "Authorization", "in": "header" }, }, "consumes": [ "application/json", ], "produces": [ "application/json", ], } Swagger(app) from app.classes.categories import category_view_post, category_manipulation, category_view_search app.add_url_rule(base_url + '/categories/', view_func=category_view_post) app.add_url_rule(base_url + '/categories/<int:id>', view_func=category_manipulation) app.add_url_rule(base_url + '/categories/search/', view_func=category_view_search) from app.classes.recipes import recipe_post_get_view, recipe_manipulation_view, recipe_search_view app.add_url_rule(base_url + '/categories/<int:id>/recipes/', view_func=recipe_post_get_view) app.add_url_rule(base_url + '/categories/<int:id>/recipes/<int:recipe_id>', view_func=recipe_manipulation_view) app.add_url_rule(base_url + '/categories/<int:id>/recipes/search/', view_func=recipe_search_view) from app.auth.authentication import user_registration_view, user_login_view, user_password_reset_view, user_logout_view app.add_url_rule(base_url + '/auth/register', view_func=user_registration_view, methods=['POST']) app.add_url_rule(base_url + '/auth/login', view_func=user_login_view, methods=['POST']) app.add_url_rule( base_url + '/auth/password-reset', view_func=user_password_reset_view, ) app.add_url_rule(base_url + '/auth/logout', view_func=user_logout_view) @app.errorhandler(404) def not_found(error): """handles error when users enters inappropriate endpoint """ response = {'message': 'Page not found'} return make_response(jsonify(response)), 404 @app.errorhandler(405) def method_not_allowed(error): """ handles errors if users uses method that is not allowed in an endpoint """ response = {'message': 'Method not allowed'} return make_response(jsonify(response)), 405 return app
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lib.blame import BlameManager from lib.graphql.schema import schema app = FlaskAPI(__name__) # app.config['DEFAULT_RENDERERS'] = [ # 'flask_api.renderers.JSONRenderer', # 'flask_api.renderers.BrowsableAPIRenderer', # ] CORS(app, supports_credentials=True, origins=['http://localhost:8080']) app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=False)) # Optional, for adding batch query support (used in Apollo-Client) # app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view('graphql', schema=schema, batch=True)) # TODO: this should probably be an argument to a track-commit or analysis mutation # excluded_exts = set() # ext_whitelist = ( # ".go", ".proto", ".c", ".h", ".sh", ".md", ".xml", ".wixproj", ".wsx", ".cs" # ) blame_manager = BlameManager() @app.errorhandler(500) def handle_500(error):
from flask_api import FlaskAPI from settings import config from controller import ProcessPayment app = FlaskAPI(__name__) app.config.from_object(config['development']) app.add_url_rule( '/process-payment', view_func=ProcessPayment.as_view('payment_request'), methods=['GET', 'POST'], ) if __name__ == "__main__": app.run()
class Api: """ class for rest interaction """ def __init__(self): cfg = yaml.safe_load(open("config.yaml")) mongourl = cfg['mongourl'] database = cfg['database'] collection = cfg['collection'] collection_new = cfg['collection_new'] self.db = db_helper.Db(mongourl, database, collection) self.db_new = db_helper.Db(mongourl, database, collection_new) self.find = findhelper.Find() self.app = FlaskAPI(__name__) self.app.add_url_rule("/search/", "search", self.search, methods=['POST']) self.app.add_url_rule("/populate/", "populate", self.insert, methods=['POST']) self.app.add_url_rule("/search_trans/", "search_trans", self.search_trans, methods=['POST']) self.app.add_url_rule("/populate_trans/", "populate_trans", self.insert_trans, methods=['POST']) self.app.add_url_rule("/find_image/", "find_image", self.find_image, methods=['POST']) logging.debug('Api has been initialized') def search(self): """ get request, search in db for data """ data = request.get_json() response = self.db.search_records(data) return json_util.dumps(response) def insert(self): """ Get POST json. populate db """ data = request.get_json() res = self.db.write_record(data) return str(res) def search_trans(self): """ get request, search in db for data """ data = request.get_json() response = self.db_new.search_records(data) return json_util.dumps(response) def insert_trans(self): """ Get POST json. populate db """ data = request.get_json() res = self.db_new.write_record(data) return str(res) def find_image(self): """ get json with 'photo' : %photo_name% :return: search results https://pp.userapi.com/c851216/v851216826/efbc4/pnz7eaWD3b8.jpg db_new.search_record({'photos_name':{'$elemMatch':{'$in':['pnz7eaWD3b8.jpg']}}}) """ try: data = request.get_json() logging.debug(data) response = self.find.main(data['photo']) return json_util.dumps(response) except Exception: logging.error(traceback.format_exc())