コード例 #1
0
def change_status(id, status):
    if not user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'You are not authenticated'
                               }))
    if status == 'open' or status == 'close':
        if Bounties.exist(id):
            Bounties.set_status(status, id)
            return render_template('ajax.html',
                                   info=jsonify({
                                       'error':
                                       'n',
                                       'msg':
                                       "Bounty #%s is now %s" % (id, status)
                                   }))
        else:
            return render_template('ajax.html',
                                   info=jsonify({
                                       'error':
                                       'y',
                                       'msg':
                                       "Bounty #%s doesn't exist" % id
                                   }))
    else:
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': "Invalid status"
                               }))
コード例 #2
0
def get_topics(category):
    result = {
        'error': '',
        'results': [],
    }
    category_exists = g.db.execute('select * from categories where slug = ?',
                                   (category, )).fetchone() is not None
    if not category_exists:
        result['error'] = 'category not found'
        return json.jsonify(result)
    cur = g.db.execute(
        '''
        select
            topics.slug,
            topics.topic,
            topics.category,
            categories.category
        from topics
            join categories on topics.category = categories.slug
        where topics.category = ?''', (category, ))
    for row in cur:
        result['results'].append({
            'slug': row[0],
            'topic': row[1],
            'category_slug': row[2],
            'category': row[3],
        })
    return json.jsonify(result)
コード例 #3
0
def show_bounty(table, id):
    if not user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'You are not authenticated'
                               }))
    if table == 'bounties':
        data = Bounties.get_by_id(id)
    elif table == 'targets':
        data = Targets.get_by_id(id)
    else:
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'Invalid table'
                               }))
    if data:
        data = data[0]
        info = {}
        for k, d in zip(data.keys(), data):
            info[k] = d
        return render_template('ajax.html', info=jsonify(info))
    else:
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'Invalid Bounty #%s' % id
                               }))
コード例 #4
0
def login():
    if user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': 'Already logged'
                               }))
    if request.form['username'] != '' and request.form['password'] != '':
        if Users.check_login(request.form['username'],
                             request.form['password']):
            session['auth'] = request.form['username']
            return render_template('ajax.html',
                                   info=jsonify({
                                       'error': 'n',
                                       'msg': 'Login OK'
                                   }))
        else:
            return render_template('ajax.html',
                                   info=jsonify({
                                       'error':
                                       'y',
                                       'msg':
                                       'Invalid username/password'
                                   }))
    else:
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': 'Invalid form'
                               }))
コード例 #5
0
ファイル: urban.py プロジェクト: CHCMATT/Code
def urban(code, input):
    # clean and split the input
    try:
        if input.group(2):
            msg = input.group(2).lower().strip()
            tmp = msg.replace("-", "").split()
            if tmp[-1].isdigit():
                if int(tmp[-1]) <= 0:
                    id = 0
                else:
                    id = int(tmp[-1].replace("-", "")) - 1
                del tmp[-1]
                msg = " ".join(tmp)
            else:
                id = 0
            data = jsonify(get(uri % quote(msg)).read())["list"]
            if not data:
                return code.reply(error)
            max = len(data)
            if id > max:
                id = max
                data = data[max - 1]
            else:
                data = data[id]
                id += 1
            msg = (
                '({purple}{id}{c} of {purple}{max}{c}) "{purple}{word}{c}": {definition} +{red}{up}{c}/-{red}{down}{c}'
            )
            if len(data["definition"]) > 235:
                data["definition"] = data["definition"][0:235] + "[...]"
            return code.say(
                code.format(msg).format(
                    id=str(id),
                    max=str(max),
                    definition=strp(data["definition"]),
                    word=data["word"],
                    up=str(data["thumbs_up"]),
                    down=str(data["thumbs_down"]),
                )
            )
            # Begin trying to get the definition
        else:
            # Get a random definition...
            data = jsonify(get(random_uri).read())["list"][0]
            if not data:
                return code.reply(error)
            msg = '(Definition for "{purple}{word}{c}"): {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data["definition"]) > 235:
                data["definition"] = data["definition"][0:235] + "[...]"
            return code.say(
                code.format(msg).format(
                    definition=strp(data["definition"]),
                    word=data["word"],
                    up=str(data["thumbs_up"]),
                    down=str(data["thumbs_down"]),
                )
            )
    except:
        return code.reply("{red}{b}Failed to pull definition from urbandictionary.com!")
コード例 #6
0
def get_topic(category, topic):
    result = {
        'error': '',
        'results': [],
    }
    topic_exists = g.db.execute(
        'select * from topics where slug = ? and category = ?',
        (topic, category)).fetchone() is not None
    if not topic_exists:
        result['error'] = 'topic not found'
        return json.jsonify(result)
    cur_topicexpertises = g.db.execute(
        '''
        select
            topicexpertise.*,
            topics.topic,
            categories.category
        from topicexpertise
            join topics on topics.id = topicexpertise.topic
            join categories on categories.slug = topics.category
        where topics.slug = ? and topics.category = ?''', (topic, category))
    for row in cur_topicexpertises:
        expertise = g.db.execute('select * from expertise where id = ?',
                                 (row[2], )).fetchone()
        expertise_result = {
            'expertise_id': row[2],
            'expertise': expertise[2],
            'content_warning': expertise[3],
            'expertise_topics': [],
            'topic_slug': topic,
            'topic': row[3],
            'category_slug': category,
            'category': row[4],
            'user': expertise[1],
        }
        topics = g.db.execute(
            '''
            select
                topicexpertise.id,
                topics.slug,
                topics.topic,
                categories.slug,
                categories.category
            from topicexpertise
                join topics on topics.id = topicexpertise.topic
                join categories on categories.slug = topics.category
            where topicexpertise.expertise = ?''', (row[2], ))
        for row in topics:
            topic_result = {
                'category_slug': row[3],
                'category': row[4],
                'topic_slug': row[1],
                'topic': row[2],
            }
            expertise_result['expertise_topics'].append(topic_result)
        result['results'].append(expertise_result)
    return json.jsonify(result)
コード例 #7
0
def show_settings():
    data = request.get_json(force=True)
    if not 'token' in data:
        return render_template(
            'json.html', jsonify({
                "result": False,
                "msg": "Missing parameter"
            }))
    settings = utils.get_user_settings(data['token'])
    return render_template('json.html', content=jsonify(settings))
コード例 #8
0
def user_register():
    user_info = request.get_json(force=True)
    if not 'username' in user_info or not 'password' in user_info or not 'email' in user_info:
        return render_template('json.html',
                               content=jsonify({
                                   "result": False,
                                   "msg": "Missing parameters"
                               }))
    return render_template('json.html',
                           content=jsonify(utils.register(user_info)))
コード例 #9
0
def urban(code, input):
    # clean and split the input
    try:
        if input.group(2):
            msg = input.group(2).lower().strip()
            tmp = msg.replace('-', '').split()
            if tmp[-1].isdigit():
                if int(tmp[-1]) <= 0:
                    id = 0
                else:
                    id = int(tmp[-1].replace('-', '')) - 1
                del tmp[-1]
                msg = ' '.join(tmp)
            else:
                id = 0
            data = jsonify(get(uri % quote(msg)).read())['list']
            if not data:
                return code.reply(error)
            max = len(data)
            if id > max:
                id = max
                data = data[max - 1]
            else:
                data = data[id]
                id += 1
            msg = '({purple}{id}{c} of {purple}{max}{c}) "{purple}{word}{c}": {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(
                code.format(msg).format(id=str(id),
                                        max=str(max),
                                        definition=strp(data['definition']),
                                        word=data['word'],
                                        up=str(data['thumbs_up']),
                                        down=str(data['thumbs_down'])))
            # Begin trying to get the definition
        else:
            # Get a random definition...
            data = jsonify(get(random_uri).read())['list'][0]
            if not data:
                return code.reply(error)
            msg = '(Definition for "{purple}{word}{c}"): {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(
                code.format(msg).format(definition=strp(data['definition']),
                                        word=data['word'],
                                        up=str(data['thumbs_up']),
                                        down=str(data['thumbs_down'])))
    except:
        return code.reply(
            '{red}{b}Failed to pull definition from urbandictionary.com!')
コード例 #10
0
def logout():
    if not user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': 'You are not authenticated'
                               }))
    session.pop('auth', None)
    return render_template('ajax.html',
                           info=jsonify({
                               'error': 'n',
                               'msg': 'Your are now deconnected'
                           }))
コード例 #11
0
ファイル: api.py プロジェクト: aqimon/aqimon_web
def addEvent():
    # API: Add events from a client
    # Parameters:
    #  - clientID: client id
    #  - temperature, humidity, dustLevel, coLevel: self-explanatory
    #  - apiKey: API key specific to that client
    # Returns:
    #  {"result": <result>}

    __paramsList__ = {
        "client_id": "str",
        "temperature": "float",
        "humidity": "float",
        "dustlevel": "float",
        "colevel": "float",
        "apikey": "str"
    }
    params = paramsParse(__paramsList__, request.args)
    if 'time' not in request.args:
        params['timestamp'] = utcNow()
    else:
        params['timestamp'] = fromTimestamp(request.args['time'])

    with database.atomic():
        try:
            client = Client.get(Client.id == params['client_id'])
        except DoesNotExist:
            return json.jsonify(result="no such client"), 404
        if client.api_key != params['apikey']:
            return json.jsonify(result="invalid api key"), 403
        del params['apikey']
        event = Event.create(**params)
        last_event, created = LastEvent.create_or_get(client_id=event.client_id, event_id=event.id)
        last_event.event_id = event.id
        last_event.save()

    broadcastEvent(event.toFrontendObject(include_geo=True), private=client.private)
    if overThreshold(client, event):
        if not client.last_notification:
            sendNotification(str(event.client_id.id), True)
            client.last_notification = True
            client.save()
    else:
        if client.last_notification:
            sendNotification(str(event.client_id.id), False)
            client.last_notification = False
            client.save()

    return json.jsonify(result="success")
コード例 #12
0
ファイル: oauth_client_edit.py プロジェクト: sgaweda/greenbot
    def handle_oauth2_response_discord(self, args):
        """Handles an oauth2 authorization response."""

        client = self.make_client()
        remote_args = {
            "client_id": self.consumer_key,
            "client_secret": self.consumer_secret,
            "code": args.get("code"),
            "redirect_uri": session.get("%s_oauthredir" % self.name),
            "scope": "identify",
        }
        log.debug("Prepare oauth2 remote args %r", remote_args)
        remote_args.update(self.access_token_params)
        headers = copy(self._access_token_headers)
        if self.access_token_method == "POST":
            headers.update(
                {"Content-Type": "application/x-www-form-urlencoded"})
            body = client.prepare_request_body(**remote_args)
            response = requests.request(
                self.access_token_method,
                self.expand_url(self.access_token_url),
                headers=headers,
                data=to_bytes(body, self.encoding),
            )
            if response.status_code not in (200, 201):
                raise OAuthException(
                    "Invalid response from %s" % self.name,
                    type="invalid_response",
                    data=to_bytes(body, self.encoding),
                )
            return jsonify(response.text.encode("utf8"))
        elif self.access_token_method == "GET":
            qs = client.prepare_request_body(**remote_args)
            url = self.expand_url(self.access_token_url)
            url += ("?" in url and "&" or "?") + qs
            response = requests.request(self.access_token_method,
                                        url,
                                        headers=headers)
            if response.status_code not in (200, 201):
                raise OAuthException(
                    "Invalid response from %s" % self.name,
                    type="invalid_response",
                    data=to_bytes(body, self.encoding),
                )
            return jsonify(response.text.encode("utf8"))
        else:
            raise OAuthException("Unsupported access_token_method: %s" %
                                 self.access_token_method)
コード例 #13
0
def generate_token(username, password):
    """Generate a secure token for the user"""
    data = {"username": username, "password": password}
    if not utils.login(data):
        return render_template('json.html', content=jsonify({"result": False}))
    token = utils.random_token()
    db = utils.get_db()
    while utils.row_exists(db, 'users', 'token', token):
        token = utils.random_token()
    utils.update('users', 'username = ? and password = ?', ['token'],
                 [token, username, password])
    return render_template('json.html',
                           content=jsonify({
                               "result": True,
                               "token": token
                           }))
コード例 #14
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def get_all_users():
    users = []
    for user in models.User.query.all():
        user_dict = row2dict(user)
        users.append(user_dict)

    return jsonify(users)
コード例 #15
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def authenticate_to_game(game_id):
    data = request.get_json(force=True)
    try:
        auth = authentication.Authentication()
        user_data = auth.user_from_identifier(data["authenticate"]["identifier"])
        users = models.User.query.filter_by(username=user_data["username"])

        if users.length > 0:
            # User is already registered
            user_id = users.first().id
        else:
            # User is not registered, register them
            register_user(user_data=user_data)
            user_id = models.User.query.filter_by(username=user_data["username"]).first().id

        game = models.Game.query.filter_by(id=game_id).first()
        score = models.Score(user_id=user_id, game_id=game.id)
        db.add(score)
        db.commit()

        response = return_success()
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #16
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def get_all_games():
    games = []
    for game in models.Game.query.all():
        game_dict = row2dict(game)
        games.append(game_dict)

    return jsonify(games)
コード例 #17
0
 def UpdateOrder(self):
     resp = self._api.UpdateOrder(
         token=self._token
     )
     resp = jsonify(resp.text)
     self._check_response(resp)
     return resp['data']
コード例 #18
0
def student_route(uname):
    if request.method == "POST":
        try:
            data = request.get_json(force=True)
            student = models.Student.query.filter_by(username=uname).first()
            for k in data:
                if k == "username":
                    student.username = data[k].lower()
                    continue
                student.__setattr__(k, data[k])
            db.add(student)
            db.commit()
            response = row2dict(student)
        except Exception as e:
            response = dict()
            response["msg"] = e.message
    else:
        try:
            student = models.Student.query.filter_by(username=uname).first()
            response = row2dict(student)
            response["gravatar"] = student.gravatar()
        except Exception as e:
            response = dict()
            response["msg"] = e.message
    return jsonify(response)
コード例 #19
0
def full_chain():
    response = {
        "chain": blockchain.chain,
        "length": len(blockchain.chain)
    }

    return jsonify(response)
コード例 #20
0
def students_route():
    response = []
    for student in models.Student.query.all():
        student_dict = row2dict(student)
        student_dict["gravatar"] = student.gravatar()
        response.append(student_dict)
    return jsonify(response)
コード例 #21
0
    def get_latest_twilight(self):
        filename = 'TWiLightMenu.7z'

        try:
            self.log.write('\nDownloading latest TWiLight Menu++ release...')

            conn = urlopen('https://api.github.com/repos/DS-Homebrew/TWiLightMenu/releases/'
                'latest')
            latest = jsonify(conn)
            conn.close()

                with urlopen(latest['assets'][0]
                    ['browser_download_url']) as src, open(filename, 'wb') as dst:
                    copyfileobj(src, dst)

            self.log.write('- Extracting ' + filename[:-3] + ' archive...')

            exe = path.join(sysname, '7za')

            proc = Popen([ exe, 'x', '-bso0', '-y', filename, '_nds', 'DSi - CFW users',
                'DSi&3DS - SD card users', 'roms' ])

            ret_val = proc.wait()

            if ret_val == 0:
                self.files.append(filename)
                self.folders.append('DSi - CFW users')
                self.folders.append('DSi&3DS - SD card users')
                Thread(target=self.install_twilight, args=(filename[:-3],)).start()

            else:
                self.log.write('ERROR: Extractor failed')
                Thread(target=self.clean, args=(True,)).start()
コード例 #22
0
    def get_latest_twilight(self):
        filename = False

        # Release archives names
        names = ('TWiLightMenu.7z', 'DSiMenuPP.7z', 'DSiMenuPlusPlus.7z',
                 'SRLoader.7z')

        for name in names:
            if (path.isfile(name)):
                filename = name
                break

        try:
            if filename:
                self.log.write('\nPreparing custom firmware...')

            else:
                self.log.write(
                    '\nDownloading latest TWiLight Menu++ release...')

                conn = urlopen(
                    'https://api.github.com/repos/RocketRobz/TWiLightMenu/releases/'
                    'latest')
                latest = jsonify(conn)
                conn.close()

                filename = names[0]
                urlretrieve(latest['assets'][0]['browser_download_url'],
                            filename)

            self.log.write('- Extracting ' + filename[:-3] + ' archive...')

            exe = path.join(sysname, '7za')

            proc = Popen([
                exe, 'x', '-bso0', '-y', filename, 'Autoboot for HiyaCFW',
                'CFW - SDNAND root', 'DSiWare (' + self.launcher_region + ')',
                '_nds', 'roms', 'BOOT.NDS'
            ])

            ret_val = proc.wait()

            if ret_val == 0:
                self.folders.append('Autoboot for HiyaCFW')
                self.folders.append('CFW - SDNAND root')
                self.folders.append('DSiWare (' + self.launcher_region + ')')
                Thread(target=self.install_twilight,
                       args=(filename[:-3], )).start()

            else:
                self.log.write('ERROR: Extractor failed')
                Thread(target=self.clean, args=(True, )).start()

        except (URLError, IOError) as e:
            self.log.write('ERROR: Could not get TWiLight Menu++')
            Thread(target=self.clean, args=(True, )).start()

        except OSError:
            self.log.write('ERROR: Could not execute ' + exe)
            Thread(target=self.clean, args=(True, )).start()
コード例 #23
0
ファイル: app.py プロジェクト: p6l-richard/FSND
def create_artist_submission():
  print(request.get_json())
  # called upon submitting the new artist listing form
  # TODO: insert form data as a new Venue record in the db, instead
  #!DONE
  # TODO: modify data to be the data object returned from db insertion
  #!DONE
  data = request.get_json()
  try:
    new_artist = get_or_create(Artist, name=data['name'], data=data)
    db.session.add(new_artist)
    db.session.commit()
    resp = Artist.query.order_by(Artist.id.desc()).first()
    return json.jsonify(resp.as_dict())
  except:
    db.session.rollback()
    print('Rolled back.\nError:', traceback.format_exc())
    return 'something went wrong, debug:' + str(traceback.format_exc()), 400
  finally:
    db.session.close()
  # on successful db insert, flash success
  # flash('Artist ' + request.form['name'] + ' was successfully listed!')
  # TODO: on unsuccessful db insert, flash an error instead.
  #!Returning bad request instead
  return render_template('pages/home.html')
コード例 #24
0
def new_node():
    data = request.get_json()
    if not data:
        return abort(400)

    if 'code' in data:
        code = data['code']
    else:
        return abort(400)

    if 'name' in data:
        name = data['name']
    else:
        name = 'UNK'

    if 'lat' in data:
        lat = data['lat']
    else:
        lat = 0

    if 'lng' in data:
        lng = data['lng']
    else:
        lng = 0

    path = models.add_node(name, lat, lng, code)
    if not path:
        return abort(403)
    db.add(path)
    db.commit()

    return jsonify({'message': path.message, 'next_code': path.next_code})
コード例 #25
0
    def delete(self) -> Response:
        data = request.get_json()
        print(data)

        try:

            import bson

            output = Test.objects(id=data['id']).delete()

            return jsonify({
                'result': 'Object has been deleted',
                'object': output
            })

        except ValidationError as e:

            return json.jsonify({
                'result': 'errror has happened',
                'detailed': e.message
            })


# new_user = User()
# user_settings = UserSettings()
# user_settings.default_cal = resp['calendar']
# new_user.settings = user_settings
# # more stuff
# new_user.save()
コード例 #26
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def get_game_by_id(game_id):
    try:
        game = models.Game.query.filter_by(id=game_id).first()
        response = row2dict(game)
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #27
0
 def Reconnect(self):
     resp = self._api.Reconnection(login=self._login, password=self._password, token=self._token,
                                   mode=self._mode)
     resp = jsonify(resp.text)
     if not resp['result']:
         raise ApiConnectionError(resp['reason'], data=resp)
     else:
         return True
コード例 #28
0
def school_route(sid):
    try:
        school = models.School.query.filter_by(id=sid).first()
        response = row2dict(school)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #29
0
def note_course_route(nid):
    try:
        course = models.Note.query.filter_by(id=nid).first().course
        response = row2dict(course)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #30
0
    def AddTrade(self):
        resp = self._api.AddTrade(
            token=self._token
        )
        resp = jsonify(resp.text)
        self._check_response(resp)

        return resp['data']
コード例 #31
0
def test_post():
    if request.method == 'POST':
        if 'application/json' in request.content_type:
            return json.jsonify(status='ok')
        else:
            return 'ok'
    else:
        return 'Expected POST, received {0}'.format(request.method)
コード例 #32
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def get_table_by_id(table_id):
    try:
        table = models.Table.query.filter_by(id=table_id).first()
        response = return_table(table)
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #33
0
def note_student_route(nid):
    try:
        student = models.Note.query.filter_by(id=nid).first().student
        response = row2dict(student)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #34
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def get_user_by_id(user_id):
    try:
        user = models.User.query.filter_by(id=user_id).first()
        response = return_user(user)
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #35
0
    def SetPortfolio(self):
        resp = self._api.SetPortfolio(
            token=self._token
        )
        resp = jsonify(resp.text)
        self._check_response(resp)

        return resp['data']
コード例 #36
0
def userify(all_args, service_payload):
    '''Augment `service_payload` with panoptes user data specified in `all_args` and post it to the specified endpoint

    Parameters
    ----------
    all_args : dict
        A dictionary containing the key/value pairs from the querystring;
        these represent either certain predefined fields like destination
        or the names of fields to be retrieved from the `User` objects

    service_payload : dict
        A dictionary containing an object vivified from a JSON string in
        the request body. This entire object graph will be searched for
        all occurrences of `user_id` and `user_ids` and any object that has
        either will be populated with a `users` array containing the
        requested fields

    Returns
    -------
    service_payload : dict
        The original service_payload object, augmented with User arrays for each object
        in the object graph with a `user_id` or `user_ids` field.

    Examples
    --------
    >>> userify({'login': None, 'destination': 'mast'}, {
        'some_field': 'some_value',
        'user_ids': [[1, 2], 3],
        'another_field': 'another_value'
    })
    {
        'some_field': 'some_value',
        'user_ids': [[1, 2], 3],
        'another_field': 'another_value',
        'users': [
            {'id': 1, 'login': '******'},
            {'id': 2, 'login': '******'},
            {'id': 3, 'login': '******'}
        ]
    }
    '''
    global users

    allowed_user_lookup_fields = _discover_user_lookup_fields(all_args)
    destination = all_args.get('destination')

    # remove restricted payload data before sending to destination (mast)
    # https://github.com/zooniverse/caesar/pull/1342#issuecomment-917096083
    for restriced_key in restricted_payload_keys:
        service_payload.pop(restriced_key, None)

    _stuff_object(service_payload, allowed_user_lookup_fields)
    users = {}

    if destination:
        _forward_contents(service_payload, destination)

    return jsonify(service_payload)
コード例 #37
0
def search():
    global conn
    resp = {}
    lat = request.args.get('lat')
    lon = request.args.get('long')
    point = lat + ", " + lon
    location = geolocator.reverse(point, language='en')
    country = location.raw['address']['country']
    country_code = location.raw['address']['country_code']
    for _ in range(0,2):
        # Try the query twice if the connection was closed (e.g. DB restarted).
        cur = conn.cursor()
        try:
            cur.execute("""
                select p.name, 
                       p.description, 
                       w.genus, 
                       w.species, 
                       w.common_name, 
                       w.conservation_status, 
                       count(*) AS total_trades 
                from wildlife_trade wt 
                inner join wildlife w on wt.wildlife_id = w.id 
                inner join product_category p on wt.product_category_id = p.id 
                where wt.country_code ilike '{}' 
                GROUP BY p.name, p.description, w.genus, w.species, w.common_name, w.conservation_status
                ORDER BY total_trades DESC;
            """.format(country_code))
        except psycopg2.OperationalError:
            conn = psycopg2.connect(database='responsibuyer')
    rows = cur.fetchall()
    products = {}
    for row in rows:
        product_name = row[0]
        if product_name not in products:
            products[product_name] = {"name": product_name, 'desc': row[1], 'animals': []}
        animal = {}
        animal['genus'] = row[2]
        animal['species'] = row[3]
        animal['common_name'] = row[4]
        animal['conservation_status'] = row[5]
        animal['trade_count'] = row[6]
        products[product_name]['animals'].append(animal)
    sorted_products = sort_products(list(products.values()))
    resp['products'] = sorted_products
    resp['country'] = country
    resp['country_code'] = country_code

    callback = request.args.get('callback')
    if callback:
        # Return JSONP
        json_data = json.dumps(resp)
        jsonp = "{}({});".format(callback, json_data)
        response = app.make_response(jsonp)
        response.mimetype = "application/javascript"
        return response
    else:
        return json.jsonify(resp)
コード例 #38
0
def school_courses_route(sid):
    try:
        response = []
        for course in models.School.query.filter_by(id=sid).first().courses:
            response.append(row2dict(course))
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #39
0
 def parse_data(self, data):
     data = jsonify(data)
     tweet = self.filter_keys(data, keys)
     tweet['urls'] = [self.filter_keys(url, ['expanded_url']) for url in data['entities']['urls']]
     user = self.filter_keys(data['user'], user_keys)
     tweet['user'] = user['id']
     tweet['text'] = tweet['text'].replace('\n', ' ')
     self.tweet = tweet
     self.user = user
コード例 #40
0
def change_status(id, status):
    if not user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'You are not authenticated'
                               }))
    if status == 'open' or status == 'close':
        db = get_db()
        if row_exists(db, 'bounties', id):
            try:
                db.execute('update bounties set status = ? where id = ?',
                           [status, id])
                db.commit()
                return render_template('ajax.html',
                                       info=jsonify({
                                           'error':
                                           'n',
                                           'msg':
                                           "Bounty #%s is now %s" %
                                           (id, status)
                                       }))
            except sqlite3.Error as e:
                return render_template('ajax.html',
                                       info=jsonify({
                                           'error':
                                           'y',
                                           'msg':
                                           "Can't update table " + e
                                       }))
        else:
            return render_template('ajax.html',
                                   info=jsonify({
                                       'error':
                                       'y',
                                       'msg':
                                       "Bounty #%s doesn't exist" % id
                                   }))
    else:
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': "Invalid status"
                               }))
コード例 #41
0
 def run(self):
     while True:
         try:    
             msg = self.prompt_user()
             self.send_request( bytes(jsonify(msg), 'utf-8') )
             
         except Exception:
             print("Exception in client. Restarting client.")
             traceback.print_exc()
             return self
コード例 #42
0
    def GetSymbols(self):  # TODO
        """

        :return:
        """
        resp = self._api.GetSymbols(token=self._token)
        resp = jsonify(resp.text)
        self._check_response(resp)

        return resp['data']
コード例 #43
0
def course_students_route(cid):
    try:
        course = models.Course.query.filter_by(id=cid).first()
        response = []
        for student in course.students:
            response.append(row2dict(student))
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #44
0
def student_notes_route(uname):
    try:
        student = models.Student.query.filter_by(username=uname).first()
        response = []
        for note in student.notes:
            response.append(row2dict(note))
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #45
0
def show_bounty(table, id):
    if not user_auth():
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'n',
                                   'msg': 'You are not authenticated'
                               }))
    if table != 'bounties' and table != 'targets':
        return render_template('ajax.html',
                               info=jsonify({
                                   'error': 'y',
                                   'msg': 'Invalid table'
                               }))
    data = query_db("select * from {0} where id = ?".format(table), [id],
                    one=True)
    info = {}
    for k, d in zip(data.keys(), data):
        info[k] = d
    return render_template('ajax.html', info=jsonify(info))
コード例 #46
0
 def parse_msg(self, request):
     if self.loggedIn == False:
         return generate_response("server", "error", "You are not logged in.")
     elif len(request["content"]) is 0:
         return generate_response("server", "error", "msg needs an argument.")
     else:
         bcastmsg = generate_response(self.username, "message", request["content"])
         broadcast(self, bcastmsg)
         messagehistory.append(jsonify(bcastmsg))
         return bcastmsg
コード例 #47
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def new_table():
    data = request.get_json(force=True)
    try:
        table = models.Table(name=data["table"]["name"])
        db.add(table)
        db.commit()
        response = return_success()
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #48
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def new_game():
    data = request.get_json(force=True)
    try:
        game = models.Game(table_id=data["game"]["table_id"])
        db.add(game)
        db.commit()
        response = return_success()
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #49
0
def new_school_route():
    data = request.get_json(force=True)
    try:
        school = models.School(data["name"])
        db.add(school)
        db.commit()
        response = row2dict(school)
        response["msg"] = "Success"
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #50
0
def new_student_route():
    data = request.get_json(force=True)
    try:
        student = models.Student(data["username"], data["realname"], data["email"])
        db.add(student)
        db.commit()
        response = row2dict(student)
        response["msg"] = "Success"
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #51
0
def buftransform(buf, fmt):
    buf = buf.getvalue()
    if fmt == 'j':
        buf = jsonify(buf)
    elif fmt == 'u':
        buf = urlencode(buf)
    elif fmt == 'x':
        buf = urlencode(buf).replace('%', '\\x')
    else:
        raise KeyError('Unsupported buffer transform', fmt)
    buf = io.BytesIO(buf)
    buf.seek(0, io.SEEK_END)
    return buf
コード例 #52
0
ファイル: user.py プロジェクト: kuykendb/eecs481-python-api
    def post(self):
        """Log user in.

        """

        app = current_app._get_current_object()

        req_json = request.get_json()

        email = req_json["email"]
        password = req_json["password"]

        user = db_user.query.filter_by(email=str(email)).first()

        if user is not None:
            if utils.verify_password(password,user.password):
                token = user.generate_auth_token(app)
                return jsonify({ 'token': token.decode('ascii') })
            else:
                return json.jsonify(error="Invalid password!")
        else:
            return json.jsonify(error="User does not exist!")
コード例 #53
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def register_user(user_data=None):
    if not user_data:
        request.get_json(force=True)["user"]

    try:
        user = models.User(username=user_data["username"], name=user_data["name"], email=user_data["email"])
        db.add(user)
        db.commit()
        response = return_success()
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
コード例 #54
0
ファイル: wikipedia.py プロジェクト: CHCMATT/Code
def wikiSearch(query, url, results=5):
    """Use MediaWikis API to search for values from wiktionary and wikipedia"""
    # First, we need to grab the data, and serialize it in JSON
    url_query = urlify(query)
    data = jsonify(get(full_search % (lang, url, url_query)).read())

    # Check to see if we have #(results as arg form) results, then make a list
    if not data[1]:
        return False
    if len(data[1]) > results:
        return data[1][:results]
    else:
        # Assume it's smaller than or = 5
        return data[1]
コード例 #55
0
def course_addstudent_route(cid, uname):
    try:
        course = models.Course.query.filter_by(id=cid).first()
        student = models.Student.query.filter_by(username=uname).first()
        course.students.append(student)
        db.add(student)
        db.add(course)
        db.commit()
        response = dict()
        response["msg"] = "Success"
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #56
0
def new_course_route():
    data = request.get_json(force=True)
    try:
        course = models.Course(data["coursename"], data["professor"])
        school = models.School.query.filter_by(id=data["school_id"]).first()
        school.courses.append(course)
        db.add(course)
        db.add(school)
        db.commit()
        response = row2dict(course)
        response["msg"] = "Success"
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #57
0
def course_notes_route(cid):
    try:
        course = models.Course.query.filter_by(id=cid).first()
        response = []
        for note in course.notes:
            note_dict = row2dict(note)
            author = models.Student.query.filter_by(id=note.student_id).first()
            author_dict = row2dict(author)
            author_dict["gravatar"] = author.gravatar()
            note_dict["author"] = author_dict
            response.append(note_dict)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #58
0
def classmate_route(uname):
    try:
        student = models.Student.query.filter_by(username=uname).first()
        response = []
        for course in student.courses:
            for classmate in course.students:
                if classmate == student:
                    continue
                entry = row2dict(classmate)
                entry["class_id"] = course.id
                entry["gravatar"] = classmate.gravatar()
                response.append(entry)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #59
0
def feed_route(uname):
    try:
        student = models.Student.query.filter_by(username=uname).first()
        response = []
        for course in student.courses:
            for note in course.notes:
                note_dict = row2dict(note)
                author = models.Student.query.filter_by(id=note.student_id).first()
                author_dict = row2dict(author)
                author_dict["gravatar"] = author.gravatar()
                note_dict["author"] = author_dict
                response.append(note_dict)
    except Exception as e:
        response = dict()
        response["msg"] = e.message
    return jsonify(response)
コード例 #60
0
ファイル: __init__.py プロジェクト: stevenmirabito/GoalSentry
def delete_game(game_id):
    try:
        game = models.Game.query.filter_by(id=game_id).first()
        db.delete(game)

        for score in models.Score.query.filter_by(game_id=game_id):
            db.delete(score)

        db.commit()

        response = {
            "status": {
                "success": True
            }
        }
    except Exception as e:
        response = return_error(e)

    return jsonify(response)