<commit_before># 3rd Party Modules
import flask
import datetime
import os

# Local Modules
import config
import db
import messaging

app = flask.Flask(__name__)

from functools import wraps
from flask import request, Response

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == config.website_user and password == config.website_pass

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route('/')
@app.route('/dashboard')
@requires_auth
def index():

    ops = db.get_all_opportunities()

    for op in ops:
        if op["status"] == "Accepted":
            op["class"] = "success"
        elif op["status"] == "Offered":
            op["class"] = "info"
        elif op["status"] == "Expired":
            op["class"] = "active"
        elif op["status"] == "Attended":
            op["class"] = "active"
        elif op["status"] == "Not Attended":
            op["class"] = "active"

        op["remaining_mins"] = int(int(op["expiry_time"] - db.to_timestamp(datetime.datetime.utcnow())) / 60)

    return flask.render_template('dashboard.html', ops = ops)

@app.route('/new', methods=['GET', 'POST'])
@requires_auth
def render_new_procedure_form():
    if request.method == 'POST':
        opportunity_doctor = flask.request.form['doctor']
        opportunity_procedure = flask.request.form['procedure']
        opportunity_location = flask.request.form['location']
        opportunity_duration = flask.request.form['duration']

        if config.demo_mode:
            opportunity_mobile1 = flask.request.form['mobile_number1']
            opportunity_mobile2 = flask.request.form['mobile_number2']

        opportunity = dict({
            'doctor': opportunity_doctor,
            'procedure': opportunity_procedure,
            'location': opportunity_location,
            'duration': opportunity_duration
        })

        if config.demo_mode:
            demo_mobiles = [opportunity_mobile1, opportunity_mobile2]
        else:
            demo_mobiles = None

        ref_id = db.add_opportunity(opportunity)
        messaging.broadcast_procedure(opportunity_procedure,
                                      opportunity_location,
                                      opportunity_duration,
                                      opportunity_doctor,
                                      ref_id,
                                      demo_mobiles)

        print(flask.json.dumps(opportunity))
        return flask.redirect('/dashboard', code=302)
    else:
        procedures = db.get_procedures()
        locations = db.get_locations()
        timeframes = db.get_timeframes()
        doctors = db.get_doctors()
        demo_mode2 = config.demo_mode
        print(str.format("Demo mode is: {0}", demo_mode2))
        return flask.render_template('new_procedure.html', procedures = procedures, locations = locations,
                                     timeframes = timeframes, doctors = doctors, demo_mode = demo_mode2)

# # Endpoint for new opportunity form submission
# @app.route('/new', methods=['POST'])
# @requires_auth
# def new_opportunity():
#     opportunity_doctor = flask.request.form['doctor']
#     opportunity_procedure = flask.request.form['procedure']
#     opportunity_location = flask.request.form['location']
#     opportunity_duration = flask.request.form['duration']
#     opportunity_mobile1 = flask.request.form['mobile_number1']
#     opportunity_mobile2 = flask.request.form['mobile_number2']
#
#     opportunity = dict({
#         'doctor': opportunity_doctor,
#         'procedure': opportunity_procedure,
#         'location': opportunity_location,
#         'duration': opportunity_duration
#     })
#
#     demo_mobiles = [opportunity_mobile1, opportunity_mobile2]
#
#     # ref_id = db.add_opportunity(opportunity)
#     # messaging.broadcast_procedure(opportunity_procedure,
#     #                               opportunity_location,
#     #                               opportunity_duration,
#     #                               opportunity_doctor,
#     #                               ref_id,
#     #                               demo_mobiles)
#
#     print(flask.json.dumps(opportunity))
#     return flask.redirect('/dashboard', code=302)

# Endpoint for receiving SMS messages from Twilio
@app.route('/sms', methods=['POST'])
@requires_auth
def receive_sms():

    sms = dict(service_number=str(flask.request.form['To']),
               mobile=str(flask.request.form['From']),
               message=str(flask.request.form['Body']))

    print(str.format("Received SMS: \n"
                     "Service Number: {0}\n"
                     "Mobile: {1}\n"
                     "Message: {2}\n",
                     sms['service_number'],
                     sms['mobile'],
                     sms['message']))

    messaging.request_procedure(sms['mobile'], sms['message'])

    db.log_sms(sms['mobile'], sms['service_number'], sms['message'], 'IN')

    return '<Response></Response>'

@app.route('/complete', methods=['POST'])
@requires_auth
def complete_procedure():

    completed_id = flask.request.form['id']

    if flask.request.form['attended_status'] == "Attended":
        attended_status = True
    else:
        attended_status = False

    print(str(completed_id))
    print(str(attended_status))

    db.complete_opportunity(completed_id, attended_status)
    return flask.redirect('/dashboard', code=302)

if __name__ == '__main__':
    app.debug = config.debug_mode
    port = int(os.environ.get("PORT", 5000))
    print(str.format("Debug Mode is: {0}", app.debug))
    print(str.format("Demo Mode is: {0}", config.demo_mode))
    app.run(
        host="0.0.0.0",
        port = port
    )
<commit_msg>Still trying to fix the new POST<commit_after># 3rd Party Modules
import flask
import datetime
import os

# Local Modules
import config
import db
import messaging

app = flask.Flask(__name__)

from functools import wraps
from flask import request, Response

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == config.website_user and password == config.website_pass

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route('/')
@app.route('/dashboard')
@requires_auth
def index():

    ops = db.get_all_opportunities()

    for op in ops:
        if op["status"] == "Accepted":
            op["class"] = "success"
        elif op["status"] == "Offered":
            op["class"] = "info"
        elif op["status"] == "Expired":
            op["class"] = "active"
        elif op["status"] == "Attended":
            op["class"] = "active"
        elif op["status"] == "Not Attended":
            op["class"] = "active"

        op["remaining_mins"] = int(int(op["expiry_time"] - db.to_timestamp(datetime.datetime.utcnow())) / 60)

    return flask.render_template('dashboard.html', ops = ops)

@app.route('/new', methods=['GET', 'POST'])
@requires_auth
def render_new_procedure_form():
    if request.method == 'POST':
        print(request.form)
        opportunity_doctor = flask.request.form['doctor']
        opportunity_procedure = flask.request.form['procedure']
        opportunity_location = flask.request.form['location']
        opportunity_duration = flask.request.form['duration']

        if config.demo_mode:
            opportunity_mobile1 = flask.request.form['mobile_number1']
            opportunity_mobile2 = flask.request.form['mobile_number2']

        opportunity = dict({
            'doctor': opportunity_doctor,
            'procedure': opportunity_procedure,
            'location': opportunity_location,
            'duration': opportunity_duration
        })

        if config.demo_mode:
            demo_mobiles = [opportunity_mobile1, opportunity_mobile2]
        else:
            demo_mobiles = None

        ref_id = db.add_opportunity(opportunity)
        messaging.broadcast_procedure(opportunity_procedure,
                                      opportunity_location,
                                      opportunity_duration,
                                      opportunity_doctor,
                                      ref_id,
                                      demo_mobiles)

        print(flask.json.dumps(opportunity))
        return flask.redirect('/dashboard', code=302)
    else:
        procedures = db.get_procedures()
        locations = db.get_locations()
        timeframes = db.get_timeframes()
        doctors = db.get_doctors()
        demo_mode2 = config.demo_mode
        print(str.format("Demo mode is: {0}", demo_mode2))
        return flask.render_template('new_procedure.html', procedures = procedures, locations = locations,
                                     timeframes = timeframes, doctors = doctors, demo_mode = demo_mode2)

# Endpoint for receiving SMS messages from Twilio
@app.route('/sms', methods=['POST'])
@requires_auth
def receive_sms():

    sms = dict(service_number=str(flask.request.form['To']),
               mobile=str(flask.request.form['From']),
               message=str(flask.request.form['Body']))

    print(str.format("Received SMS: \n"
                     "Service Number: {0}\n"
                     "Mobile: {1}\n"
                     "Message: {2}\n",
                     sms['service_number'],
                     sms['mobile'],
                     sms['message']))

    messaging.request_procedure(sms['mobile'], sms['message'])

    db.log_sms(sms['mobile'], sms['service_number'], sms['message'], 'IN')

    return '<Response></Response>'

@app.route('/complete', methods=['POST'])
@requires_auth
def complete_procedure():

    completed_id = flask.request.form['id']

    if flask.request.form['attended_status'] == "Attended":
        attended_status = True
    else:
        attended_status = False

    print(str(completed_id))
    print(str(attended_status))

    db.complete_opportunity(completed_id, attended_status)
    return flask.redirect('/dashboard', code=302)

if __name__ == '__main__':
    app.debug = config.debug_mode
    port = int(os.environ.get("PORT", 5000))
    print(str.format("Debug Mode is: {0}", app.debug))
    print(str.format("Demo Mode is: {0}", config.demo_mode))
    app.run(
        host="0.0.0.0",
        port = port
    )
<|endoftext|>


<commit_before>import os
from datetime import datetime, timedelta
import pymongo
import json
from urlparse import parse_qs, urlparse
from bson import json_util, code
import xlwt
from cStringIO import StringIO
from itertools import groupby
from operator import itemgetter

from flask import Flask, request, make_response
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.url_map.strict_slashes = False

env = os.environ.get('PROJECTENV')

DEBUG = False

if env == 'local':
    c = pymongo.MongoClient(host=os.environ['CRIME_MONGO'])
    DEBUG = True
else:
    c = pymongo.MongoClient()
    app.config['SENTRY_DSN'] = os.environ['SENTRY_URL']
    sentry = Sentry(app)
db = c['chicago']
db.authenticate(os.environ['CHICAGO_MONGO_USER'], os.environ['CHICAGO_MONGO_PW'])
crime_coll = db['crime']
iucr_coll = db['iucr']

OK_FIELDS = [
    'year',
    'domestic',
    'case_number',
    'id',
    'primary_type',
    'district',
    'arrest',
    'location',
    'community_area',
    'description',
    'beat',
    'date',
    'ward',
    'iucr',
    'location_description',
    'updated_on',
    'fbi_code',
    'block',
    'type',
    'time',
]

OK_FILTERS = [
    'lt',
    'lte',
    'gt',
    'gte',
    'near',
    'geoWithin',
    'in',
    'ne',
    'nin',
    None,
]

WORKSHEET_COLUMNS = [
    'date',
    'primary_type',
    'description',
    'location_description',
    'iucr',
    'case_number',
    'block',
    'ward',
    'community_area',
    'beat',
    'district',
    'time_of_day'
]

@app.route('/api/report/', methods=['GET'])
def crime_report():
    get = request.args
    query = json_util.loads(get['query'])
    results = list(crime_coll.find(query).hint([('date', -1)]))
    book = xlwt.Workbook()
    types = ', '.join(query['type']['$in'])
    from_date = query['date']['$gte'].strftime('%m/%d/%Y')
    to_date = query['date']['$lte'].strftime('%m/%d/%Y')
    sheet_title = 'Between %s and %s' % (from_date, to_date)
    sheet = book.add_sheet('Crime')
    for i,col_name in enumerate(WORKSHEET_COLUMNS):
        if col_name != '_id':
            sheet.write(0, i, ' '.join(col_name.split('_')).title())
    for i, result in enumerate(results):
        i += 1
        del result['_id']
        for j, key in enumerate(WORKSHEET_COLUMNS):
            try:
                value = result[key]
            except KeyError:
                value = ''
            if type(value) == datetime:
                value = result[key].strftime('%Y-%m-%d')
            if key == 'time_of_day':
                value = result['date'].strftime('%H:%M')
            sheet.write(i, j, value)
    out = StringIO()
    book.save(out)
    resp = make_response(out.getvalue())
    resp.headers['Content-Type'] = 'application/vnd.ms-excel'
    resp.headers['Content-Disposition'] = 'attachment; filename=Crime.xls'
    resp.set_cookie('fileDownload', value="true")
    return resp

# expects GeoJSON object as a string
# client will need to use JSON.stringify() or similar

@app.route('/api/crime/', methods=['GET'])
def crime_list():
    get = request.args.copy()
    callback = get.get('callback', None)
    maxDistance = get.get('maxDistance', 1000)
    limit = int(get.get('limit', 2000))
    resp_format = get.get('format', 'jsonp')
    if limit > 2000:
        limit = 2000
    if not callback:
        resp = {
            'status': 'Bad Request',
            'message': 'You must provide the name of a callback',
            'code': 400
        }
    else:
        del get['callback']
        try:
            del get['_']
        except KeyError:
            pass
        try:
            del get['maxDistance']
        except KeyError:
            pass
        try:
            del get['limit']
        except KeyError:
            pass
        try:
            del get['format']
        except KeyError:
            pass
        query = {}
        resp = None
        for field,value in get.items():
            filt = None
            geom = None
            try:
                field, filt = field.split('__')
            except ValueError:
                pass
            if field not in OK_FIELDS:
                resp = {
                    "status": "Bad Request",
                    "message": "Unrecognized field: '%s'" % field,
                    "code": 400,
                }
            else:
                if field in ['date', 'updated_on']:
                    try:
                        value = datetime.fromtimestamp(float(value))
                    except TypeError:
                        resp = {
                            'status': 'Bad Request',
                            'message': 'Date time queries expect a valid timestamp',
                            'code': 400
                        }
                if filt not in OK_FILTERS:
                    resp = {
                        'status': 'Bad Request',
                        'message': "Unrecognized query operator: '%s'" % filt,
                        'code': 400,
                    }
                elif field == 'location':
                    query[field] = {'$%s' % filt: {'$geometry': json.loads(value)}}
                    if filt == 'near':
                        query[field]['$%s' % filt]['$maxDistance'] = maxDistance
                elif field in ['fbi_code', 'iucr', 'type']:
                    query[field] = {'$in': value.split(',')}
                elif field == 'time':
                    try:
                        time_range = sorted(list(set([int(v) for v in value.split(',')])))
                        times = time_range[0], time_range[-1]
                        query['$where'] = code.Code('this.date.getHours() > %s && this.date.getHours() < %s' % times)
                    except ValueError:
                        # Someone unchecked all the boxes
                        pass
                elif filt:
                    if query.has_key(field):
                        update = {'$%s' % filt: value}
                        query[field].update(**update)
                    else:
                        query[field] = {'$%s' % filt: value}
                else:
                    query[field] = value
        if not query.has_key('date'):
            query['date'] = {'$gte': datetime.now() - timedelta(days=14)}
        if not query.has_key('type'):
            query['type'] = {'$in': ['violent', 'property', 'quality']}
        if not resp:
            results = list(crime_coll.find(query).hint([('date', -1)]).limit(limit))
            results = sorted(results, key=itemgetter('type'))
            totals_by_type = {}
            totals_by_date = {}
            for k,g in groupby(results, key=itemgetter('type')):
                totals_by_type[k] = len(list(g))
            results = sorted(results, key=itemgetter('date'))
            for k,g in groupby(results, key=itemgetter('date')):
                key = k.strftime('%Y-%m-%d')
                count = len(list(g))
                stored_count = totals_by_date.get(key, 0)
                totals_by_date[key] = stored_count + count
            resp = {
                'status': 'ok',
                'results': results,
                'code': 200,
                'meta': {
                    'total_results': len(results),
                    'query': query,
                    'totals_by_type': totals_by_type,
                    'totals_by_date': totals_by_date,
                }
            }
        if resp['code'] == 200:
            if resp_format == 'jsonp':
                out = make_response('%s(%s)' % (callback, json_util.dumps(resp)), resp['code'])
            else:
                out = make_response(json_util.dumps(resp), resp['code'])
        else:
            if not DEBUG:
                sentry.captureMessage(resp)
            out = make_response(json.dumps(resp), resp['code'])
        return out

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 7777))
    app.run(host='0.0.0.0', port=port, debug=True)
<commit_msg>Fixed the query string parsing for the report generator<commit_after>import os
from datetime import datetime, timedelta
import pymongo
import json
from urlparse import parse_qs, urlparse
from bson import json_util, code
import xlwt
from cStringIO import StringIO
from itertools import groupby
from operator import itemgetter

from flask import Flask, request, make_response
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.url_map.strict_slashes = False

env = os.environ.get('PROJECTENV')

DEBUG = False

if env == 'local':
    c = pymongo.MongoClient(host=os.environ['CRIME_MONGO'])
    DEBUG = True
else:
    c = pymongo.MongoClient()
    app.config['SENTRY_DSN'] = os.environ['SENTRY_URL']
    sentry = Sentry(app)
db = c['chicago']
db.authenticate(os.environ['CHICAGO_MONGO_USER'], os.environ['CHICAGO_MONGO_PW'])
crime_coll = db['crime']
iucr_coll = db['iucr']

OK_FIELDS = [
    'year',
    'domestic',
    'case_number',
    'id',
    'primary_type',
    'district',
    'arrest',
    'location',
    'community_area',
    'description',
    'beat',
    'date',
    'ward',
    'iucr',
    'location_description',
    'updated_on',
    'fbi_code',
    'block',
    'type',
    'time',
]

OK_FILTERS = [
    'lt',
    'lte',
    'gt',
    'gte',
    'near',
    'geoWithin',
    'in',
    'ne',
    'nin',
    None,
]

WORKSHEET_COLUMNS = [
    'date',
    'primary_type',
    'description',
    'location_description',
    'iucr',
    'case_number',
    'block',
    'ward',
    'community_area',
    'beat',
    'district',
    'time_of_day'
]

@app.route('/api/report/', methods=['GET'])
def crime_report():
    query = urlparse(request.url).query.replace('query=', '')
    query = json_util.loads(query)
    results = list(crime_coll.find(query).hint([('date', -1)]))
    book = xlwt.Workbook()
    types = ', '.join(query['type']['$in'])
    from_date = query['date']['$gte'].strftime('%m/%d/%Y')
    to_date = query['date']['$lte'].strftime('%m/%d/%Y')
    sheet_title = 'Between %s and %s' % (from_date, to_date)
    sheet = book.add_sheet('Crime')
    for i,col_name in enumerate(WORKSHEET_COLUMNS):
        if col_name != '_id':
            sheet.write(0, i, ' '.join(col_name.split('_')).title())
    for i, result in enumerate(results):
        i += 1
        del result['_id']
        for j, key in enumerate(WORKSHEET_COLUMNS):
            try:
                value = result[key]
            except KeyError:
                value = ''
            if type(value) == datetime:
                value = result[key].strftime('%Y-%m-%d')
            if key == 'time_of_day':
                value = result['date'].strftime('%H:%M')
            sheet.write(i, j, value)
    out = StringIO()
    book.save(out)
    resp = make_response(out.getvalue())
    resp.headers['Content-Type'] = 'application/vnd.ms-excel'
    resp.headers['Content-Disposition'] = 'attachment; filename=Crime.xls'
    resp.set_cookie('fileDownload', value="true")
    return resp

# expects GeoJSON object as a string
# client will need to use JSON.stringify() or similar

@app.route('/api/crime/', methods=['GET'])
def crime_list():
    get = request.args.copy()
    callback = get.get('callback', None)
    maxDistance = get.get('maxDistance', 1000)
    limit = int(get.get('limit', 2000))
    resp_format = get.get('format', 'jsonp')
    if limit > 2000:
        limit = 2000
    if not callback:
        resp = {
            'status': 'Bad Request',
            'message': 'You must provide the name of a callback',
            'code': 400
        }
    else:
        del get['callback']
        try:
            del get['_']
        except KeyError:
            pass
        try:
            del get['maxDistance']
        except KeyError:
            pass
        try:
            del get['limit']
        except KeyError:
            pass
        try:
            del get['format']
        except KeyError:
            pass
        query = {}
        resp = None
        for field,value in get.items():
            filt = None
            geom = None
            try:
                field, filt = field.split('__')
            except ValueError:
                pass
            if field not in OK_FIELDS:
                resp = {
                    "status": "Bad Request",
                    "message": "Unrecognized field: '%s'" % field,
                    "code": 400,
                }
            else:
                if field in ['date', 'updated_on']:
                    try:
                        value = datetime.fromtimestamp(float(value))
                    except TypeError:
                        resp = {
                            'status': 'Bad Request',
                            'message': 'Date time queries expect a valid timestamp',
                            'code': 400
                        }
                if filt not in OK_FILTERS:
                    resp = {
                        'status': 'Bad Request',
                        'message': "Unrecognized query operator: '%s'" % filt,
                        'code': 400,
                    }
                elif field == 'location':
                    query[field] = {'$%s' % filt: {'$geometry': json.loads(value)}}
                    if filt == 'near':
                        query[field]['$%s' % filt]['$maxDistance'] = maxDistance
                elif field in ['fbi_code', 'iucr', 'type']:
                    query[field] = {'$in': value.split(',')}
                elif field == 'time':
                    try:
                        time_range = sorted(list(set([int(v) for v in value.split(',')])))
                        times = time_range[0], time_range[-1]
                        query['$where'] = code.Code('this.date.getHours() > %s && this.date.getHours() < %s' % times)
                    except ValueError:
                        # Someone unchecked all the boxes
                        pass
                elif filt:
                    if query.has_key(field):
                        update = {'$%s' % filt: value}
                        query[field].update(**update)
                    else:
                        query[field] = {'$%s' % filt: value}
                else:
                    query[field] = value
        if not query.has_key('date'):
            query['date'] = {'$gte': datetime.now() - timedelta(days=14)}
        if not query.has_key('type'):
            query['type'] = {'$in': ['violent', 'property', 'quality']}
        if not resp:
            results = list(crime_coll.find(query).hint([('date', -1)]).limit(limit))
            results = sorted(results, key=itemgetter('type'))
            totals_by_type = {}
            totals_by_date = {}
            for k,g in groupby(results, key=itemgetter('type')):
                totals_by_type[k] = len(list(g))
            results = sorted(results, key=itemgetter('date'))
            for k,g in groupby(results, key=itemgetter('date')):
                key = k.strftime('%Y-%m-%d')
                count = len(list(g))
                stored_count = totals_by_date.get(key, 0)
                totals_by_date[key] = stored_count + count
            resp = {
                'status': 'ok',
                'results': results,
                'code': 200,
                'meta': {
                    'total_results': len(results),
                    'query': query,
                    'totals_by_type': totals_by_type,
                    'totals_by_date': totals_by_date,
                }
            }
        if resp['code'] == 200:
            if resp_format == 'jsonp':
                out = make_response('%s(%s)' % (callback, json_util.dumps(resp)), resp['code'])
            else:
                out = make_response(json_util.dumps(resp), resp['code'])
        else:
            if not DEBUG:
                sentry.captureMessage(resp)
            out = make_response(json.dumps(resp), resp['code'])
        return out

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 7777))
    app.run(host='0.0.0.0', port=port, debug=True)
<|endoftext|>


<commit_before>import bottle
import json

app = application = bottle.Bottle()

_temp = 0
@app.route('/temperature_pressure', method='POST')
def temperature_data():
    for l in bottle.request.body:
        print (l)
    print (bottle.request.body)
    data = json.loads(bottle.request.body)
    _temp = data["temperature"]

@app.route('/temperature_pressure', method='GET')
def temperature_data():
    #return bottle.template('Hello World!')
    return bottle.template(' Latest temperature is: {{temp}} ', temp=_temp)

#debug stuff
if __name__ == '__main__':
    bottle.run(app=application, host='0.0.0.0', port=5000)
<commit_msg>Cast POST body string so that the json module can parse it.<commit_after>import bottle
import json

app = application = bottle.Bottle()

_temp = 0
@app.route('/temperature_pressure', method='POST')
def temperature_data():
    for l in bottle.request.body:
        print (l)
    print (bottle.request.body)
    data = json.loads(str(bottle.request.body))
    _temp = data["temperature"]

@app.route('/temperature_pressure', method='GET')
def temperature_data():
    #return bottle.template('Hello World!')
    return bottle.template(' Latest temperature is: {{temp}} ', temp=_temp)

#debug stuff
if __name__ == '__main__':
    bottle.run(app=application, host='0.0.0.0', port=5000)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from functools import wraps
import json

import argparse
from flask import Blueprint, Flask, make_response, render_template
from peewee import fn

import app_config
from render_utils import make_context, smarty_filter, urlencode_filter
import static
import static_app
import static_theme
from models import Race

app = Flask(__name__)

app.jinja_env.filters['smarty'] = smarty_filter
app.jinja_env.filters['urlencode'] = urlencode_filter

def _group_races_by_closing_time(races):
    """
    Process race results for use in templates.
    """
    results = {}

    for race in races:
        if not results.get(race.poll_closing_time):
            results[race.poll_closing_time] = []
        results[race.poll_closing_time].append(race)

    return sorted(results.items())

def _partition(l):
    """
    Split a list in two!
    """
    length = len(l)
    left = int(round(length / 2.))
    return (l[0:left], l[left:])

@app.template_filter()
def format_closing_time(dt):
   return '{d:%l}:{d.minute:02}'.format(d=dt)

def cors(f):
    """
    Decorator that enables local CORS support for easier local dev.
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        response = make_response(f(*args, **kwargs))
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    return decorated_function

# Example application views
@app.route('/')
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    from models import Race

    context = make_context()

    with open('data/featured.json') as f:
        context['featured'] = json.load(f)

    context['races'] = Race.select()

    return render_template('index.html', **context), 200,

@app.route('/chromecast/')
def chromecast():
    """
    Custom Chromecast receiver.
    """
    context = make_context()

    return render_template('chromecast.html', **context)

@app.route('/game/')
def game():
    """
    Custom Chromecast receiver.
    """
    context = make_context()

    secrets = app_config.get_secrets()
    context['DYNAMODB_ACCESS_KEY_ID'] = secrets['DYNAMODB_ACCESS_KEY_ID']
    context['DYNAMODB_SECRET_ACCESS_KEY'] = secrets['DYNAMODB_SECRET_ACCESS_KEY']

    return render_template('game.html', **context)

@app.route('/results/house/')
def results_house():
    """
    House big board
    """
    context = make_context()

    return render_template('slides/house.html', **context)

@app.route('/results/senate/')
def results_senate():
    """
    Senate big board
    """
    context = make_context()
    races = Race.select().where(Race.office_name == "U.S. Senate")
    grouped = _group_races_by_closing_time(races)
    context["race_columns"] = _partition(grouped)
    return render_template('slides/senate.html', **context)

@app.route('/comments/')
def comments():
    """
    Full-page comments view.
    """
    return render_template('comments.html', **make_context())

@app.route('/widget.html')
def widget():
    """
    Embeddable widget example page.
    """
    return render_template('widget.html', **make_context())

@app.route('/test_widget.html')
def test_widget():
    """
    Example page displaying widget at different embed sizes.
    """
    return render_template('test_widget.html', **make_context())

@app.route('/slides/<slug>.html')
@cors
def _slide(slug):
    """
    Serve up slide html fragment
    """
    from models import Slide

    slide = Slide.get(Slide.slug == slug)
    return render_template('_stack_fragment.html', body=slide.body)

@app.route('/live-data/next-slide.json')
@cors
def _stack_json():
    """
    Serve up pointer to next slide in stack
    """
    from models import SlideSequence

    if not hasattr(app, 'stack_number'):
        min_sequence = SlideSequence.select(fn.Min(SlideSequence.sequence)).scalar()
        app.stack_number = min_sequence

    max = SlideSequence.select(fn.Max(SlideSequence.sequence)).scalar()
    if app.stack_number > max:
        min = SlideSequence.select(fn.Min(SlideSequence.sequence)).scalar()
        app.stack_number = min

    next_slide = SlideSequence.get(SlideSequence.sequence == app.stack_number)
    app.stack_number += 1

    js = json.dumps({
        'next': 'slides/%s.html' % next_slide.slide.slug,
    })
    return js, 200, { 'Content-Type': 'application/javascript' }

@app.route('/stack/')
def stack():
    """
    Serve shell page for stack
    """
    context = make_context()

    return render_template('stack.html', **context)

app.register_blueprint(static.static)
app.register_blueprint(static_app.static_app)
app.register_blueprint(static_theme.theme)

# Boilerplate
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port')
    args = parser.parse_args()
    server_port = 8000

    if args.port:
        server_port = int(args.port)

    app.run(host='0.0.0.0', port=server_port, debug=app_config.DEBUG)
<commit_msg>Don't crash when we don't have poll closing times.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from functools import wraps
import json

import argparse
from flask import Flask, make_response, render_template
from peewee import fn

import app_config
from render_utils import make_context, smarty_filter, urlencode_filter
import static
import static_app
import static_theme

app = Flask(__name__)

app.jinja_env.filters['smarty'] = smarty_filter
app.jinja_env.filters['urlencode'] = urlencode_filter

def _group_races_by_closing_time(races):
    """
    Process race results for use in templates.
    """
    results = {}

    for race in races:
        if not results.get(race.poll_closing_time):
            results[race.poll_closing_time] = []

        results[race.poll_closing_time].append(race)

    return sorted(results.items())

def _partition(l):
    """
    Split a list in two!
    """
    length = len(l)
    left = int(round(length / 2.))
    return (l[0:left], l[left:])

@app.template_filter()
def format_closing_time(dt):
    if not dt:
        return ''

    return '{d:%l}:{d.minute:02}'.format(d=dt)

def cors(f):
    """
    Decorator that enables local CORS support for easier local dev.
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        response = make_response(f(*args, **kwargs))
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    return decorated_function

# Example application views
@app.route('/')
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    from models import Race

    context = make_context()

    with open('data/featured.json') as f:
        context['featured'] = json.load(f)

    context['races'] = Race.select()

    return render_template('index.html', **context), 200,

@app.route('/chromecast/')
def chromecast():
    """
    Custom Chromecast receiver.
    """
    context = make_context()

    return render_template('chromecast.html', **context)

@app.route('/game/')
def game():
    """
    Custom Chromecast receiver.
    """
    context = make_context()

    secrets = app_config.get_secrets()
    context['DYNAMODB_ACCESS_KEY_ID'] = secrets['DYNAMODB_ACCESS_KEY_ID']
    context['DYNAMODB_SECRET_ACCESS_KEY'] = secrets['DYNAMODB_SECRET_ACCESS_KEY']

    return render_template('game.html', **context)

@app.route('/results/house/')
def results_house():
    """
    House big board
    """
    context = make_context()

    return render_template('slides/house.html', **context)

@app.route('/results/senate/')
def results_senate():
    """
    Senate big board
    """
    from models import Race

    context = make_context()

    races = Race.select().where(Race.office_name == "U.S. Senate")
    grouped = _group_races_by_closing_time(races)
    context["race_columns"] = _partition(grouped)

    return render_template('slides/senate.html', **context)

@app.route('/comments/')
def comments():
    """
    Full-page comments view.
    """
    return render_template('comments.html', **make_context())

@app.route('/widget.html')
def widget():
    """
    Embeddable widget example page.
    """
    return render_template('widget.html', **make_context())

@app.route('/test_widget.html')
def test_widget():
    """
    Example page displaying widget at different embed sizes.
    """
    return render_template('test_widget.html', **make_context())

@app.route('/slides/<slug>.html')
@cors
def _slide(slug):
    """
    Serve up slide html fragment
    """
    from models import Slide

    slide = Slide.get(Slide.slug == slug)
    return render_template('_stack_fragment.html', body=slide.body)

@app.route('/live-data/next-slide.json')
@cors
def _stack_json():
    """
    Serve up pointer to next slide in stack
    """
    from models import SlideSequence

    if not hasattr(app, 'stack_number'):
        min_sequence = SlideSequence.select(fn.Min(SlideSequence.sequence)).scalar()
        app.stack_number = min_sequence

    max = SlideSequence.select(fn.Max(SlideSequence.sequence)).scalar()
    if app.stack_number > max:
        min = SlideSequence.select(fn.Min(SlideSequence.sequence)).scalar()
        app.stack_number = min

    next_slide = SlideSequence.get(SlideSequence.sequence == app.stack_number)
    app.stack_number += 1

    js = json.dumps({
        'next': 'slides/%s.html' % next_slide.slide.slug,
    })
    return js, 200, { 'Content-Type': 'application/javascript' }

@app.route('/stack/')
def stack():
    """
    Serve shell page for stack
    """
    context = make_context()

    return render_template('stack.html', **context)

app.register_blueprint(static.static)
app.register_blueprint(static_app.static_app)
app.register_blueprint(static_theme.theme)

# Boilerplate
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port')
    args = parser.parse_args()
    server_port = 8000

    if args.port:
        server_port = int(args.port)

    app.run(host='0.0.0.0', port=server_port, debug=app_config.DEBUG)
<|endoftext|>


<commit_before>"""spark-kafka-openshift skeleton

This is a skeleton application for processing stream data from Apache
Kafka with Apache Spark. It will read messages on an input topic and
simply echo those message to the output topic.

For an entry point to adding your own processing component, examine
the `EchoStreamProcessor` class and its `configure_processing`
function.
"""

import argparse
import os
import re

import kafka
import pyspark
from pyspark import streaming
from pyspark.streaming import kafka as kstreaming

class EchoStreamProcessor():
    """A class to echo Kafka stream data

    This class wraps the Spark and Kafka specific logic for creating a
    DStream and applying processing functions to the RDDs contained
    therein.

    It is meant as an example of how to configure a processor to read
    from Kafka and write data back to Kafka. See the
    `configure_processing` function for a place to add your custom
    modifications.
    """
    def __init__(self, input_topic, output_topic, servers, duration):
        """Create a new StreamProcessor

        Keyword arguments:
        input_topic -- Kafka topic to read messages from
        output_topic -- Kafka topic to write message to
        servers -- A list of Kafka brokers
        duration -- The window duration to sample the Kafka stream in
                    seconds
        """
        self.input_topic = input_topic
        self.output_topic = output_topic
        self.servers = servers
        self.spark_context = pyspark.SparkContext(
            appName='spark-kafka-skeleton')
        self.streaming_context = streaming.StreamingContext(
            self.spark_context, duration)
        self.kafka_stream = kstreaming.KafkaUtils.createDirectStream(
            self.streaming_context,
            [self.input_topic],
            {'bootstrap.servers': self.servers})

    def configure_processing(self):
        """Configure the processing pipeline

        This function contains all the stream processing
        configuration that will affect how each RDD is processed.
        It will be called before the stream listener is started.
        """
        def send_response(rdd):
            """A function to publish an RDD to a Kafka topic"""
            producer = kafka.KafkaProducer(bootstrap_servers=self.servers)
            for r in rdd.collect():
                try:
                    producer.send(self.output_topic, r)
                except:
                    print('Error sending collected RDD: {}'.format(r))
            producer.flush()

        messages = self.kafka_stream.map(lambda m: m[1])
        messages.foreachRDD(send_response)

    def start_and_await_termination(self):
        """Start the stream processor

        This function will start the Spark-based stream processor,
        it will run until `stop` is called or an exception is
        thrown.
        """
        self.configure_processing()
        self.streaming_context.start()
        self.streaming_context.awaitTermination()

    def stop(self):
        """Stop the stream processor"""
        self.streaming_context.stop()

def main():
    """The main function

    This will process the command line arguments and launch the main
    Spark/Kafka monitor class.
    """
    parser = argparse.ArgumentParser(
        description='process data with Spark, using Kafka as the transport')
    parser.add_argument('--in', dest='input_topic',
        help='the kafka topic to read data from')
    parser.add_argument('--out', dest='output_topic',
        help='the kafka topic to publish data to')
    parser.add_argument('--servers', help='the kafka brokers')
    args = parser.parse_args()

    processor = EchoStreamProcessor(
        input_topic = args.input_topic,
        output_topic = args.output_topic,
        servers = args.servers,
        duration = 3)

    processor.start_and_await_termination()

if __name__ == '__main__':
    main()

<commit_msg>add more string processing to collected RDD<commit_after>"""spark-kafka-openshift skeleton

This is a skeleton application for processing stream data from Apache
Kafka with Apache Spark. It will read messages on an input topic and
simply echo those message to the output topic.

For an entry point to adding your own processing component, examine
the `EchoStreamProcessor` class and its `configure_processing`
function.
"""

import argparse
import os
import re

import kafka
import pyspark
from pyspark import streaming
from pyspark.streaming import kafka as kstreaming

class EchoStreamProcessor():
    """A class to echo Kafka stream data

    This class wraps the Spark and Kafka specific logic for creating a
    DStream and applying processing functions to the RDDs contained
    therein.

    It is meant as an example of how to configure a processor to read
    from Kafka and write data back to Kafka. See the
    `configure_processing` function for a place to add your custom
    modifications.
    """
    def __init__(self, input_topic, output_topic, servers, duration):
        """Create a new StreamProcessor

        Keyword arguments:
        input_topic -- Kafka topic to read messages from
        output_topic -- Kafka topic to write message to
        servers -- A list of Kafka brokers
        duration -- The window duration to sample the Kafka stream in
                    seconds
        """
        self.input_topic = input_topic
        self.output_topic = output_topic
        self.servers = servers
        self.spark_context = pyspark.SparkContext(
            appName='spark-kafka-skeleton')
        self.streaming_context = streaming.StreamingContext(
            self.spark_context, duration)
        self.kafka_stream = kstreaming.KafkaUtils.createDirectStream(
            self.streaming_context,
            [self.input_topic],
            {'bootstrap.servers': self.servers})

    def configure_processing(self):
        """Configure the processing pipeline

        This function contains all the stream processing
        configuration that will affect how each RDD is processed.
        It will be called before the stream listener is started.
        """
        def send_response(rdd):
            """A function to publish an RDD to a Kafka topic"""
            producer = kafka.KafkaProducer(bootstrap_servers=self.servers)
            for r in rdd.collect():
                try:
                    record = '{}'.format(r)
                    producer.send(self.output_topic, record)
                except Exception as e:
                    print('Error sending collected RDD: {}'.format(r))
                    print('Original exception: {}'.format(e))
            producer.flush()

        messages = self.kafka_stream.map(lambda m: m[1])
        messages.foreachRDD(send_response)

    def start_and_await_termination(self):
        """Start the stream processor

        This function will start the Spark-based stream processor,
        it will run until `stop` is called or an exception is
        thrown.
        """
        self.configure_processing()
        self.streaming_context.start()
        self.streaming_context.awaitTermination()

    def stop(self):
        """Stop the stream processor"""
        self.streaming_context.stop()

def main():
    """The main function

    This will process the command line arguments and launch the main
    Spark/Kafka monitor class.
    """
    parser = argparse.ArgumentParser(
        description='process data with Spark, using Kafka as the transport')
    parser.add_argument('--in', dest='input_topic',
        help='the kafka topic to read data from')
    parser.add_argument('--out', dest='output_topic',
        help='the kafka topic to publish data to')
    parser.add_argument('--servers', help='the kafka brokers')
    args = parser.parse_args()

    processor = EchoStreamProcessor(
        input_topic = args.input_topic,
        output_topic = args.output_topic,
        servers = args.servers,
        duration = 3)

    processor.start_and_await_termination()

if __name__ == '__main__':
    main()

<|endoftext|>


<commit_before>from flask import Flask
from flask import request
from flask import jsonify
import sqlite3
app = Flask(__name__)

conn = sqlite3.connect('db.db')

@app.route("/")
def hello():
	return "executed"

def jsonify_get_images(lst):
	ret_list = list()
	for img,logo in lst:
		ret_list.append({"image": img, "logo": logo})

	return ret_list

@app.route("/get-images")
def get_images():

	if request.args.get('image'):
		c = conn.cursor()
		c.execute('SELECT * FROM images where name=\'' + request.args.get('image') + '\'')
		return jsonify(jsonify_get_images(c.fetchall()))
	else:
		c = conn.cursor()
		c.execute('SELECT * FROM images')
		return jsonify(jsonify_get_images(c.fetchall()))

	print(request.args.get('image'))
if __name__ == "__main__":
    app.run()<commit_msg>remove print<commit_after>from flask import Flask
from flask import request
from flask import jsonify
import sqlite3
app = Flask(__name__)

conn = sqlite3.connect('db.db')

@app.route("/")
def hello():
	return "executed"

def jsonify_get_images(lst):
	ret_list = list()
	for img,logo in lst:
		ret_list.append({"image": img, "logo": logo})

	return ret_list

@app.route("/get-images")
def get_images():

	if request.args.get('image'):
		c = conn.cursor()
		c.execute('SELECT * FROM images where name=\'' + request.args.get('image') + '\'')
		return jsonify(jsonify_get_images(c.fetchall()))
	else:
		c = conn.cursor()
		c.execute('SELECT * FROM images')
		return jsonify(jsonify_get_images(c.fetchall()))

if __name__ == "__main__":
    app.run()<|endoftext|>


<commit_before>#!/usr/bin/env python

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

import json
import os

import re #retira etiquetas HTML de la descripción

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)#Invoca función de consulta y muestra speech al situr3

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def listadoBusqueda(dato_recuperado):
    for x in range(0,len(dato_recuperado)):
        print (dato_recuperado[x]['title']['rendered'], end=", ")
    return

def makeWebhookResult(req):
    if req.get("result").get("action") != "buscarAtractivos":
        return {}
    result = req.get("result")#invocar el result del json
    parameters = result.get("parameters")#invocar el parameters dentro de result
    atractivos = parameters.get("atractivos")#DATO TRAÍDO DE API.AI - ATRACTIVOS

    #URL BASE CONSULTA ATRACTIVOS JSON
    baseUrlAtractivos = "http://situr.boyaca.gov.co/wp-json/wp/v2/atractivo_turistico?orderby=relevance&search="#URL Base Atractivos
    baseUrlImgAtract = "http://www.situr.boyaca.gov.co/wp-json/wp/v2/media/"#URL Base Imagenes Atractivos
    retirarEspacios = atractivos.replace(" ",  "%20")#Retirar Espacios Atractivos

    leerAtractivo = json.loads(urlopen(baseUrlAtractivos + retirarEspacios).read())
    cantidadResultados = str(len(leerAtractivo))#Contar Cantidad de Resultados Encontrados
    range(0,len(leerAtractivo))#Rango que recorre la cantidad de resultados mostrados

    tituloAtractivo = leerAtractivo[0]['title']['rendered']
    descripcionAtractivo = re.sub("<.*?>", "", leerAtractivo[0]['excerpt']['rendered'])
    urlAtractivo = leerAtractivo[0].get('link')
    idImagenAtractivo = str(leerAtractivo[0]['featured_media'])

    leerImagenAtr = json.loads(urlopen(baseUrlImgAtract + idImagenAtractivo).read())
    imagenAtractivo = leerImagenAtr['media_details']['sizes']['medium']['source_url']

  #  pollo = listadoBusqueda(leerAtractivo)

    speech = "Encontré " + cantidadResultados + " Resultados.   El atractivo que solicitaste es: " + tituloAtractivo + "  y la url de la imagen es: " + imagenAtractivo
    fbMsg = {
            "facebook" : {
                "text":"hello, world!"
            }
"""            "facebook" : {
                "attachment" : {
                    "type" : "template",
                    "payload" : {
                        "template_type" : "generic",
                        "elements" : [
                            {
                                "title" : tituloAtractivo,
                                "image_url" : imagenAtractivo,
                                "subtitle": descripcionAtractivo,
                                "buttons":  [
                                    {
                                        "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton1"
                                    },
                                    {
                                         "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton2"
                                    },
                                    {
                                          "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton3"
                                    }
                                ]
                            },
                            {
                                "title": tituloAtractivo,
                                "image_url": imagenAtractivo,
                                "subtitle": descripcionAtractivo,
                                "default_action": {
                                    "type": "web_url",
                                    "url": "https://www.moovrika.com/m/4167",
                                    "webview_height_ratio": "tall"
                                },
                                "buttons": [
                                    {
                                        "title": "más info",
                                        "type": "web_url",
                                        "url": "https://www.moovrika.com/m/4082",
                                        "webview_height_ratio": "tall"
                                    },
                                    {
                                         "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton2"
                                    },
                                    {
                                          "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton3"
                                    }
                                ]
                            }
                       ]
                   }
                }
            }"""
        }

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        "data" : fbMsg,
"""        "data" : {
                "facebook" : {
                    "attachment" : {
                        "type" : "template",
                        "payload" : {
                            "template_type" : "generic",
                            "elements" : [
                                {
                                    "title" : tituloAtractivo,
                                    "image_url" : imagenAtractivo,
                                    "subtitle": descripcionAtractivo,
                                    "buttons":  [
                                        {
                                            "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver"
                                        },
                                        {
                                             "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver2"
                                        },
                                        {
                                              "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver3"
                                        }
                                    ]
                                },
                                {
                                    "title": tituloAtractivo,
                                    "image_url": imagenAtractivo,
                                    "subtitle": descripcionAtractivo,
                                    "default_action": {
                                        "type": "web_url",
                                        "url": "https://www.moovrika.com/m/4167",
                                        "webview_height_ratio": "tall"
                                    },
                                    "buttons": [
                                        {
                                            "title": "more info",
                                            "type": "web_url",
                                            "url": "https://www.moovrika.com/m/4082",
                                            "webview_height_ratio": "tall"
                                        },
                                        {
                                             "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver2"
                                        },
                                        {
                                              "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver3"
                                        }
                                    ]
                                }
                           ]
                       }
                    }
                }
            },"""
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print("Starting app on port %d" % port)

    app.run(debug=False, port=port, host='0.0.0.0')
<commit_msg>concom<commit_after>#!/usr/bin/env python

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

import json
import os

import re #retira etiquetas HTML de la descripción

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)#Invoca función de consulta y muestra speech al situr3

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def listadoBusqueda(dato_recuperado):
    for x in range(0,len(dato_recuperado)):
        print (dato_recuperado[x]['title']['rendered'], end=", ")
    return

def makeWebhookResult(req):
    if req.get("result").get("action") != "buscarAtractivos":
        return {}
    result = req.get("result")#invocar el result del json
    parameters = result.get("parameters")#invocar el parameters dentro de result
    atractivos = parameters.get("atractivos")#DATO TRAÍDO DE API.AI - ATRACTIVOS

    #URL BASE CONSULTA ATRACTIVOS JSON
    baseUrlAtractivos = "http://situr.boyaca.gov.co/wp-json/wp/v2/atractivo_turistico?orderby=relevance&search="#URL Base Atractivos
    baseUrlImgAtract = "http://www.situr.boyaca.gov.co/wp-json/wp/v2/media/"#URL Base Imagenes Atractivos
    retirarEspacios = atractivos.replace(" ",  "%20")#Retirar Espacios Atractivos

    leerAtractivo = json.loads(urlopen(baseUrlAtractivos + retirarEspacios).read())
    cantidadResultados = str(len(leerAtractivo))#Contar Cantidad de Resultados Encontrados
    range(0,len(leerAtractivo))#Rango que recorre la cantidad de resultados mostrados

    tituloAtractivo = leerAtractivo[0]['title']['rendered']
    descripcionAtractivo = re.sub("<.*?>", "", leerAtractivo[0]['excerpt']['rendered'])
    urlAtractivo = leerAtractivo[0].get('link')
    idImagenAtractivo = str(leerAtractivo[0]['featured_media'])

    leerImagenAtr = json.loads(urlopen(baseUrlImgAtract + idImagenAtractivo).read())
    imagenAtractivo = leerImagenAtr['media_details']['sizes']['medium']['source_url']

  #  pollo = listadoBusqueda(leerAtractivo)

    speech = "Encontré " + cantidadResultados + " Resultados.   El atractivo que solicitaste es: " + tituloAtractivo + "  y la url de la imagen es: " + imagenAtractivo
    fbMsg = {
            "facebook" : {
                "text":"hello, world!"
            },
"""            "facebook" : {
                "attachment" : {
                    "type" : "template",
                    "payload" : {
                        "template_type" : "generic",
                        "elements" : [
                            {
                                "title" : tituloAtractivo,
                                "image_url" : imagenAtractivo,
                                "subtitle": descripcionAtractivo,
                                "buttons":  [
                                    {
                                        "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton1"
                                    },
                                    {
                                         "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton2"
                                    },
                                    {
                                          "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton3"
                                    }
                                ]
                            },
                            {
                                "title": tituloAtractivo,
                                "image_url": imagenAtractivo,
                                "subtitle": descripcionAtractivo,
                                "default_action": {
                                    "type": "web_url",
                                    "url": "https://www.moovrika.com/m/4167",
                                    "webview_height_ratio": "tall"
                                },
                                "buttons": [
                                    {
                                        "title": "más info",
                                        "type": "web_url",
                                        "url": "https://www.moovrika.com/m/4082",
                                        "webview_height_ratio": "tall"
                                    },
                                    {
                                         "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton2"
                                    },
                                    {
                                          "type":"web_url",
                                        "url": "http://situr.boyaca.gov.co",
                                        "title": "boton3"
                                    }
                                ]
                            }
                       ]
                   }
                }
            }"""
        }

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        "data" : fbMsg,
"""        "data" : {
                "facebook" : {
                    "attachment" : {
                        "type" : "template",
                        "payload" : {
                            "template_type" : "generic",
                            "elements" : [
                                {
                                    "title" : tituloAtractivo,
                                    "image_url" : imagenAtractivo,
                                    "subtitle": descripcionAtractivo,
                                    "buttons":  [
                                        {
                                            "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver"
                                        },
                                        {
                                             "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver2"
                                        },
                                        {
                                              "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver3"
                                        }
                                    ]
                                },
                                {
                                    "title": tituloAtractivo,
                                    "image_url": imagenAtractivo,
                                    "subtitle": descripcionAtractivo,
                                    "default_action": {
                                        "type": "web_url",
                                        "url": "https://www.moovrika.com/m/4167",
                                        "webview_height_ratio": "tall"
                                    },
                                    "buttons": [
                                        {
                                            "title": "more info",
                                            "type": "web_url",
                                            "url": "https://www.moovrika.com/m/4082",
                                            "webview_height_ratio": "tall"
                                        },
                                        {
                                             "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver2"
                                        },
                                        {
                                              "type":"web_url",
                                            "url": "http://situr.boyaca.gov.co",
                                            "title": "Ver3"
                                        }
                                    ]
                                }
                           ]
                       }
                    }
                }
            },"""
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print("Starting app on port %d" % port)

    app.run(debug=False, port=port, host='0.0.0.0')
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from nose.tools import *  # flake8: noqa

from framework.auth.core import Auth
from website.models import Node
from tests.base import ApiTestCase, fake
from rest_framework import generics, permissions as drf_permissions
from tests.factories import UserFactory, ProjectFactory, FolderFactory, DashboardFactory

class TestUsers(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.save()
        self.user_two = UserFactory.build()
        self.user_two.save()

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_returns_200(self):
        res = self.app.get('/v2/users/')
        assert_equal(res.status_code, 200)

    def test_find_user_in_users(self):
        url = "/v2/users/"

        res = self.app.get(url)
        user_son = res.json['data']

        ids = [each['id'] for each in user_son]
        assert_in(self.user_two._id, ids)

    def test_all_users_in_users(self):
        url = "/v2/users/"

        res = self.app.get(url)
        user_son = res.json['data']

        ids = [each['id'] for each in user_son]
        assert_in(self.user_one._id, ids)
        assert_in(self.user_two._id, ids)

    def test_find_multiple_in_users(self):
        url = "/v2/users/?filter[fullname]=fred"

        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_in(self.user_one._id, ids)
        assert_in(self.user_two._id, ids)

    def test_find_single_user_in_users(self):
        url = "/v2/users/?filter[fullname]=my"
        self.user_one.fullname = 'My Mom'
        self.user_one.save()
        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_in(self.user_one._id, ids)
        assert_not_in(self.user_two._id, ids)

    def test_find_no_user_in_users(self):
        url = "/v2/users/?filter[fullname]=NotMyMom"
        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_not_in(self.user_one._id, ids)
        assert_not_in(self.user_two._id, ids)

class TestUserDetail(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social['twitter'] = 'howtopizza'
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_gets_200(self):
        url = "/v2/users/{}/".format(self.user_one._id)
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

    def test_get_correct_pk_user(self):
        url = "/v2/users/{}/".format(self.user_one._id)
        res = self.app.get(url)
        user_json = res.json['data']
        assert_equal(user_json['fullname'], self.user_one.fullname)
        assert_equal(user_json['social_accounts']['twitter'], 'howtopizza')

    def test_get_incorrect_pk_user_logged_in(self):
        url = "/v2/users/{}/".format(self.user_two._id)
        res = self.app.get(url)
        user_json = res.json['data']
        assert_not_equal(user_json['fullname'], self.user_one.fullname)

    def test_get_incorrect_pk_user_not_logged_in(self):
        url = "/v2/users/{}/".format(self.user_two._id)
        res = self.app.get(url, auth=self.auth_one)
        user_json = res.json['data']
        assert_not_equal(user_json['fullname'], self.user_one.fullname)
        assert_equal(user_json['fullname'], self.user_two.fullname)

class TestUserNodes(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social['twitter'] = 'howtopizza'
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')
        self.user_one_url = '/v2/users/{}/'.format(self.user_one._id)
        self.user_two_url = '/v2/users/{}/'.format(self.user_two._id)
        self.public_project_user_one = ProjectFactory(title="Public Project User One", is_public=True, creator=self.user_one)
        self.private_project_user_one = ProjectFactory(title="Private Project User One", is_public=False, creator=self.user_one)
        self.public_project_user_two = ProjectFactory(title="Public Project User Two", is_public=True, creator=self.user_two)
        self.private_project_user_two = ProjectFactory(title="Private Project User Two", is_public=False, creator=self.user_two)
        self.deleted_project_user_one = FolderFactory(title="Deleted Project User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.folder = FolderFactory()
        self.deleted_folder = FolderFactory(title="Deleted Folder User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.dashboard = DashboardFactory()

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_authorized_in_gets_200(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url, auth=self.auth_one)
        assert_equal(res.status_code, 200)

    def test_anonymous_gets_200(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

    def test_get_projects_logged_in(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url, auth=self.auth_one)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_one._id, ids)
        assert_in(self.private_project_user_one._id, ids)
        assert_not_in(self.public_project_user_two._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

    def test_get_projects_not_logged_in(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_one._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.public_project_user_two._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

    def test_get_projects_logged_in_as_different_user(self):
        url = "/v2/users/{}/nodes/".format(self.user_two._id)
        res = self.app.get(url, auth=self.auth_one)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_two._id, ids)
        assert_not_in(self.public_project_user_one._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

class TestUserUpdate(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social_accounts = {
            'github' : '',
            "scholar" : "",
            "personal" : 'http://mymom.com',
            "twitter" : "billyhunt",
            "linkedIn" : "",
            "impactStory": "",
            "orcid": "",
            "researcherId": ""
        }

        self.user_one.fullname = 'Martin Luther Kung Jr.'
        self.user_one.given_name = 'Martin'
        self.user_one.family_name = 'King'
        self.user_one.suffix = 'Jr.'
        self.user_one.employment_institutions = [
            {
                'startYear': '1995',
                'title': '',
                'startMonth': 1,
                'endMonth': None,
                'endYear': None,
                'ongoing': False,
                'department': '',
                'institution': 'Waffle House'
            }
        ]
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.social['twitter'] = 'ihaveadream'
        self.user_two.fullname = 'el-Hajj Malik el-Shabazz'
        self.user_two.given_name = 'Malcolm'
        self.user_two.family_name = 'X'
        self.user_two.suffix = ''
        self.user_two.employment_institutions = [
            {
                'startYear': '1982',
                'title': '',
                'startMonth': 1,
                'endMonth': None,
                'endYear': None,
                'ongoing': False,
                'department': '',
                'institution': 'IHop'
            }
        ]

        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')
        self.twitter = 'hotcrossbuns'
        self.new_social_accounts =  {
            'github': '',
            'scholar': '',
            'personal': 'http://mymom.com',
            'twitter': 'billyhunt',
            'linkedIn': '',
            'impactStory': '',
            'orcid': '',
            'researcherId': ''
        }

        self.new_name = 'Flash Gordon'
        self.public_project_user_one = ProjectFactory(title="Public Project User One", is_public=True, creator=self.user_one)
        self.private_project_user_one = ProjectFactory(title="Private Project User One", is_public=False, creator=self.user_one)
        self.public_project_user_two = ProjectFactory(title="Public Project User Two", is_public=True, creator=self.user_two)
        self.private_project_user_two = ProjectFactory(title="Private Project User Two", is_public=False, creator=self.user_two)
        self.deleted_project_user_one = FolderFactory(title="Deleted Project User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.folder = FolderFactory()
        self.deleted_folder = FolderFactory(title="Deleted Folder User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.dashboard = DashboardFactory()
        self.user_one_url = "/v2/users/{}/".format(self.user_one._id)
        self.user_two_url = "/v2/users/{}/".format(self.user_two._id)

    def test_patch_user_logged_out(self):
        res = self.app.patch_json(self.user_one_url, {
            'fullname': self.new_name,
        }, expect_errors=True)
        # This is 403 instead of 401 because basic authentication is only for unit tests and, in order to keep from
        # presenting a basic authentication dialog box in the front end. We may change this as we understand CAS
        # a little better
        assert_equal(res.status_code, 403)

    def test_patch_user_logged_in(self):
        # Logged in User updates his own stuff
        res = self.app.patch_json(self.user_one_url, {
            'fullname': self.new_name
        }, auth=self.auth_one)
        assert_equal(res.status_code, 200)
        assert_equal(res.json['data']['fullname'], self.new_name)

    def test_put_user_logged_out(self):
        res = self.app.put_json(self.user_one_url, {
            'fullname': self.new_name,
            'social_accounts' : self.new_social_accounts,
        }, expect_errors=True)
        # This is 403 instead of 401 because basic authentication is only for unit tests and, in order to keep from
        # presenting a basic authentication dialog box in the front end. We may change this as we understand CAS
        # a little better
        assert_equal(res.status_code, 403)

    def test_put_user_logged_in(self):
        # Logged in User updates his own stuff
        res = self.app.put_json(self.user_one_url, {
            'fullname': self.new_name,
            'social_accounts' : self.new_social_accounts,
        }, auth=self.auth_one)
        assert_equal(res.status_code, 200)
        assert_equal(res.json['data']['fullname'], self.new_name)
        assert_equal(res.json['data']['social_accounts'], self.new_social_accounts)
<commit_msg>wrote new tests to test permissions<commit_after># -*- coding: utf-8 -*-
from nose.tools import *  # flake8: noqa

from framework.auth.core import Auth
from website.models import Node
from tests.base import ApiTestCase, fake
from rest_framework import generics, permissions as drf_permissions
from tests.factories import UserFactory, ProjectFactory, FolderFactory, DashboardFactory

class TestUsers(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.save()
        self.user_two = UserFactory.build()
        self.user_two.save()

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_returns_200(self):
        res = self.app.get('/v2/users/')
        assert_equal(res.status_code, 200)

    def test_find_user_in_users(self):
        url = "/v2/users/"

        res = self.app.get(url)
        user_son = res.json['data']

        ids = [each['id'] for each in user_son]
        assert_in(self.user_two._id, ids)

    def test_all_users_in_users(self):
        url = "/v2/users/"

        res = self.app.get(url)
        user_son = res.json['data']

        ids = [each['id'] for each in user_son]
        assert_in(self.user_one._id, ids)
        assert_in(self.user_two._id, ids)

    def test_find_multiple_in_users(self):
        url = "/v2/users/?filter[fullname]=fred"

        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_in(self.user_one._id, ids)
        assert_in(self.user_two._id, ids)

    def test_find_single_user_in_users(self):
        url = "/v2/users/?filter[fullname]=my"
        self.user_one.fullname = 'My Mom'
        self.user_one.save()
        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_in(self.user_one._id, ids)
        assert_not_in(self.user_two._id, ids)

    def test_find_no_user_in_users(self):
        url = "/v2/users/?filter[fullname]=NotMyMom"
        res = self.app.get(url)
        user_json = res.json['data']
        ids = [each['id'] for each in user_json]
        assert_not_in(self.user_one._id, ids)
        assert_not_in(self.user_two._id, ids)

class TestUserDetail(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social['twitter'] = 'howtopizza'
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_gets_200(self):
        url = "/v2/users/{}/".format(self.user_one._id)
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

    def test_get_correct_pk_user(self):
        url = "/v2/users/{}/".format(self.user_one._id)
        res = self.app.get(url)
        user_json = res.json['data']
        assert_equal(user_json['fullname'], self.user_one.fullname)
        assert_equal(user_json['social_accounts']['twitter'], 'howtopizza')

    def test_get_incorrect_pk_user_logged_in(self):
        url = "/v2/users/{}/".format(self.user_two._id)
        res = self.app.get(url)
        user_json = res.json['data']
        assert_not_equal(user_json['fullname'], self.user_one.fullname)

    def test_get_incorrect_pk_user_not_logged_in(self):
        url = "/v2/users/{}/".format(self.user_two._id)
        res = self.app.get(url, auth=self.auth_one)
        user_json = res.json['data']
        assert_not_equal(user_json['fullname'], self.user_one.fullname)
        assert_equal(user_json['fullname'], self.user_two.fullname)

class TestUserNodes(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social['twitter'] = 'howtopizza'
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')
        self.user_one_url = '/v2/users/{}/'.format(self.user_one._id)
        self.user_two_url = '/v2/users/{}/'.format(self.user_two._id)
        self.public_project_user_one = ProjectFactory(title="Public Project User One", is_public=True, creator=self.user_one)
        self.private_project_user_one = ProjectFactory(title="Private Project User One", is_public=False, creator=self.user_one)
        self.public_project_user_two = ProjectFactory(title="Public Project User Two", is_public=True, creator=self.user_two)
        self.private_project_user_two = ProjectFactory(title="Private Project User Two", is_public=False, creator=self.user_two)
        self.deleted_project_user_one = FolderFactory(title="Deleted Project User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.folder = FolderFactory()
        self.deleted_folder = FolderFactory(title="Deleted Folder User One", is_public=False, creator=self.user_one, is_deleted=True)
        self.dashboard = DashboardFactory()

    def tearDown(self):
        ApiTestCase.tearDown(self)
        Node.remove()

    def test_authorized_in_gets_200(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url, auth=self.auth_one)
        assert_equal(res.status_code, 200)

    def test_anonymous_gets_200(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

    def test_get_projects_logged_in(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url, auth=self.auth_one)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_one._id, ids)
        assert_in(self.private_project_user_one._id, ids)
        assert_not_in(self.public_project_user_two._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

    def test_get_projects_not_logged_in(self):
        url = "/v2/users/{}/nodes/".format(self.user_one._id)
        res = self.app.get(url)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_one._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.public_project_user_two._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

    def test_get_projects_logged_in_as_different_user(self):
        url = "/v2/users/{}/nodes/".format(self.user_two._id)
        res = self.app.get(url, auth=self.auth_one)
        node_json = res.json['data']

        ids = [each['id'] for each in node_json]
        assert_in(self.public_project_user_two._id, ids)
        assert_not_in(self.public_project_user_one._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.deleted_project_user_one._id, ids)

class TestUserUpdate(ApiTestCase):

    def setUp(self):
        ApiTestCase.setUp(self)
        self.user_one = UserFactory.build()
        self.user_one.set_password('justapoorboy')
        self.user_one.social_accounts = {
            'github': '',
            "scholar": "",
            "personal": 'http://mymom.com',
            "twitter": "billyhunt",
            "linkedIn": "",
            "impactStory": "",
            "orcid": "",
            "researcherId": ""
        }

        self.user_one.fullname = 'Martin Luther Kung Jr.'
        self.user_one.given_name = 'Martin'
        self.user_one.family_name = 'King'
        self.user_one.suffix = 'Jr.'
        self.user_one.employment_institutions = [
            {
                'startYear': '1995',
                'title': '',
                'startMonth': 1,
                'endMonth': None,
                'endYear': None,
                'ongoing': False,
                'department': '',
                'institution': 'Waffle House'
            }
        ]
        self.user_one.save()
        self.auth_one = (self.user_one.username, 'justapoorboy')
        self.user_two = UserFactory.build()
        self.user_two.set_password('justapoorboy')
        self.user_two.social['twitter'] = 'ihaveadream'
        self.user_two.fullname = 'el-Hajj Malik el-Shabazz'
        self.user_two.given_name = 'Malcolm'
        self.user_two.family_name = 'X'
        self.user_two.suffix = ''
        self.user_two.employment_institutions = [
            {
                'startYear': '1982',
                'title': '',
                'startMonth': 1,
                'endMonth': None,
                'endYear': None,
                'ongoing': False,
                'department': '',
                'institution': 'IHop'
            }
        ]

        self.user_two.save()
        self.auth_two = (self.user_two.username, 'justapoorboy')
        self.twitter = 'hotcrossbuns'
        self.new_social_accounts = {
            'github': '',
            'scholar': '',
            'personal': 'http://mymom.com',
            'twitter': 'billyhunt',
            'linkedIn': '',
            'impactStory': '',
            'orcid': '',
            'researcherId': ''
        }

        self.new_name = 'Flash Gordon'
        self.user_one_url = "/v2/users/{}/".format(self.user_one._id)
        self.user_two_url = "/v2/users/{}/".format(self.user_two._id)

    def test_patch_user_logged_out(self):
        res = self.app.patch_json(self.user_one_url, {
            'fullname': self.new_name,
        }, expect_errors=True)
        # This is 403 instead of 401 because basic authentication is only for unit tests and, in order to keep from
        # presenting a basic authentication dialog box in the front end. We may change this as we understand CAS
        # a little better
        assert_equal(res.status_code, 403)

    def test_patch_user_logged_in(self):
        # Logged in user updates their user information via patch
        res = self.app.patch_json(self.user_one_url, {
            'fullname': self.new_name
        }, auth=self.auth_one)
        assert_equal(res.status_code, 200)
        assert_equal(res.json['data']['fullname'], self.new_name)

    def test_put_user_logged_out(self):
        res = self.app.put_json(self.user_one_url, {
            'fullname': self.new_name,
            'social_accounts': self.new_social_accounts,
        }, expect_errors=True)
        # This is 403 instead of 401 because basic authentication is only for unit tests and, in order to keep from
        # presenting a basic authentication dialog box in the front end. We may change this as we understand CAS
        # a little better
        assert_equal(res.status_code, 403)

    def test_put_wrong_user_auth(self):
        # User tries to update someone else's user information via put
        res = self.app.put_json(self.user_one_url, {
            'fullname': self.new_name,
            'social_accounts': self.new_social_accounts,
        }, auth=self.auth_two)
        assert_not_equal(res.status_code, 200)
        assert_not_equal(res.json['data']['fullname'], self.new_name)
        assert_not_equal(res.json['data']['social_accounts'], self.new_social_accounts)

    def test_patch_wrong_user_auth(self):
        # User tries to update someone else's user information via patch
        res = self.app.patch_json(self.user_one_url, {
            'fullname': self.new_name,
            'social_accounts': self.new_social_accounts,
        }, auth=self.auth_two)
        assert_not_equal(res.status_code, 200)
        assert_not_equal(res.json['data']['fullname'], self.new_name)
        assert_not_equal(res.json['data']['social_accounts'], self.new_social_accounts)
<|endoftext|>