class SiteSettingsAPI(MethodView): def get(self): user = current_user() if user is None: return redirect(url_for('authorized')) if not user.faculty: return abort(403) return jsonify({c.key: config.to_frontend_value(c) for c in SiteConfiguration.query.all()}) def post(self): if current_user() is None: redirect(url_for('authorized')) user = current_user() if not user.faculty: return abort(403) key = request.form.get('key', None) value = request.form.get('value', None) try: try: config.set(key, config.from_frontend_value(key, json.loads(value))) return jsonify({'status': 'OK'}) except ValueError: return abort(404) except: return abort(400) app.add_url_rule( '/api/v1/site_settings', view_func=SiteSettingsAPI.as_view('site_settings'))
if ('post_id' in request_data) and ('user_id' in request_data): post_like = ForumsPostsLikes.query.filter( and_(ForumsPostsLikes.post_id == request_data['post_id'], ForumsPostsLikes.user_id == request_data['user_id'])).first() db.session.delete(post_like) db.session.commit() return jsonify(**{'success': True}) return jsonify(**{'success': False}), 401 # Routing information threads_view = ThreadsAPI.as_view('threads_api') app.add_url_rule('/api/forums/threads/', view_func=threads_view, methods=['POST', 'GET']) posts_view = PostsAPI.as_view('posts_api') app.add_url_rule('/api/forums/posts/', view_func=posts_view, methods=['POST', 'GET', 'DELETE']) postsimage_view = PostsImagesAPI.as_view('postsimages_api') app.add_url_rule('/api/forums/postsimages/', view_func=postsimage_view, methods=['POST', 'GET']) postslikes_view = PostsLikesAPI.as_view('postslike_api') app.add_url_rule('/api/forums/likes/', view_func=postslikes_view,
from google.appengine.ext import ndb from flask import json, Response, request, abort from flask.views import MethodView from backend import app from backend.models import Tag class TagREST(MethodView): def get(self, id=None): if id is None: tags = Tag.query().fetch() res = [{ 'id': t.key.id(), 'name': t.name } for t in tags] else: res = {} return Response(json.dumps(res), mimetype='application/json') tag_view = TagREST.as_view('tag_rest') app.add_url_rule('/tags/', view_func=tag_view, methods=['GET',]) app.add_url_rule('/tags/', view_func=tag_view, methods=['POST',]) app.add_url_rule('/tags/<id>', view_func=tag_view, methods=['GET', 'PUT', 'DELETE'])
temp_data['web_online'] = new_data.web_online temp_data['game_online'] = new_data.game_online # This deletes a user from presence list if he has gone offline for it_data in presence_list: if not any(init_data.user.username == it_data['username'] for init_data in user_presences): presence_list.remove(it_data) # return jsonify(data = presence_list) return "data: %s\n\n" % json.dumps(presence_list) @app.route('/stream') def stream(): return Response(event_stream(), mimetype="text/event-stream") ## Used to get all users which are present class PresenceOnlineApi(MethodView): def get(self): presence_list = [] user_presences = Presence.query.join(Presence.user).filter(or_(Presence.game_online == True, Presence.web_online == True)).all() if user_presences is None: return jsonify(**{'success': False}), 401 for data in user_presences: json = {'username': data.user.username,'first_name': data.user.first_name, 'last_name': data.user.last_name, 'web_online': data.web_online, 'game_online': data.game_online} presence_list.append(json) return jsonify(results = presence_list) presence_online_view = PresenceOnlineApi.as_view('presence_online_api') app.add_url_rule('/api/presence/online/', view_func=presence_online_view, methods=['GET'])
from flask.views import MethodView from sqlalchemy import and_ from flask.ext.login import current_user from backend.api.sessionauth import current_user_props from backend import db, app from backend.database.models import User, UserStatistics ## reformats the passed in user stats to an JSON-like object def user_statistics_props(user_stat): return { 'id': user_stat.id, 'games_played': user_stat.games_played, 'wins': user_stat.wins, 'win_loss_ratio': user_stat.win_loss_ratio } ## Used to retrieve the stats of all users class UserStatisticsAPI(MethodView): def get(self): user_stat = UserStatistics.query.filter(UserStatistics.user_id == current_user.id).first() if user_stat is None: return jsonify(**{'success': False}) return jsonify(**{'success': True, 'user_statistics': user_statistics_props(user_stat)}) # Routing and View bindings user_statistics_view = UserStatisticsAPI.as_view('user_statistics_api') app.add_url_rule('/api/user_statistics/', view_func=user_statistics_view, methods=['GET'])
'success': False, 'user': request_data['user'], 'key': request_data['tok'] }), 401 user.new_user = 0 db.session.add(user) db.session.commit() return jsonify(**{'success': True}) return jsonify(**{'success': False}), 401 ## Routing and View bindings settings_view = SettingsAPI.as_view('settings') app.add_url_rule('/api/users/settings/', view_func=settings_view, methods=['POST']) change_details_view = ChangeDetailsAPI.as_view('change_details') app.add_url_rule('/api/users/change_details/', view_func=change_details_view, methods=['POST']) register_view = RegisterAPI.as_view('register_api') app.add_url_rule('/api/users/register/', view_func=register_view, methods=['POST']) password_change_view = PasswordChangeApi.as_view('password_change_api') app.add_url_rule('/api/users/changepass/', view_func=password_change_view,
return jsonify(**{'success': 'none'}), 401 if 'id' in request_data: userprivileges = UserPrivileges.query.filter( UserPrivileges.id == request_data['id']).first() userprivileges.admin_access = False db.session.add(userprivileges) db.session.commit() return jsonify(**{'success': True}) return jsonify(**{'success': False}), 401 # Routing information and view bindings globalannouncements_view = GlobalAnnouncementsAPI.as_view( 'globalannouncements_api') app.add_url_rule('/api/admin/announcements/', view_func=globalannouncements_view, methods=['POST', 'GET']) globalannouncementsposts_view = GlobalAnnouncementsPostsAPI.as_view( 'globalannouncementsposts_api') app.add_url_rule('/api/admin/announcementposts/', view_func=globalannouncementsposts_view, methods=['POST', 'GET']) todo_view = ToDoAPI.as_view('todo_api') app.add_url_rule('/api/admin/todo/', view_func=todo_view, methods=['POST', 'GET']) globalannouncementsget_view = GlobalAnnouncementsGETAPI.as_view( 'globalannouncementsget_api')
@session_auth_required def post(self): file = request.files['file'] ext = (file.filename.rsplit('.', 1)[1]) if ('.' in file.filename) else None if ext not in ['jpg', 'jpeg', 'png', 'gif']: return jsonify(**{'success': False}), 422 # PIL Image Compression image = Image.open(file) # Calculate the height using the same aspect ratio widthPercent = (640 / float(image.size[0])) height = int((float(image.size[1]) * float(widthPercent))) image = image.resize((640, height), Image.ANTIALIAS) # In case for whatever reason a username is made of Unix relative directory markers filename = file.filename + secure_filename(current_user.username) + '.' + ext print os.path.join(app.config['AVATAR_UPLOADS'], filename) image.save(os.path.join(app.config['AVATAR_UPLOADS'], filename), optimize=True, quality=65) current_user.set_avatar_local_path(filename) db.session.add(current_user) db.session.commit() return jsonify(**{'success': True, 'user': current_user_props()}) avatar_view = AvatarAPI.as_view('avatar_api') app.add_url_rule('/api/avatar/', view_func=avatar_view, methods=['POST'])
"MWI": "Malawi", "MUS": "Mauritius", "MOZ": "Mozambique", "NAM": "Namibia", "SYC": "Seychelles", "ZAF": "South Africa", "SWZ": "Swaziland", "TZA": "Tanzania", "ZMB": "Zambia", "ZWE": "Zimbabwe", } # handling static files (only relevant during development) app.static_folder = 'static' app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=app.send_static_file, subdomain='api-med-db') def send_api_response(data_json): response = flask.make_response(data_json) response.headers['Access-Control-Allow-Origin'] = "*" response.headers['Content-Type'] = "application/json" return response def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None or not g.user.is_active():
if to_user is None or from_user is None: return jsonify(**{'success': False}), 401 jsonData = { 'to_username': to_user.username, 'to_firstname': to_user.first_name, 'to_lastname': to_user.last_name, 'to_avatar_path': to_user.avatar_path, 'from_username': from_user.username, 'from_firstname': from_user.first_name, 'from_lastname': from_user.last_name, 'from_avatar_path': from_user.avatar_path } userList.append(jsonData) return json.dumps(userList) return jsonify(**{'success': False}), 401 chat_user_view = ChatUserApi.as_view('chat_user_api') app.add_url_rule('/api/messages/users/', view_func=chat_user_view, methods=['GET']) chat_message_view = ChatMessageApi.as_view('chat_message_api') app.add_url_rule('/api/messages/chat/', view_func=chat_message_view, methods=['POST', 'GET', 'PUT']) chat_userRetrieve_view = ChatUserRetrieveApi.as_view('chat_userretrieve_api') app.add_url_rule('/api/messages/retrieveUsers/', view_func=chat_userRetrieve_view, methods=['GET', 'POST'])
if tagids: tagkeys = [ndb.Key("Tag", int(id)) for id in tagids] events = Event.query(ndb.AND(Event.intervals.start_date == dt, Event.tags.IN(tagkeys))).fetch() else: events = Event.query(Event.intervals.start_date == dt).fetch(count + 1, offset=offset) r = [to_dict(e, dt) for e in events] more = len(r) > count # Flag shows there are more results to display res = {"more": more, "events": r[:-1] if more else r} else: res = to_dict(Event.get_by_id(int(id))) return Response(json.dumps(res), mimetype="application/json") event_view = EventREST.as_view("event_rest") app.add_url_rule("/events/", view_func=event_view, methods=["GET"]) app.add_url_rule("/events/", view_func=event_view, methods=["POST"]) app.add_url_rule("/events/<id>", view_func=event_view, methods=["GET", "PUT", "DELETE"]) def to_dict(o, dt=None): return { "item_id": o.key.id(), "watchword": o.watchword, "description": o.description, "intervals": [ { "start_date": i.start_date.strftime(DF), "start_time": i.start_time.strftime(TF) if i.start_time is not None else None, "end_date": i.start_date.strftime(DF) if i.end_date is not None else None, "end_time": i.end_time.strftime(TF) if i.end_time is not None else None,
if presence is None: return jsonify(**{'success': False}), 401 presence.web_online = True db.session.add(presence) db.session.commit() # Leave property authenticated to be calculated by current_user.is_authenticated() return jsonify(**{'success': True, 'authenticated': current_user.is_authenticated(), 'user': current_user_props()}) else: errors = 'Invalid username or password' return jsonify(**{'success': False, 'authenticated': current_user.is_authenticated(), 'errors': errors}), 401 ## returns whether a user is authenticated @session_auth_required def get(self): return jsonify(**{'authenticated': True, 'user': current_user_props()}) ## Deletes session, and makes db updates as necessary def delete(self): presence = Presence.query.filter(Presence.user_id==current_user.id).first() if presence is None: return jsonify(**{'success': False}), 401 presence.web_online = False presence.web_last_seen = datetime.datetime.now() db.session.add(presence) db.session.commit() logout_user() return jsonify(**{'success': True, 'authenticated': current_user.is_authenticated()}) session_auth_view = SessionAuthAPI.as_view('session_auth_api') app.add_url_rule('/api/session_auth/', view_func=session_auth_view, methods=['GET', 'POST', 'DELETE'])
'game_id': row.game.id, 'user_id': row.user_id, 'numCannons': row.numCannons, 'numFires': row.numFires, 'numWalls': row.numWalls, 'num_players': row.game.num_players, 'time_played': row.game.time_played.strftime("%Y-%m-%d %H:%M:%S"), 'winner_id': row.game.winner_id } ## Interface for retrieving game information from the database class GameInfoAPI(MethodView): ## Returns all games corresponding to a specific user_id def get(self): game_info_array = [] user_id = request.args.get('id') if user_id is "" or user_id is None: return jsonify(**{'success': 'none'}), 401 game_info = GameInfo.query.join(Game.game_info).filter(GameInfo.user_id==user_id).all() if game_info is not None: for row in game_info: game_info_array.append(buildGameInfoJSON(row)) return json.dumps(game_info_array) return jsonify(**{'success': False}), 401 # Routing and view binding game_info_view = GameInfoAPI.as_view('game_info_api') app.add_url_rule('/api/game_info/', view_func=game_info_view, methods=['GET'])
for i in queryObject: emailArray.append(i.email) if len(emailArray) > 0: msg = Message('Fort Nitta New Message!', sender='*****@*****.**', recipients=emailArray) msg.body = ("Hey Fort Nitta user,\n\n" + " You have new unread messages waiting!\n " + " Visit Fort Nitta now to check!\n " + "\n\nAll the best,\n" + "Fort Nitta Team,\n" + url) mail.send(msg) threading.Timer( intervalInSecs, lambda: sendEmail(maxPK, intervalID, intervalInSecs)).start() # kick of email scheduling startEmailing(running) # Routing and view binding password_rec_view = PasswordRecApi.as_view('password_rec_api') app.add_url_rule('/api/recpassmail/', view_func=password_rec_view, methods=['POST']) verify_email_view = VerifyEmailApi.as_view('verify_email_api') app.add_url_rule('/api/veremailacc/', view_func=verify_email_view, methods=['POST'])