Example #1
0
 def request_tokens(self):
     ''' Method to request API tokens from ecobee '''
     url = 'https://api.ecobee.com/token'
     params = {
         'grant_type': 'ecobeePin',
         'code': self.authorization_code,
         'client_id': self.api_key
     }
     try:
         request = requests.post(url, params=params)
     except RequestException:
         logger.warn(
             "Error connecting to Ecobee.  Possible connectivity outage."
             "Could not request token.")
         return
     if request.status_code == requests.codes.ok:
         self.access_token = request.json()['access_token']
         self.refresh_token = request.json()['refresh_token']
         self.write_tokens_to_file()
         self.pin = None
     else:
         logger.warn('Error while requesting tokens from ecobee.com.'
                     ' Status code: ' + str(request.status_code) + '\n' +
                     'request: ' + json.dumps(request.json(), indent=4) +
                     '\n' + 'params: ' + json.dumps(params, indent=4))
         return
Example #2
0
def api(isbn):
    request = requests.get("https://www.goodreads.com/book/review_counts.json",
                           params={
                               "key": "hVKf909VqkHtK6iHy3Mbw",
                               "isbns": isbn
                           })
    result_query = db.execute("SELECT * FROM books WHERE isbn=:isbn", {
        "isbn": isbn
    }).fetchall()
    average_rating = request.json()['books'][0]['average_rating']
    work_ratings_count = request.json()['books'][0]['work_ratings_count']
    api_query = db.execute("SELECT * FROM books WHERE isbn=:isbn", {
        "isbn": isbn
    }).fetchone()
    if api_query == None:
        return 'Error oooooo'  #render_template("error.html")
    data = {
        "title": api_query.title,
        "author": api_query.author,
        "year": api_query.year,
        "isbn": api_query.isbn,
        "review_count": work_ratings_count,
        "average_score": average_rating
    }
    dump = json.dumps(data)
    return render_template("api.html", api=dump)
Example #3
0
def locations():

    if request.method == 'GET':
        location_lst = HousingLocation.query.all()
        result = locations_schema.dump(location_lst)
        return jsonify(result), 200

    else:
        if request.is_json():
            latitude = float(request.json('latitude'))
            longitude = float(request.json('longitude'))
            housing_type_id = int(request.json('housing_type_id'))
            beds_available = int(request.json('beds_available'))

            location = HousingLocation(latitude=latitude,
                                       longitude=longitude,
                                       housing_type_id=housing_type_id,
                                       beds_available=beds_available)
            db.session.add(location)
            db.session.commit()

            result = location_schema.dump(location)
            return jsonify(result), 201
        else:
            return jsonify(message='request not valid json'), 500
Example #4
0
def location(location_id):

    location = HousingLocation.query.filter_by(location_id=location_id).first()
    if not location:
        return 404

    if request.method == 'GET':
        result = location_schema.dump(location)
        return jsonify(result)

    elif request.method == 'PUT':
        if request.is_json():
            location.latitude = float(request.json('latitude'))
            location.longitude = float(request.json('longitude'))
            location.housing_type_id = int(request.json('housing_type_id'))
            location.beds_available = int(request.json('beds_available'))

            db.session.commit()
            result = location_schema.dump(location)
            return jsonify(result), 202
        else:
            return 500

    else:
        pass
Example #5
0
def test_travis_like():
    request = requests.post(
        'https://api.' + app.config['APP_DOMAIN'] + '/v0.2/tty',
        verify=False,
        auth=('key', app.config['API_KEY']),
        json={
            "username": "******" + app.config['APP_DOMAIN'],
            "repo":
            "https://*****:*****@github.com/it-dojo/user.sample.test.git",
            "action": "init",
        },
    )

    if request.ok:
        app.logger.debug(request.json())
        data = request.json()
        app.logger.debug(data['tty']['uri'])

        response = requests.get('http://' + data['tty']['uri'])
        counter = 0
        while not response.status_code == requests.codes.ok:
            time.sleep(1)
            counter += 1
            app.logger.debug("Waiting %ss for %s ...", counter,
                             data['tty']['uri'])
            response = requests.get('http://' + data['tty']['uri'])

    return render_template("test-travis-like.html",
                           title="Test Travis Like Interface",
                           uri=data['tty']['uri'],
                           instructions=data['tty']['readme'])
Example #6
0
def api_run_pipeline():
    """
    Invoke a servable.

    Returns:
        (str): Response from the servables
    """
    return jsonify({
        "error":
        "This function is now deprecated. Please update your dlhub_sdk."
    })
    servables = []
    if 'servables' in request.json():
        servables = request.json()['servables']

    resolved_servables = []
    for x in servables:
        servable_namespace = x.split('/')[0]
        servable_name = x.split('/')[1]
        resolved_servables.append(
            _resolve_namespace_model(cur, conn, servable_namespace,
                                     servable_name))

    output = _perform_invocation(resolved_servables, request, type='run')
    return output
Example #7
0
def api_v1_count():
    cursor = conn.cursor()
    if request.method == 'POST' and request.is_json and request.json().get(
            'key'):
        key = str(request.json().get('key'))
        imgid = str(request.json().get('imgid'))
    elif request.method == 'POST' and request.form.get('key'):
        key = str(request.form.get('key'))
        imgid = str(request.form.get('imgid'))
    elif request.method == 'GET' and request.args.get('key'):
        key = str(request.args.get('key'))
        imgid = str(request.args.get('imgid'))
    else:
        return abort(403)
    cursor.execute('SELECT userid FROM apikeys WHERE key = ?', [key])
    userid = cursor.fetchall()
    if userid:
        cursor.execute('SELECT count FROM counter WHERE id = ? AND userid = ?',
                       [imgid, userid[0][0]])
        count = cursor.fetchall()
        if count:
            return jsonify({
                'imgname': imgid,
                'count': count[0][0],
                'imgurl': URLROOT + 'img/' + imgid,
                'counturl': URLROOT + 'count/' + imgid
            })
        return abort(403)
    return abort(403)
Example #8
0
    def request_pin(self):
        ''' Method to request a PIN from ecobee for authorization '''
        url = 'https://api.ecobee.com/authorize'
        params = {
            'response_type': 'ecobeePin',
            'client_id': self.api_key,
            'scope': 'smartWrite'
        }
        try:
            request = requests.get(url, params=params)
        except RequestException:
            logger.warn(
                "Error connecting to Ecobee.  Possible connectivity outage."
                "Could not request pin.")
            return
        try:
            self.authorization_code = request.json()['code']
        except:
            logger.error('Error calling request_pin.\nRequest output:\n' +
                         json.dumps(request.json(), indent=4) +
                         '\nRequest params:\n' + json.dumps(params, indent=4) +
                         '\nRequest URL: ' + url)

        self.pin = request.json()['ecobeePin']
        logger.error(
            'Please authorize your ecobee developer app with PIN code ' +
            self.pin + '\nGoto https://www.ecobee.com/consumerportal'
            '/index.html, click\nMy Apps, Add application, Enter Pin'
            ' and click Authorize.\nAfter authorizing, call request_'
            'tokens() method.')
        # new:
        self.write_tokens_to_file()
Example #9
0
def connect_to_network():
   
   my_node = {
    'nodeIp': myNodeIp,
    'nodeName': myNodeName,
   }
     
   blockchain.nodes.add(myNodeIp)
   
   if firstnode != '':
       request = requests.post(f'http://{firstnode}/add_new_node', json = my_node)
       if request.status_code == 201:
           json = request.json()
           blockchain.nodes = set(json.get('nodeList'))       
           message = json.get('message')
           print(message)
           print(f' Received nodes: {blockchain.nodes}')
           
           if len(blockchain.nodes) > 0:
               for node in blockchain.nodes:
                   if node != myNodeIp and node != firstnode: #safe switch for double
                       request = requests.post(f'http://{node}/add_new_node', json = my_node)
                       if request.status_code == 201:
                           json = request.json()
                           #add recieved nodes from all nodes
                           newNodes = set(json.get('nodeList'))
                           blockchain.nodes = blockchain.nodes.union(newNodes) 
                           message = json.get('message')
                           print(message)
                           print(f' Received nodes: {blockchain.nodes}')
Example #10
0
def configure():
    # seems like this needs to be done in order to reference global vars inside of the flask server thread
    global keepWeeks
    global currencies
    global exchanges
    global interval
    global on_demand
    if flaskRequest.method == 'POST':
        #return the config settings TODO: error check so that the user doesn't have to submit everything at once. Also implement a form here.
        keepWeeks = flaskRequest.json("keepWeeks")
        exchanges = flaskRequest.json("exchanges")
        currencies = flaskRequest.json("currencies")
        interval = flaskRequest.json("interval")
        return {
            'updated settings?': 'yes',
            'keepWeeks': keepWeeks,
            'currencies': currencies,
            'exchanges': exchanges,
            'interval': interval
        }
    else:
        return {
            'updated settings?': 'no',
            'keepWeeks': keepWeeks,
            'currencies': currencies,
            'on demand exchanges': list(ex_objs.keys()),
            'cached exchanges': exchanges,
            'interval': interval
        }
Example #11
0
def api_queue():
	print request.json()['_id']
	db.queue.
	return jsonify({
	    'success': True,
	    'data': []
	})
Example #12
0
def update_topic(id):
    topic = Topic.query.get(id)

    topic.title = request.json("title")
    topic.description = request.json("description")

    db.session.commit()
    return topic_schema.jsonify(topic)
Example #13
0
def recommend_places():
    cost=request.json('cost')
    seating=request.json('seating')
    location=request.json('location')
    category=request.json('category')
    preference=request.json('preference')
    output=dummy_recommender(cost,seating,location,category,preference)
    return jsonify({"Places":output}),200 #a string ,not a list,map UI accordingly
Example #14
0
def update_picture(id):
    picture = Pictures.query.get(id)

    picture.ArticleID = request.json('ArticleID')
    picture.TagLine = request.json('TagLine')

    db.session.commit()
    return single_pschema.jsonify(picture)
Example #15
0
def get_userbought():
    current_user = auth_login_required()  # check token
    if type(current_user) is dict:
        return jsonify(current_user)
    page = request.json().get('page')
    num = request.json().get('num')
    msg = ulord_helper.ulord_userbought(current_user.wallet)

    return jsonify({'result': 1, 'msg': msg})
Example #16
0
def my_post():
    if "key" not in request.json() or  "value" not in request.json():
        abort(400)
    key = request.json.get("key")
    value = request.json.get("value")
    if key in date.keys():
        abort(409)
    date.update({key:value})
    return jsonify({"your_result":value,"time":datetime.datetime.now()})
Example #17
0
def recebe(troco):
    for trocos in troco:
        if trocos['notas'] == troco:
            trocos['notas'] = request.json().get('notas')
    for trocos in troco:
        if trocos['moedas'] == troco:
            trocos['moedas'] = request.json().get('moedas')

    return jsonify({'ERROR'}), 404
Example #18
0
def update_journalist(id):
    journal = Journalist.query.get(id)

    journal.FName = request.json('FName')
    journal.LName = request.json('LName')
    journal.Description = request.json('Description')
    # journal.Pictures = request.json('Pictures')

    db.session.commit()
    return single_jschema.jsonify(journal)
Example #19
0
def requisitar( page ):
    # this make the requisition from the backend 
    response = []
    __URL = 'http://localhost:3001/api/products?page='+ str(page)
    request = requests.get(url=__URL)
    pages = request.json()['pages']
    data = request.json()['docs']
    response.append(pages)
    response.append(data)
    return response
Example #20
0
def update_article(id):
    article = Articles.query.get(id)

    article.Writer = request.json('Writer')
    article.Heading = request.json('Heading')
    article.Subheading = request.json('Subheading')
    article.Body = request.json('Body')

    db.session.commit()
    return single_aschema.jsonify(article)
Example #21
0
def event_captains_api(event_id):
    if request.method == 'GET':
        captains = get_captains_from_db(event_id)
        return json.dumps([captain._asdict() for captain in captains])
    elif request.method == 'POST':
        return add_captains(request.json())
    elif request.method == 'DELETE':
        return delete_captains(request.json(), event_id)
    else:
        return utilities.NAVY_SEAL
Example #22
0
    def post(self):
        new_list ={
            'id':new_list[-1]['id']+1
            'name':request.()
            'divishion':request.json()
            'blood':request.json()



        }
Example #23
0
def api_v1_add():
    cursor = conn.cursor()
    if request.method == 'POST' and request.is_json and request.json().get(
            'key'):
        key = str(request.json().get('key'))
        url = request.json().get('url')
        startval = request.json().get('start')
    elif request.method == 'POST' and request.form.get('key'):
        key = str(request.form.get('key'))
        url = request.form.get('url')
        startval = request.form.get('start')
    elif request.method == 'GET' and request.args.get('key'):
        key = str(request.args.get('key'))
        url = request.args.get('url')
        startval = request.args.get('start')
    else:
        return abort(403)
    try:
        if url:
            url = str(url)
            if startval:
                startval = int(startval)
            else:
                startval = -2
        else:
            return abort(400)
    except:
        return abort(400)
    cursor.execute('SELECT userid FROM apikeys WHERE key = ?', [key])
    userid = cursor.fetchall()
    if userid:
        userid = userid[0][0]
        imgid = secrets.token_urlsafe(16)
        name = secrets.token_urlsafe(16)
        cursor.execute(
            'INSERT INTO counter (id, name, userid, count, last, lastinfo, url) VALUES(?,?,?,?,?,?,?)',
            [
                imgid, name, userid, startval,
                str(
                    datetime.datetime.fromtimestamp(
                        time.time()).strftime(r'%Y-%m-%d %H:%M:%S')),
                str(request.headers), url
            ])
        conn.commit()
        return jsonify({
            'userid': userid,
            'imgid': imgid,
            'imgname': name,
            'imgurl': URLROOT + 'img/' + imgid,
            'endpoint': url,
            'counturl': URLROOT + 'count/' + imgid
        })
    else:
        return abort(403)
    return abort(500)
Example #24
0
def send_message(chatId, text='Please wait a few seconds...!'):
    url = URL + 'sendMessage'
    answer = {'chat_id': chatId, 'text': text}
    print(answer)
    #r=requests.get(url,json=answer)
    #print(r.json())

    request = requests.post(url, data=answer)

    print(request.json())
    return request.json()
Example #25
0
def create_contact():
    logger.debug(
        "Creating a contact record:  FirstName: {}. LastName: {}. Phone {}. Group Id {}"
        .format(request.json["firstName"], request.json["lastName"],
                request.json["phone"], request.json("groupId")))

    contactId = contactDB.create(request.json["firstName"],
                                 request.json["lastName"],
                                 request.json["phone"],
                                 request.json("groupId"))
    return jsonify({'contactId': contactId}), 201
Example #26
0
def chpass(user_id):
    current = request.json('current_password')
    new = request.json('new_password')
    repeat = request.json('repeat_password')
    user = User.fetch(user_id)
    if user is None:
        return jsonify({'error': 'user not found'})
    elif new == repeat:
        return jsonify({'data': User().chpass(id, new)})
    elif new != repeat:
        return jsonify({'error': 'password confirmation failed.'})
Example #27
0
def move():
    if not request.json():
        return jsonify(err="can only send json")

    json = request.json()
    x = json["x"]
    y = json["y"]

    x = x + 1 if x < 1000 else 0
    y = y + 1 if y < 1000 else 0

    return jsonify(x=x, y=y)
Example #28
0
 def post(self):
     db_name = request.json('db')
     collection = request.json('collection')
     cols = request.json('cols')
     version = request.json('version')
     new_version = version + 1
     connection = get_connection(username, password, db_name, host, port)
     input_df = read_mongo(db_name, collection)
     input_df.drop_duplicates(subset=cols, inplace=True)
     input_df[version] = new_version
     save_data(connection, db_name, collection, input_df)
     return jsonify({"message": "success"})
Example #29
0
def departments():
    request = requests.get(api_url + 'departments')
    depts = request.json()
    request = requests.get(api_url + 'employees/heads')
    heads = request.json()

    for dept in depts:
        head = next((item for item in heads if item["id"] == dept['head_id']),
                    None)
        dept['head'] = ('unassigned' if head is None else '{} {}'.format(
            head["first_name"], head["last_name"]))
    return render_template('departments.html', depts=depts)
def get_paths():
    try:
        request = session.get('http://localhost:9999')
        request.raise_for_status()
        path = request.json()['_directory']
        tar = request.json()['_tar']
        if path is None or not os.path.isdir(path):
            raise ValueError()
        if tar is None or not os.path.isfile(tar):
            raise ValueError()
    except Exception:
        raise ServiceUnavailable("No update ready")
    return path, tar
Example #31
0
def department(name):
    request = requests.get(api_url + 'departments/' + name)
    dept = request.json()
    request = requests.get(api_url + 'employees/?department=' + dept['name'])
    employees = request.json()

    head = next(
        (person for person in employees if person["id"] == dept['head_id']),
        None)

    if head is not None:
        form = DepartmentForm(dept_name=dept['name'],
                              head_salary=head['salary'])
    else:
        form = DepartmentForm(dept_name=dept['name'])

    dept['head'] = 'unassigned' if head is None \
        else (format_emplyee(head['id'],
                             head["first_name"], head["last_name"])
              )
    candidates_list = [(person['id'],
                        format_emplyee(person['id'], person['first_name'],
                                       person['last_name']))
                       for person in employees]
    candidates_list.insert(0, (-1, 'Unassigned'))

    if head is not None:  # making current head the first (default) option
        current_head = (head['id'],
                        format_emplyee(head['id'], head['first_name'],
                                       head['last_name']))
        candidates_list.remove(current_head)
        candidates_list.insert(0, current_head)

    form.dept_head.choices = candidates_list
    if form.validate_on_submit():
        args_string = 'departments/{}?name={}'.format(name,
                                                      form.dept_name.data)
        args_string += '&head_id={}'.format(form.dept_head.data)

        if form.head_salary.data is not None:
            args_string += '&head_salary={}'.format(form.head_salary.data)

        api_request = requests.put(api_url + args_string)
        print(api_request.status_code)
        return redirect(url_for('department', name=form.dept_name.data))

    dept['head_salary'] = None if head is None else head['salary']
    return render_template('department.html',
                           dept=dept,
                           employees=employees,
                           form=form)
Example #32
0
def set_location():
	if request.method == 'POST':
		log_google_debug("Received a POST response on the location page")
		try:
			user_lat = request.json('lat')
			user_long = request.json('long')
			log_google_debug("Found coordinates: "+user_lat+", "+user_long)
			session['located'] = True
			session['lat'] = user_lat
			session['long'] = user_long
			log_google_debug("Added geolocation data to user cookie")
		except:
			log_google_error("Something went wrong reading coordinates from the POST request, nothing added to user cookie")
	return redirect(url_for('index')) 
Example #33
0
def send_with_mandrill(data):
    """ Sends mail with data using mandrill
        Returns True if sent successfully, False otherwise
        On error, switches the configuration to Mailgun """
    app.logger.debug("Email sent with Mandrill")
    payload = {"key": app.config['MANDRILL_KEY'],
               "message": {"text": data["body"], "subject": data["subject"],
                           "from_email": data["from"],
                           "from_name": data["from_name"],
                           "to": [{"email": data["to"],
                                   "name": data["to_name"],
                                   "type": "to"}]
                           }
               }
    request = requests.post(app.config['MANDRILL_URL'],
                            data=json.dumps(payload))
    response = request.json()
    try:
        if response[0]['status'] == "sent":
            return True
        else:
            app.logger.warning("Mandrill Send Failed: " +
                               response[0]['reject_reason'])
    except:
        app.logger.error("Mandrill Error: " + str(response))
        # switch to mailgun
        app.logger.debug("Switch default to Mailgun")
        app.config['DEFAULT_MAIL_SERVICE'] = "mailgun"
    return False
Example #34
0
def process_hook():
    url = PIVOTAL_URL
    try:
        payload_json = request.json()
        commits = payload_json.get('commits')
        if commits:
            api_token = get_api_token(commits[0].get('author').get('email'))

        for commit in commits:
            xml_data = form_xml_post_data(commit)
            req = requests.post(url, data=xml_data,
                headers={
                    'X-TrackerToken': api_token,
                    'Content-type': 'application/xml',
                }
            )
            if not req:
                logging.debug(
                    u"Commiting ticket to pivotal resulted in an error."
                    " %s url with data %s and api_token %s",
                    url, xml_data, api_token
                )
    except Exception:
        logging.exception("Exception when attempting to process payload")
        return "Your hook made trouble so nothing done."
    else:
        return "Thank your for your hook"
Example #35
0
 def request_pin(self):
     logger.info(f'Attempting to request pin for {self.api_key}')
     url = f'{ecobee_url}authorize'
     params = {
         'response_type': 'ecobeePin',
         'client_id': self.api_key,
         'scope': 'smartWrite'
     }
     try:
         request = requests.get(url, params=params)
     except RequestException:
         logger.warn(f'Pin request for {self.api_key} unsuccessful')
     else:
         if request.status_code == requests.codes.ok:
             logger.info(f'Pin request for {self.api_key} successful')
             self.authorization_code = request.json()['code']
             self.pin = request.json()['ecobeePin']
         else:
             return False
Example #36
0
        def inner(*args, **kwargs):
            if request.method == "GET":
                formdata = request.args
            else:
                formdata = request.form if request.form else MultiDict(request.json(force=True))

            form = form_class(formdata)
            if not form.validate():
                return api_error(10013)
            g.form = form
Example #37
0
 def request_tokens(self):
     logger.info(f'Attempting to request tokens for {self.api_key}')
     url = f'{ecobee_url}token'
     params = {'grant_type': 'ecobeePin',
               'code': self.authorization_code,
               'client_id': self.api_key}
     try:
         request = requests.post(url, params=params)
     except RequestException:
         return
     else:
         if request.status_code == requests.codes.ok:
             logger.info(f'Tokens request for {self.api_key} successful')
             self.access_token = request.json()['access_token']
             self.refresh_token = request.json()['refresh_token']
             self.write_to_db()
             self.pin = None
         else:
             logger.info(f'Tokens request for {self.api_key} unsuccessful')
             return
Example #38
0
def event_notification():
    try:
        request_params = request.json()
        command = request_params.get('command')
        data = request_params.get('data')
        template_id = request_params.get('template_id')
        from ..services import event_task_listener
        task = event_task_listener(command, template_id, data)
        return jsonify(dict(status='success', message='Successfully submitted the request', task=str(task.id)))
    except Exception, e:
        return jsonify(dict(status='error', message=str(e)))
Example #39
0
def request_access_token(code):
  params = {
    'grant_type': 'authorization_code',
    'client_id': READMILL_CLIENT_ID,
    'client_secret': READMILL_CLIENT_SECRET,
    'redirect_uri': url_for_auth_callback(),
    'code': code
  }
  request = requests.post(READMILL_ACCESS_TOKEN_URL, params=params)

  return request.json()
Example #40
0
def create_patient():
    if not request.json or not 'gender' in request.json:
        abort(400)
    patient = {
        'id': patients[-1]['id'] + 1,
        'gender': request.json['gender'],
        'age': request.json('age'),
        'height': request.json['height'],
        'weight': request.json['weight']
    }
    patients.append(patient)
    return jsonify( { 'patient': make_public_patient(patient) } ), 201
def get_results(params):
  ##Obtain these from Yelp's manage access page (adding this to test heroku)
  session = rauth.OAuth1Session(
    consumer_key = os.environ['yelp_consumer_key']
    ,consumer_secret = os.environ['yelp_consumer_secret']
    ,access_token = os.environ['yelp_token']
    ,access_token_secret = os.environ['yelp_token_secret'])
     
  request = session.get("http://api.yelp.com/v2/search",params=params)
   
  #Transforms the JSON API response into a Python dictionary
  return request.json()
def get_yelp_results(businessID):
    # Session setup
    session = rauth.OAuth1Session(
        consumer_key = yelp_consumer_key, 
        consumer_secret = yelp_consumer_secret, 
        access_token = yelp_token, 
        access_token_secret = yelp_token_secret)

    request = session.get('http://api.yelp.com/v2/search/' + businessID)

    # Transform JSON API response into Python dictionary
    data = request.json()
    session.close()

    return data
Example #43
0
def writeMe():
	if request.method == 'GET':
		user = request.args.get('chat_name')
		message = request.args.get('content')
	else:
		if request.json:
			user = request.json('chat_name')
			message = request.json('content')
		else:
			user = request.form['chat_name']
			message = request.form['content']

	app.logger.error(request)
	if user is None:
		user = "******"
	
	if message is None:
		message = ""

	chat = ChatLog(parent=chatlog_key(DEFAULT_CHAT_NAME))
	chat.author = user
	chat.content = message
	chat.put()
	return make_response("", 200)
Example #44
0
    def exit_chat(identifier):
        conn = sqlite3.connect(FROLIC_DB)
        c = conn.cursor()
        c.execute("SELECT chat FROM chats WHERE identifier=?", [identifier])
        chat = c.fetchone()
        chat = jsonpickle.decode(chat)

        body = request.json()
        token = body['token']

        member = dict(chat['members'])[token]
        chat['members'].remove(member)
        c.execute("UPDATE chats SET chat = ? where identifier = ?", [identifier, jsonpickle.encode(chat)])
        conn.commit()
        conn.close()
        return jsonify({})
def check_recaptcha(response, ip):
    # Prepare the recaptcha verification_data
    verification_data = {
        "secret": app.config.get("RECAPTCHA_SECRET_KEY"),
        "response": response,
        "remoteip": ip
    }
    # Make the request
    request = requests.get(
        app.config.get("RECAPTCHA_VERIFY_URL"),
        params = verification_data
    )
    # Check the request results
    if request.json()["success"]:
        return True
    else:
        return False
Example #46
0
def create_plant_logs(plant_id):
    if not request.json or not 'log_body' in request.json:
        abort(400)

        log_body = request.json('log_body')
        time_of_log = datetime.now()
        parent_plant = plant_id
        log_type = "Testing"

        #Put all of the submitted data into our Log model and assign it the variable log.
        log = Log(time_of_log, log_body, log_type, parent_plant)

        #Add the log to the current database session for submission.
        #Then commit the session data to the database.
        db.session.add(log)
        db.session.commit()

        return "Success.  You logged '%s' to plant ID#%s" % log_body,
Example #47
0
    def post(self):
        input = request.json()
        terminal_no = input.get('terminal_no', '').strip()
        if not terminal_no:
            return jsonify(success=False, msg=u'设置默认终端失败:无效的终端号')

        q = db_session.query(TerminalInfo) \
            .filter(TerminalInfo.terminal_no==terminal_no) \
            .filter(TerminalInfo.shop_no.in_(db_session.query(ShopInfo).filter(ShopInfo.unit_no==session['unit_no'])))

        if q.count():
            if q.one().status == '0':
                session['default_terminal'] == terminal_no
                return jsonify(success=True, msg=u'设置终端号成功', show_msg=True)
            else:
                return jsonify(success=False, msg=u'设置默认终端失败:此终端不可用', show_msg=True)
        else:
            return jsonify(success=False, msg=u'设置默认终端失败:无此终端', show_msg=True)
Example #48
0
def do_request(params):
  #Obtain these from Yelp's manage access page
  consumer_key = "3J0vOb8Pkm0ZVj6RNT6SgQ"
  consumer_secret = "9PCim5pcmDmHAUFtqPQlFwfitRg"
  token = "WqA1ClKuVKCjalKpcD_93c0vXRWEBxD7"
  token_secret = "c7PZFWyW173hCwGj28u0KhaXoH0"
  print params 
  session = rauth.OAuth1Session(
    consumer_key = consumer_key
    ,consumer_secret = consumer_secret
    ,access_token = token
    ,access_token_secret = token_secret)
     
  request = session.get("http://api.yelp.com/v2/search",params=params)

   
  #Transforms the JSON API response into a Python dictionary
  data = request.json()
  session.close()
   
  return data    
Example #49
0
File: app.py Project: amjd/GenMed
	def med_details(self, search_term):
		"""
		GET /medicine_details
		Parameters:
		id = SEARCH_STRING, key = API_KEY
		"""
		url = self.ENDPOINT + 'medicine_details/'
		self.__params(search_term)
		medicine_details = {}
		try:
			request = requests.get(url, params=self.params)
			result = request.json()
			if result['status'] == 'ok' or result['status'] == 200:
				medicine_details = result['response']
				error_code = 0
				error_msg = "Success"
		except:
			error_code = 1
			error_msg = "Sorry, we are experiencing some connection issues right now. Please try again later."
		
		return medicine_details, error_code, error_msg
Example #50
0
File: app.py Project: amjd/GenMed
	def med_suggestions(self, search_term, limit = 8):
		"""
		GET /medicine_suggestions
		Parameters:
		id = SEARCH_STRING, key = API_KEY, limit = LIMIT
		"""
		url = self.ENDPOINT + 'medicine_suggestions/'
		self.__params(search_term, limit)
		suggestions_list = []
		try:
			request = requests.get(url, params=self.params)
			result = request.json()
			if result['status'] == 'ok' or result['status'] == 200:
				error_code = 0
				error_msg = "Success"
				temp_list = result['response']['suggestions']
				suggestions_list = [item['suggestion'] for item in temp_list]

		except:
			error_code = 1
			error_msg = "Sorry, we are experiencing some connection issues right now. Please try again later."
		return suggestions_list, error_code, error_msg
Example #51
0
File: app.py Project: amjd/GenMed
	def med_alternatives(self, search_term, limit = 5):
		"""
		GET /medicine_alternatives
		Parameters:
		id = SEARCH_STRING, key = API_KEY, limit = LIMIT
		"""
		url = self.ENDPOINT + 'medicine_alternatives/'
		self.__params(search_term, limit)
		alternatives_list = []
		try:
			request = requests.get(url, params=self.params)
			result = request.json()
			if result['status'] == 'ok' or result['status'] == 200:
				temp_list = result['response']['medicine_alternatives']
				alternatives_list = [{'brand': item['brand'], 'unit_price' : item['unit_price']} for item in temp_list]
				error_code = 0
				error_msg = "Success"
		except:
			error_code = 1
			error_msg = "Sorry, we are experiencing some connection issues right now. Please try again later."

		return alternatives_list, error_code, error_msg
Example #52
0
def send_with_mailgun(data):
    """ Sends mail with data using mailgun
        Returns True if sent successfully, False otherwise
        On error, switches the configuration to Mandrill """
    app.logger.debug("Email sent with Mailgun")
    payload = {"from": data["from_name"] + "<" + data["from"] + ">",
               "to": data["to_name"] + "<" + data["to"] + ">",
               "subject": data["subject"], "text": data["body"]}
    request = requests.post(
        app.config['MAILGUN_URL'],
        auth=("api", app.config['MAILGUN_KEY']),
        data=payload
    )
    response = request.json()
    try:
        if response['message'] == "Queued. Thank you.":
            return True
    except:
        app.logger.error("Mailgun Error: " + str(response))
        # switch to mandrill
        app.logger.debug("Switch default to Mandrill")
        app.config['DEFAULT_MAIL_SERVICE'] = "mandrill"
    return False
Example #53
0
    def msg_chat(identifier):
        conn = sqlite3.connect(FROLIC_DB)
        c = conn.cursor()
        c.execute("SELECT chat FROM chats WHERE identifier=?", [identifier])
        chat = c.fetchone()
        chat = jsonpickle.decode(chat)

        body = request.json()
        token = body['token']
        msg = body['msg']
        member = chat['members'][token]
        chat['messages'] = deque(chat['messages'])
        chat['messages'].append((member, msg))
        if len(chat['messages']) > 20:
            chat['messages'].popleft()
        response = {'token': token,
                    'members': chat['members'],
                    'messages': list(chat['messages'])
        }
        c.execute("UPDATE chats SET chat = ? where identifier = ?", [identifier, jsonpickle.encode(chat)])
        conn.commit()
        conn.close()
        return jsonify(response)
Example #54
0
def get_root():
    url = api + reportEndpoint
    request = requests.get(url)
    return render_template('map.html', reports=request.json(), api_key=api_key)
Example #55
0
def get_server_info(server_name):
    params = {"servername": str(server_name)}
    url_to_send = "{address}/get_server_info".format(address=handyrep_address)
    request= requests.get(url_to_send,params=params, auth=(username,password))
    return request.json()
def get_speed():
    result = {'command': 'get_speed', 'return_values':request.json()}
    print(result, file=sys.stderr)
    return jsonify(result)
Example #57
0
def what_itis():
    print(request.json())
    loadedJson = json.loads(request.text)
    return loadedJson
Example #58
0
 def request_return(request):
     j = request.json()
     j[u'status'] = request.status_code
     return j
Example #59
0
def get_php():
    try:
        request = requests.get(config['env']['phpinfo'], params={'format': 'json'})
        return request.json()
    except requests.exceptions.RequestException:
        return {'version': '<span class="text-danger">Cannot fetch, is Apache and Php containers running?</span>'}
Example #60
0
 def object(self):
     if isinstance(request.json, dict):
         return request.json
     else:
         return request.json()