def login(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) data = request.json if not all([data.get('Username'), data.get('Password')]): error = jsonify({'Error': 'username/password missing'}) return json_response(error, 400) user_in_db = users_col.find({'Username': data.get('Username')}) for user in user_in_db: # iterate over the pymongo cursor user_id = user['_id'] hashed_password = user['Password'] Full_name = user['First name'] + ' ' + user['Last name'] if user_in_db.count() != 0 and bcrypt.check_password_hash( hashed_password, data.get('Password')): # Store the user information into the session session.clear() session['user_id'] = str(user_id) session['Username'] = data.get('Username') session['Full name'] = Full_name return json_response(data=jsonify( {'Response': 'You are connected as ' + session['Username']}), status=200) else: error = jsonify({'Error': 'bad username/password'}) return json_response(error, 400)
def register(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) data = request.json if not all([ data.get('First Name'), data.get('Last Name'), data.get('Username'), data.get('Password') ]): error = jsonify({'Error': 'field(s) missing'}) return json_response(error, 400) hashed_password = bcrypt.generate_password_hash( data.get('Password')).decode('utf-8') data['Password'] = hashed_password try: users_col.insert(data) except DuplicateKeyError: error = jsonify({'Error': 'Username already exists'}) return json_response(error, 400) return json_response(data=jsonify({'Success': 'User added'}), status=200)
def signup(request): username = request.POST.get("username") password = request.POST.get("password") if config.InviteOnlySignUp: invitecode = request.POST.get("invitecode") username, msg = util.check_string(username, 2, 20, config.UsernameChars) if not username: result = {"status": "error", "error": "username " + msg} return util.json_response(result) password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = {"status": "error", "error": "password " + msg} return util.json_response(result) r = g.redis if config.InviteOnlySignUp: # race condition here. if not r.sismember("invite.code", invitecode): result = {"status": "error", "error": "invalid invitation code"} return util.json_response(result) # mark as used r.smove("invite.code", "invite.code.used", invitecode) # XXX proxied requests have the same REMOTE_ADDR auth, msg = create_user(username, password, request.environ["REMOTE_ADDR"]) if not auth: result = {"status": "error", "error": msg} else: result = {"status": "ok", "auth": auth} return util.json_response(result)
def delete_news(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.' } return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret' } return util.json_response(result) news_id = util.force_int(request.POST.get('news_id')) if not news_id: result = {'status': 'error', 'error': 'bad news_id' } return util.json_response(result) if del_news(news_id, g.user['id']): result = {'status': 'ok', 'news_id': -1 } return util.json_response(result) result = {'status': 'err', 'error': 'News too old or wrong ID/owner.' } return util.json_response(result)
def vote_news(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.' } return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret' } return util.json_response(result) news_id = util.force_int(request.POST.get('news_id')) vote_type = request.POST.get('vote_type') if not news_id or (vote_type != 'up' and vote_type != 'down'): result = {'status': 'error', 'error': 'Missing news ID or invalid vote type.' } return util.json_response(result) # Vote the news karma, error = do_vote_news(news_id, vote_type) if karma: return util.json_response({"status": "ok" }) else: return util.json_response({"status": "error" })
def login(request): username = request.GET.get('username') password = request.GET.get('password') username, msg = util.check_string(username, 2, 20) if not username: result = {'status': 'error', 'error': 'username ' + msg} return util.json_response(result) password, msg = util.check_string(password) if not password: result = {'status': 'error', 'error': 'password ' + msg} return util.json_response(result) auth, apisecret = check_user_credentials(username, password) if auth: result = {'status': 'ok', 'auth': auth, 'apisecret': apisecret} else: result = { 'status': 'error', 'error': 'bad username/password', } return util.json_response(result)
def vote_news(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.'} return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret'} return util.json_response(result) news_id = util.force_int(request.POST.get('news_id')) vote_type = request.POST.get('vote_type') if not news_id or (vote_type != 'up' and vote_type != 'down'): result = { 'status': 'error', 'error': 'Missing news ID or invalid vote type.' } return util.json_response(result) # Vote the news karma, error = do_vote_news(news_id, vote_type) if karma: return util.json_response({"status": "ok"}) else: return util.json_response({"status": "error"})
def delete_re_property(): if is_logged_in(): properties_col.delete_one({'Landlord': session['Full name']}) return json_response(data=jsonify({'success': 'property deleted'}), status=200) else: return json_response(data=jsonify({'error': 'Please log in first!'}), status=400)
def logout(): # remove the username from the session if it's there if is_logged_in(): session.pop('Username', None) session.pop('Full name', None) return json_response(jsonify({'Success': 'Logged out'}), 400) else: error = jsonify({'Error': 'you are not logged in'}) return json_response(error, 400)
def user_new(): # Check if account already exists exists = mongo.db.users.find_one({'email': request.json['email']}) if exists: return json_response({'message': 'email already exists'}, status_code=409) new_user_data = request.json oid = mongo.db.users.insert(new_user_data) user = mongo.db.users.find_one({'_id': ObjectId(oid)}) return json_response(user)
def user_update(user_id): # Authorization user = mongo.db.users.find_one({'_id': user_id}) if not user['email'] == session['email']: return json_response({'message': 'unauthorized'}, status_code=401) # PUT oid = mongo.db.users.save(json_oid(request.json)) user = mongo.db.users.find_one({'_id': ObjectId(oid)}) return json_response(user)
def logout(request): auth_user(request.cookies.get("auth")) if g.user: apisecret = request.POST.get("apisecret") if apisecret == g.user["apisecret"]: update_auth_token(g.user) return util.json_response({"status": "ok"}) result = {"status": "error", "error": "Wrong auth credentials or API secret."} return util.json_response(result)
def logout(request): auth_user(request.cookies.get('auth')) if g.user: apisecret = request.POST.get('apisecret') if apisecret == g.user["apisecret"]: update_auth_token(g.user) return util.json_response({'status': 'ok'}) result = {'status': 'error', 'error': 'Wrong auth credentials or API secret.' } return util.json_response(result)
def logout(request): auth_user(request.cookies.get('auth')) if g.user: apisecret = request.POST.get('apisecret') if apisecret == g.user["apisecret"]: update_auth_token(g.user) return util.json_response({'status': 'ok'}) result = { 'status': 'error', 'error': 'Wrong auth credentials or API secret.' } return util.json_response(result)
def signup(request): username = request.POST.get('username') password = request.POST.get('password') if config.InviteOnlySignUp: invitecode = request.POST.get('invitecode') username, msg = util.check_string(username, 2, 20, config.UsernameChars) if not username: result = { 'status': 'error', 'error': 'username ' + msg } return util.json_response(result) password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = { 'status': 'error', 'error': 'password ' + msg } return util.json_response(result) r = g.redis if config.InviteOnlySignUp: #race condition here. if not r.sismember('invite.code', invitecode): result = { 'status': 'error', 'error': 'invalid invitation code', } return util.json_response(result) #mark as used r.smove('invite.code', 'invite.code.used', invitecode) #XXX proxied requests have the same REMOTE_ADDR auth, msg = create_user(username, password, request.environ['REMOTE_ADDR']) if not auth: result = { 'status': 'error', 'error': msg, } else: result = { 'status': 'ok', 'auth': auth, } return util.json_response(result)
def re_properties_by_city(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) data = request.json if data.get('city') is None: error = jsonify({'Error': 'city missing'}) return json_response(error, 400) else: property_req = properties_col.find({'City': data.get('city')}) if property_req.count() == 0: error = jsonify({'Error': 'No property found'}) return json_response(error, 400) return json_response(dumps(property_req), status=200)
def error(e): r = { "err": "error happened", "err_type": type(e).__name__, "err_msg": e.args[0] } return json_response(500, r)
def login(request: _Parsed): json = request.json get = json.get user = get("user", "").strip().lower() password = get("password", "") invalids = [] if not user: invalids.append("username") if not password: invalids.append("password") if invalids: raise AppException(f"Invalid {' and '.join(invalids)}", code=401) user_data = get_user_by_id(user) password_hash = user_data.password_hash if not check_password_hash(password_hash, password): raise AppException("Incorrect Password", code=401) username = user_data.user access_token = create_token(issue_access_token(username)) refresh_token = create_token(issue_refresh_token(username, password_hash)) return json_response( {"data": { "success": True, "user_data": user_data.as_json }}, headers={ "x-access-token": access_token, "x-refresh-token": refresh_token }, )
def home_view(request): result = {} for district in alldistricts: result[district.name] = district.getPerformanceMetric() return json_response(result)
def create_re_property(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) if is_logged_in(): data = request.json if not all([data.get('Name'), data.get('Landlord')]): error = jsonify({'Error': 'Name/landlord missing'}) return json_response(error, 400) properties_col.insert(data) return json_response(data='property added', status=200) else: return json_response(data=jsonify({'error': 'Please log in first!'}), status=400)
def re_properties_list(): all_properties_req = properties_col.find() if all_properties_req is None: error = jsonify({'Error': 'No properties'}) return json_response(error, 400) return dumps( all_properties_req) # use of dumps to convert a pymongo cursor to json
def bins(): fileList = [] for f in listdir(config.binaries_path): # Create link html link = url_for('static', filename=f) fileList.append(link) return json_response(200, 'ok', fileList)
def edit_re_property(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) if is_logged_in(): print(session['Full name']) data = dict(request.json) new_values = {'$set': data} properties_col.update_one({'Landlord': session['Full name']}, new_values) return json_response(data=jsonify({'success': 'property updated'}), status=200) else: return json_response(data=jsonify({'error': 'Please log in first!'}), status=400)
def batch_calculate_view(request): data = json.loads(request.read()) response = {} for name, x in data.iteritems(): response[name] = model.calculate(float(x) * x_value_factor) return json_response(response)
def query_process(): ''' /process?script=xxx ''' print('query_process') script_name = request.args.get("script") or "" CMD = ["pgrep", "-f", script_name + '.py'] print(CMD) child = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=False) pid = child.communicate()[0].decode('utf-8') if pid: msg = '脚本%s正在运行, pid %s' % (script_name, pid) r = {'msg': msg} return json_response(200, r, True) else: msg = '脚本%s未运行!' % script_name r = {'msg': msg} return json_response(200, r, True)
def signup(request): username = request.POST.get('username') password = request.POST.get('password') if config.InviteOnlySignUp: invitecode = request.POST.get('invitecode') username, msg = util.check_string(username, 2, 20, config.UsernameChars) if not username: result = {'status': 'error', 'error': 'username ' + msg} return util.json_response(result) password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = {'status': 'error', 'error': 'password ' + msg} return util.json_response(result) r = g.redis if config.InviteOnlySignUp: #race condition here. if not r.sismember('invite.code', invitecode): result = { 'status': 'error', 'error': 'invalid invitation code', } return util.json_response(result) #mark as used r.smove('invite.code', 'invite.code.used', invitecode) #XXX proxied requests have the same REMOTE_ADDR auth, msg = create_user(username, password, request.environ['REMOTE_ADDR']) if not auth: result = { 'status': 'error', 'error': msg, } else: result = { 'status': 'ok', 'auth': auth, } return util.json_response(result)
def execute(): if request.method == 'POST': version_type = request.form.get('type') checkout_target = request.form.get('value') if version_type == 'tag': checkout_target = 'tags/' + checkout_target exe = Executor(config.log_path, config.scripts_path, checkout_target, config.lock) return Response(exe.run(), mimetype='text/html') else: return json_response(409, 'another process running') if Executor.is_locked(config.lock) else json_response(200, 'idle')
def query_stop(): ''' /stop?script=xxx ''' print('query_stop') script_name = request.args.get("script") or "" child = subprocess.Popen(["pgrep", "-f", script_name + '.py'], stdout=subprocess.PIPE, shell=False) pid = child.communicate()[0].decode('utf-8') if pid: CMD = 'kill -9 ' + pid sub_child = run(CMD) r = {'msg': pformat(sub_child)} return json_response(200, r, True) else: msg = '脚本%s未运行!' % script_name r = {'msg': msg} return json_response(200, r, True)
def edit_user(): if request.content_type != JSON_MIME_TYPE: error = jsonify({'Error': 'Invalid Content-Type'}) return json_response(error, 400) data = dict(request.json) if is_logged_in(): # the user can only change his data and needs to be logged in if 'Password' in data: # hash the new password data['Password'] = bcrypt.generate_password_hash( data['Password']).decode('utf-8') new_values = {'$set': data} users_col.update_one({'_id': ObjectId(session['user_id'])}, new_values) return json_response(data=jsonify({'Success': 'User edited'}), status=200) else: return json_response(data=jsonify({'Error': 'you are not logged in'}), status=400)
def gconnect(): if request.args.get('state') != login_session['state']: return json_response('Invalid state parameter', 400) authorization_code = request.data try: credentials = upgrade_to_credentials(authorization_code) except FlowExchangeError: return json_response('Failed to upgrade the authorization code.', 401) access_token_info = token_info(credentials.access_token) if access_token_info.get('error') is not None: error = access_token_info.get('error') return json_response(error, 500) gplus_id = credentials.id_token['sub'] if access_token_info['user_id'] != gplus_id: return json_response("Token's user ID doesn't match given user ID.", 401) if access_token_info['issued_to'] != CLIENT_ID: return json_response("Token's client ID does not match this app.", 401) if is_already_logged_in(login_session): return json_response("Current user is already connected.", 401) user_info = get_user_info(credentials.access_token) update_login_session(login_session, credentials, gplus_id, user_info) db_update_user(session, login_session) flash("You are now logged in as %s" % login_session['username']) return '<html></html>'
def delete_news(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.'} return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret'} return util.json_response(result) news_id = util.force_int(request.POST.get('news_id')) if not news_id: result = {'status': 'error', 'error': 'bad news_id'} return util.json_response(result) if del_news(news_id, g.user['id']): result = {'status': 'ok', 'news_id': -1} return util.json_response(result) result = {'status': 'err', 'error': 'News too old or wrong ID/owner.'} return util.json_response(result)
def query_start(): ''' /start?script=xxx&log=output ''' print('query_start') script_name = request.args.get("script") or "" LOGPATH = request.args.get("log") or "output" LOGPATH += '.txt' child = subprocess.Popen(["pgrep", "-f", script_name + '.py'], stdout=subprocess.PIPE, shell=False) pid = child.communicate()[0].decode('utf-8') if pid: msg = '脚本%s已运行!' % script_name r = {'msg': msg} return json_response(200, r, True) else: # LOGPATH = 'output.txt' CMD = 'nohup python -u ' + script_name + '.py > ' + LOGPATH + ' 2>&1 &' sub_child = run(CMD) r = {'msg': pformat(sub_child)} return json_response(200, r, True)
def vote_news(request): auth_user(request.cookies.get("auth")) if not g.user: result = {"status": "error", "error": "Not authenticated."} return util.json_response(result) if request.POST.get("apisecret") != g.user["apisecret"]: result = {"status": "error", "error": "Wrong form secret"} return util.json_response(result) news_id = util.force_int(request.POST.get("news_id")) vote_type = request.POST.get("vote_type") if not news_id or (vote_type != "up" and vote_type != "down"): result = {"status": "error", "error": "Missing news ID or invalid vote type."} return util.json_response(result) # Vote the news karma, error = do_vote_news(news_id, vote_type) if karma: return util.json_response({"status": "ok"}) else: return util.json_response({"status": "error"})
def delete_news(request): auth_user(request.cookies.get("auth")) if not g.user: result = {"status": "error", "error": "Not authenticated."} return util.json_response(result) if request.POST.get("apisecret") != g.user["apisecret"]: result = {"status": "error", "error": "Wrong form secret"} return util.json_response(result) news_id = util.force_int(request.POST.get("news_id")) if not news_id: result = {"status": "error", "error": "bad news_id"} return util.json_response(result) if del_news(news_id, g.user["id"]): result = {"status": "ok", "news_id": -1} return util.json_response(result) result = {"status": "err", "error": "News too old or wrong ID/owner."} return util.json_response(result)
def as_response(self): ''' return a bundle as a response ''' bundle_dict = self._make_bundle() if self.data_format == 'json': response = json_response() response.data = json.dumps(bundle_dict) else: response = xml_bundle_response() response.data = render_template('bundle.xml', **bundle_dict) return response
def as_response(self): ''' return a bundle as a response ''' bundle_dict = self._make_bundle() if self.data_format == 'json': response = json_response() response.data = json.dumps(bundle_dict, indent=4, sort_keys=True) else: response = xml_bundle_response() response.data = render_template('bundle.xml', **bundle_dict) return response
def login(request): username = request.GET.get("username") password = request.GET.get("password") username, msg = util.check_string(username, 2, 20) if not username: result = {"status": "error", "error": "username " + msg} return util.json_response(result) password, msg = util.check_string(password) if not password: result = {"status": "error", "error": "password " + msg} return util.json_response(result) auth, apisecret = check_user_credentials(username, password) if auth: result = {"status": "ok", "auth": auth, "apisecret": apisecret} else: result = {"status": "error", "error": "bad username/password"} return util.json_response(result)
def login(request): username = request.GET.get('username') password = request.GET.get('password') username, msg = util.check_string(username, 2, 20) if not username: result = { 'status': 'error', 'error': 'username ' + msg } return util.json_response(result) password, msg = util.check_string(password) if not password: result = { 'status': 'error', 'error': 'password ' + msg } return util.json_response(result) auth, apisecret = check_user_credentials(username, password) if auth: result = { 'status': 'ok', 'auth': auth, 'apisecret': apisecret } else: result = { 'status': 'error', 'error': 'bad username/password', } return util.json_response(result)
def new_channel(globs, request): client_id = request.headers.get('X-KeyExchange-Id') #if not _valid_client_id(client_id): # # The X-KeyExchange-Id is valid # try: # log = 'Invalid X-KeyExchange-Id' # log_cef(log, 5, request.environ, config, # msg=_cid2str(client_id)) # finally: # raise HTTPBadRequest() cid = _get_new_cid(client_id) headers = [('X-KeyExchange-Channel', cid), ('Content-Type', 'application/json')] return json_response(cid, headerlist=headers)
def update_profile(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.' } return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret' } return util.json_response(result) password = request.POST.get('password') #optinal email = request.POST.get('email') about = request.POST.get('about') email, msg = util.check_string(email, maxlen=128) if email is None: result = { 'status': 'error', 'error': 'email ' + msg } return util.json_response(result) about, msg = util.check_string(about, maxlen=256) if about is None: result = { 'status': 'error', 'error': 'about ' + msg } return util.json_response(result) r = g.redis if password: password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = { 'status': 'error', 'error': 'password ' + msg } return util.json_response(result) r.hset("user:"******"password", util.hash_password(password, g.user['salt'])) r.hmset("user:"******"about": about.rstrip(), "email": email }) return util.json_response({'status': "ok"})
def new_error(status_code): ''' Create a new OperationOutcome resource from HTTP status_code ''' msg, severity = CODES[status_code] outcome_content = { 'resourceType': 'OperationOutcome', 'issue': { 'severity': severity, 'details': msg } } is_xml = (request.args.get('_format', 'xml') == 'xml') response= (json_response(json.dumps(outcome_content)) if not is_xml else xml_response(json_to_xml(outcome_content))) response.status = status_code return response
def as_response(self, request, created=False): ''' return the resource as a HTTP response ''' status = '201' if created else '200' if request.format == 'json': response = json_response(status=status) response.data = self.data else: response = xml_response(status=status) response.data = json_to_xml(json.loads(self.data)) loc_header = 'Location' if created else 'Content-Location' response.headers[loc_header] = urljoin(request.api_base, '%s/%s/_history/%s' % ( self.resource_type, self.resource_id, self.version)) return response
def re_authenticate(req: _Parsed): headers = flask_request.headers access_token = get_bearer_token(headers) decoded_access = decode_token(access_token) if decoded_access is None: refresh_token = headers.get("x-refresh-token") decoded_refresh = decode_token(refresh_token) access, refresh = regenerate_access_token(decoded_refresh) if access is None: raise AppException("re-auth", code=401) return json_response( {}, headers={ "x-access-token": create_token(access), "x-refresh-token": create_token(refresh), }, )
def as_response(self, request, created=False): ''' return the resource as a HTTP response ''' status = '201' if created else '200' if request.format == 'json': response = json_response(status=status) response.data = self.data else: response = xml_response(status=status) response.data = json_to_xml(json.loads(self.data)) loc_header = 'Location' if created else 'Content-Location' response.headers[loc_header] = urljoin( request.api_base, '%s/%s/_history/%s' % (self.resource_type, self.resource_id, self.version)) return response
def update_profile(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.'} return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret'} return util.json_response(result) password = request.POST.get('password') #optinal email = request.POST.get('email') about = request.POST.get('about') email, msg = util.check_string(email, maxlen=128) if email is None: result = {'status': 'error', 'error': 'email ' + msg} return util.json_response(result) about, msg = util.check_string(about, maxlen=256) if about is None: result = {'status': 'error', 'error': 'about ' + msg} return util.json_response(result) r = g.redis if password: password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = {'status': 'error', 'error': 'password ' + msg} return util.json_response(result) salt = g.user.get('salt', util.get_rand()) r.hmset("user:"******"password": util.hash_password(password, salt), "salt": salt }) r.hmset("user:"******"about": about.rstrip(), "email": email}) return util.json_response({'status': "ok"})
def update_profile(request): auth_user(request.cookies.get("auth")) if not g.user: result = {"status": "error", "error": "Not authenticated."} return util.json_response(result) if request.POST.get("apisecret") != g.user["apisecret"]: result = {"status": "error", "error": "Wrong form secret"} return util.json_response(result) password = request.POST.get("password") # optinal email = request.POST.get("email") about = request.POST.get("about") email, msg = util.check_string(email, maxlen=128) if email is None: result = {"status": "error", "error": "email " + msg} return util.json_response(result) about, msg = util.check_string(about, maxlen=256) if about is None: result = {"status": "error", "error": "about " + msg} return util.json_response(result) r = g.redis if password: password, msg = util.check_string(password, config.PasswordMinLength) if not password: result = {"status": "error", "error": "password " + msg} return util.json_response(result) salt = g.user.get("salt", util.get_rand()) r.hmset("user:"******"id"], {"password": util.hash_password(password, salt), "salt": salt}) r.hmset("user:"******"id"], {"about": about.rstrip(), "email": email}) return util.json_response({"status": "ok"})
def getGmailMessages(email): #~~~PUT MESSAGE ID BELOW~~~ messages = ListMessagesMatchingQuery(build_service(get_credentials()), "me", query='from:'+email) convos = [] i = 0 while (i<len(messages)): msg_id = messages[i]["threadId"] msg_info = GetMimeMessage(build_service(get_credentials()), "me", msg_id) #print msg_info #TODO: Find a better way to get the message string, ex: by newlines index1 = str(msg_info).index("Content-Type: text/plain; charset=UTF-8") index1 += len("Content-Type: text/plain; charset=UTF-8") index2 = str(msg_info).index("Content-Type: text/html; charset=UTF-8") index2 -= len("--001a113d38862b78c0052be7b244") msg_content = str(msg_info)[index1:index2] convos.append(msg_content) i+=1 #print convos tone_analyzer = ToneAnalyzer(username='******', password='******', version='2016-02-11') analyzed_text = [] for c in convos: analyzed_text.append(json.dumps(tone_analyzer.tone(text=c), indent=2)) tones = {} tones["emotion"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][0]["tones"] tones["language"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][1]["tones"] tones["social"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][2]["tones"] values = [] scores = [] for el in tones["emotion"]: values.append(el["tone_name"]) for el in tones["language"]: values.append(el["tone_name"]) for el in tones["social"]: values.append(el["tone_name"]) print values for el in tones["emotion"]: scores.append(el["score"]) for el in tones["language"]: scores.append(el["score"]) for el in tones["social"]: scores.append(el["score"]) print scores #print values #print scores ret={} ret["values"] = values ret["scores"] = scores f = open('out.json', 'w+') f.write(str(ret)) return util.json_response(ret);
def user_get(): # Authorization user = mongo.db.users.find_one({'_id': ObjectId(session['userId'])}) if not user: return json_response({'message': 'cannot find user'}, status_code=500) return json_response(user)
def submit(request): auth_user(request.cookies.get('auth')) if not g.user: result = {'status': 'error', 'error': 'Not authenticated.' } return util.json_response(result) if request.POST.get('apisecret') != g.user["apisecret"]: result = {'status': 'error', 'error': 'Wrong form secret' } return util.json_response(result) title = request.POST.get('title') url = request.POST.get('url') text = request.POST.get('text') news_id = util.force_int(request.POST.get('news_id')) if text: text = text.lstrip('\r\n').rstrip() if not title or (not url and not text): result = {'status': 'error', 'error': 'title and (url or text) required' } return util.json_response(result) # Make sure the URL is about an acceptable protocol, that is # http:// or https:// for now. if url and not url.startswith('http://') and not url.startswith('https://'): result = {'status': 'error', 'error': 'we only accept http:// and https:// news' } return util.json_response(result) if len(title) > config.MaxTitleLen or len(url) > config.MaxUrlLen: result = {'status': 'error', 'error': 'title or url too long' } return util.json_response(result) if not url and len(text) > config.CommentMaxLength: result = {'status': 'error', 'error': 'text too long' } return util.json_response(result) if news_id is None: result = {'status': 'error', 'error': 'bad news_id' } return util.json_response(result) if news_id == -1: if limit.submitted_recently(): result = {'status': 'error', 'error': "You have submitted a story too recently, " + "please wait %s seconds." % limit.allowed_to_post_in_seconds() } return util.json_response(result) news_id = insert_news(title, url, text, g.user['id']) else: news_id = edit_news(news_id, title, url, text, g.user['id']) if not news_id: result = {'status': 'error', 'error': 'Invalid parameters, news too old to be modified' + 'or url recently posted.' } return util.json_response(result) result = {'status': 'ok', 'news_id': int(news_id) } return util.json_response(result)
def submit(request): auth_user(request.cookies.get("auth")) if not g.user: result = {"status": "error", "error": "Not authenticated."} return util.json_response(result) if request.POST.get("apisecret") != g.user["apisecret"]: result = {"status": "error", "error": "Wrong form secret"} return util.json_response(result) title = request.POST.get("title") url = request.POST.get("url") text = request.POST.get("text") news_id = util.force_int(request.POST.get("news_id")) if text: text = text.lstrip("\r\n").rstrip() if not title or (not url and not text): result = {"status": "error", "error": "title and (url or text) required"} return util.json_response(result) # Make sure the URL is about an acceptable protocol, that is # http:// or https:// for now. if url and not url.startswith("http://") and not url.startswith("https://"): result = {"status": "error", "error": "we only accept http:// and https:// news"} return util.json_response(result) if len(title) > config.MaxTitleLen or len(url) > config.MaxUrlLen: result = {"status": "error", "error": "title or url too long"} return util.json_response(result) if not url and len(text) > config.CommentMaxLength: result = {"status": "error", "error": "text too long"} return util.json_response(result) if news_id is None: result = {"status": "error", "error": "bad news_id"} return util.json_response(result) if news_id == -1: if limit.submitted_recently(): result = { "status": "error", "error": "You have submitted a story too recently, " + "please wait %s seconds." % limit.allowed_to_post_in_seconds(), } return util.json_response(result) news_id = insert_news(title, url, text, g.user["id"]) else: news_id = edit_news(news_id, title, url, text, g.user["id"]) if not news_id: result = { "status": "error", "error": "Invalid parameters, news too old to be modified" + "or url recently posted.", } return util.json_response(result) result = {"status": "ok", "news_id": int(news_id)} return util.json_response(result)