コード例 #1
0
ファイル: fmtasks.py プロジェクト: fjfnaranjo/fmtasks
def add_task(id):
    """Adds a new task to the database."""

    content = get_content_or_400(request)

    collection = get_db_collection()

    object_id = None
    if id:
        object_id = ObjectId(id)
        object = collection.find({"_id": object_id})
        if object:
            response = jsonify(errormsg="id already exists")
            response.status_code = 400
            return response

    new_object = {"content": content}
    if id:
        new_object["_id"] = id
    new_object_id = collection.insert_one(new_object).inserted_id

    response = jsonify(id=str(new_object_id))
    response.status_code = 201
    response.headers["Location"] = url_for('get_task', id=new_object_id)
    return response
コード例 #2
0
 def get(self):
     q = db_session.query(UnitInfo).filter(UnitInfo.unit_no == session['unit_no'])
     if not q.count():
         return jsonify(success=False, token="", msg=u'没有找到token', show_msg=False)
     else:
         q = q.one()
         return jsonify(success=True, token=q.weixin_token)
コード例 #3
0
ファイル: endpoints.py プロジェクト: cmbi/xssp-rest
def get_xssp_result(input_type, output_type, id):
    """
    Get the result of a previous job submission.

    :param input_type:
        Either 'pdb_id', 'pdb_redo_id', 'pdb_file' or 'sequence'.
    :param output_type: Either 'hssp_hssp', 'hssp_stockholm', or 'dssp'.
    :param id: The id returned by a call to the create method.
    :return: The output of the job. If the job status is not SUCCESS, this
             method returns an error.
    """
    from xssp_api.tasks import get_task
    task = get_task(input_type, output_type)
    _log.debug("task is {}".format(task.__name__))

    async_result = task.AsyncResult(id)
    if async_result.status != 'SUCCESS':
        return jsonify({'error': 'job status is {}'.format(async_result.status)}), 500

    result = async_result.get()
    if len(result) <= 0:
        return jsonify({'error': 'empty result'}), 500

    response = {'result': result}
    return jsonify(response)
コード例 #4
0
def GetGameList():
	jsonRequest = request.get_json(force = True)
	app.logger.info("hook: GetGameList: %s", jsonRequest)

	if 'UserId' not in jsonRequest:
		return json.jsonify(Message = "Missing UserId.",
					ResultCode = 2)

	user_id = jsonRequest['UserId']
	game_list = db.get_user_game_list(user_id)
	list = {}
	for game_id, actor_nr in game_list:
		app.logger.info("%s -> %d", game_id, actor_nr)
		if db.game_state_exists(game_id):
			state = db.get_game_state(game_id)
			list[game_id] = {
				'ActorNr': actor_nr, 
			}
			if state != "":
				stateObj = json.loads(state)
				list[game_id]['Properties'] = stateObj['CustomProperties']

		else:
			db.delete_user_game(user_id, game_id)


	return json.jsonify(ResultCode = 0, Message = "", Data = list)
コード例 #5
0
 def post(self, brand_id):
     brand = _get_by_id(brand_id)
     if not brand:
         return jsonify(success=False, msg=u'您要修改的品牌不存在', show_msg=True)
     db_session.query(BrandInfo).filter(BrandInfo.id == brand_id).update({'id': brand_id})
     db_session.commit()
     return jsonify(success=True, msg=u'修改品牌名称成功', show_msg=True)
コード例 #6
0
def query():
    req = request.get_json()
    if not req:
        return make_response('', 400)

    try:
        conn = pool.getconn()
        with conn.cursor() as cur:
            cur.execute(req['query'])
            results = cur.fetchall()

        return jsonify({
            'status': 200,
            'results': results
        })

    except (psycopg2.DataError, psycopg2.ProgrammingError, psycopg2.NotSupportedError) as e:
        # User error
        return jsonify({
            'status': 400,
            'error': e.pgerror
        }), 400

    except:
        return jsonify({
            'status': 500,
            'error': str(sys.exc_info()[1])
        }), 500

    finally:
        pool.putconn(conn)
コード例 #7
0
ファイル: endpoints.py プロジェクト: cmbi/xssp-rest
def create_xssp(input_type, output_type):
    """
    Create HSSP or DSSP data.

    Adds a job to a queue to produce the data in the given output_type format
    from the data passed. The pdb_id and sequence must be set in a form
    parameter called 'data', and the pdb_file content in a parameter called
    'file_' format.

    :param input_type: Either 'pdb_id', 'pdb_redo_id', 'pdb_file' or 'sequence'.
    :param output_type: Either 'hssp_hssp', 'hssp_stockholm', or 'dssp'.
    :return: The id of the job.
    """
    form = XsspForm(allowed_extensions=app.config['ALLOWED_EXTENSIONS'],
                    csrf_enabled=False)
    form.input_type.data = input_type
    form.output_type.data = output_type
    form.sequence.data = request.form.get('data', None)
    form.pdb_id.data = request.form.get('data', None)
    form.file_.data = request.files.get('file_', None)
    if form.validate_on_submit():
        celery_id = process_request(form.input_type.data, form.output_type.data,
                                    form.pdb_id.data, request.files,
                                    form.sequence.data)

        storage.insert('tasks', {'task_id': celery_id,
                                 'input_type': input_type,
                                 'output_type': output_type,
                                 'created_on': datetime.datetime.utcnow()})

        return jsonify({'id': celery_id}), 202
    return jsonify(form.errors), 400
コード例 #8
0
def GameLeave():
	jsonRequest = request.get_json(force = True)
	app.logger.info("hook: GameLeave: %s", jsonRequest)

	if 'GameId' not in jsonRequest:
		return json.jsonify(Message = "Missing GameId.",
					ResultCode = 1)
	if 'UserId' not in jsonRequest:
		return json.jsonify(Message = "Missing UserId.",
					ResultCode = 2)
	if 'ActorNr' not in jsonRequest:
		return json.jsonify(Message = "Missing ActorNr.",
					ResultCode = 6)

	game_id = jsonRequest['GameId']
	user_id = jsonRequest['UserId']
	actor_nr = jsonRequest['ActorNr']
					
	if 'IsInactive' in jsonRequest and jsonRequest['IsInactive']:
		if actor_nr > 0:
			db.set_user_game(user_id, game_id, jsonRequest['ActorNr'])
	else:
		db.delete_user_game(user_id, game_id)

	return json.jsonify(Message = "",
					ResultCode = 0)
コード例 #9
0
ファイル: __init__.py プロジェクト: bfirsh/Website
def json_response(f, *args, **kwargs):
    try:
        response = f(*args, **kwargs)

    except HTTPException as e:
        data = {'error': str(e),
                'description': e.description}
        return jsonify(data), e.code

    except Exception as e:
        app.logger.error('Exception during json request: %r', e)
        # Werkzeug sends the response and then logs, which is fiddly
        from werkzeug.debug.tbtools import get_current_traceback
        traceback = get_current_traceback(ignore_system_exceptions=True)
        app.logger.info('Traceback %s', traceback.plaintext)

        data = {'error': e.__class__.__name__,
                'description': str(e)}
        return jsonify(data), 500

    else:
        if isinstance(response, (app.response_class, BaseResponse)):
            return response

        return jsonify(response), 200
コード例 #10
0
def automatic_refresh():
    """Refreshing an OAuth 2 token using a refresh token.
    """
    token = session['oauth_token']

    # We force an expiration by setting expired at in the past.
    # This will trigger an automatic refresh next time we interact with
    # Googles API.
    token['expires_at'] = time() - 10

    extra = {
        'client_id': client_id,
        'client_secret': client_secret,
    }

    def token_updater(token):
        session['oauth_token'] = token

    google = OAuth2Session(client_id,
                           token=token,
                           auto_refresh_kwargs=extra,
                           auto_refresh_url=refresh_url,
                           token_updater=token_updater)

    # Trigger the automatic refresh
    jsonify(google.get('https://www.googleapis.com/oauth2/v1/userinfo').json())
    return jsonify(session['oauth_token'])
コード例 #11
0
ファイル: backend.py プロジェクト: nickles-lee/code-sample
def query_train_location():
    try:
        trip_uid = request.args['trip_uid']
        query_time_s = int(request.args['query_time_s'])
        return json.jsonify(lpgps.get_train_coordinates(trip_uid, query_time_s))
    except:
        return json.jsonify({'error': 'bad param'})
コード例 #12
0
    def get(self):
        i = request.args
        today = datetime.datetime.now().strftime('%Y%m%d')
        date = i.get('date', today).strip()
        type_ = i.get('type', 'total').strip()  # 收入类型:card/cash/total

        if type_ in ('card', 'total'):
            if date == today:
                TransTable = aliased(Trans)
            else:
                TransTable = aliased(HistoryTrans)

            q_card = db_session.query(func.sum(HistoryTrans.amount).label('amount')) \
                .filter(TransTable.trans_date == date) \
                .filter(TransTable.trans_code == '000010') \
                .filter(TransTable.status == '0')

            if session['user_level'] == 'unit':
                q_card = q_card.filter(TransTable.unit_no == session['unit_no'])
            if session['user_level'] == 'shop':
                q_card = q_card.filter(TransTable.shop_no == session['shop_no'])

        if type_ in ('cash', 'total'):
            q_cash = db_session.query(func.sum(SaleOrderInfo.cash_pay_amount).label('amount')) \
                .filter(SaleOrderInfo.is_paid == True) \
                .filter(SaleOrderInfo.pay_time == '20000000')

        if type_ == 'card':
            return jsonify(success=True, total=q_card.one().amount)
        if type_ == 'cash':

            return jsonify(success=True, total=q_cash.one().amount)
コード例 #13
0
ファイル: views.py プロジェクト: jxcl/shadow-share
def register_key(user_name):
    """Receive a key from the user and index it."""
    db = get_db()

    if db.user_lookup(user_name):
        response = {
            "status": "FAIL",
            "error_message": "Username already taken."
            }

        return json.jsonify(response)
    else:
        req_obj = request.get_json()

        key = req_obj["public_key"]
        if io.key_valid(key):
            db.register_user(user_name, key)
            response = {
                "status": "SUCCESS"
                }
            return json.jsonify(response)
        else:
            response = {
                "status": "FAIL",
                "error_message": "The provided key is not valid."
                }
            return json.jsonify(response)
コード例 #14
0
ファイル: v2.py プロジェクト: causztic/sutd-timetable
def load_data():
    module = request.get_json()

    if 'group' in module:
        try:
            gt = 'group'
            lb = module['label']
        except (KeyError, ValueError):
            h = hash(frozenset(int(i) for i in module['group']))
            gt = 'hgrp'
            lb = '%05d' % (h % 100000)

        rd.sadd('{}s'.format(gt), lb)
        rd.sadd('%s:%s' % (gt, lb), *module['group'])

        return json.jsonify({
            'status': 'ok',
        })

    if not Module.query.get(module['code']):
        db.session.add(Module(**module))

    sections = []

    for cn, section in module['sections'].items():
        try:
            cn = int(cn)
        except ValueError:
            continue

        sct = Section.query.get(cn)

        if not sct:
            db.session.add(Section(**{
                'class_no': cn,
                'name': section['name'],
                'mod_code': module['code']
            }))
            db.session.commit()
        else:
            sct.last_updated = datetime.now()
            Lesson.query.filter_by(class_no=cn).delete()

        sections.append(section['name'])

        for i in section['schedule']:
            d = get_int(i['d'])
            dts = tuple(datetime(*(d+get_int(i[l]))) for l in 'se')
            db.session.add(Lesson(**{
                'dts': dts,
                'class_no': cn,
                'location': i['l'],
                'component': i['c'],
            }))

        db.session.commit()

    return json.jsonify({
        'status': 'ok',
    })
コード例 #15
0
ファイル: cache_view.py プロジェクト: Wordseer/wordseer
 def clear_old_query(self, params):
     query = Query.query.get(params["query_id"])
     if query:
         query.delete()
         return jsonify({ "ok": True })
     else:
         return jsonify({ "ok": False })
コード例 #16
0
ファイル: json_blueprint.py プロジェクト: pyload/pyload
def package(id):
    api = flask.current_app.config["PYLOAD_API"]
    try:
        data = api.get_package_data(id)
        for pyfile in data["links"]:
            if pyfile["status"] == 0:
                pyfile["icon"] = "status_finished.png"
            elif pyfile["status"] in (2, 3):
                pyfile["icon"] = "status_queue.png"
            elif pyfile["status"] in (9, 1):
                pyfile["icon"] = "status_offline.png"
            elif pyfile["status"] == 5:
                pyfile["icon"] = "status_waiting.png"
            elif pyfile["status"] == 8:
                pyfile["icon"] = "status_failed.png"
            elif pyfile["status"] == 4:
                pyfile["icon"] = "arrow_right.png"
            elif pyfile["status"] in (11, 13):
                pyfile["icon"] = "status_proc.png"
            else:
                pyfile["icon"] = "status_downloading.png"

        tmp = data["links"]
        tmp.sort(key=lambda entry: entry["order"])
        data["links"] = tmp
        return jsonify(data)

    except Exception:
        flask.abort(500)

    return jsonify(False)
コード例 #17
0
ファイル: json_blueprint.py プロジェクト: pyload/pyload
def links():
    api = flask.current_app.config["PYLOAD_API"]
    try:
        links = api.status_downloads()
        ids = []
        for link in links:
            ids.append(link["fid"])

            if link["status"] == 12:
                formatted_eta = link["format_eta"]
                formatted_speed = format_speed(link["speed"])
                link["info"] = f"{formatted_eta} @ {formatted_speed}"

            elif link["status"] == 5:
                link["percent"] = 0
                link["size"] = 0
                link["bleft"] = 0
                link["info"] = api._("waiting {}").format(link["format_wait"])
            else:
                link["info"] = ""

        return jsonify(links=links, ids=ids)

    except Exception as exc:
        flask.abort(500)

    return jsonify(False)
コード例 #18
0
ファイル: server.py プロジェクト: AlexeyProskuryakov/rr
def update_post(fullname, video_id):
    found = db.get_post(fullname, video_id)
    if found:
        update_stored_posts(db, [found])
        found = db.get_post(fullname, video_id)
        return jsonify(**{"ok": True, "updated": found})
    return jsonify(**{"ok": False, "detail": "Post %s %s not found" % (fullname, video_id)})
コード例 #19
0
ファイル: app.py プロジェクト: Smart-Switch/backend
    def post(self):
        args = self.post_parser.parse_args()

        user = User.where('email', args['email']).get().first()

        if (user is None):
            response = jsonify({"message": "User not found"})
            response.status_code = 404
            return response

        # TODO: Use User's static methods
        token = self.encode_token(user)

        user_token = user.resettoken().order_by('created_at', 'desc').first()
        if (user_token is not None):
            user_token.active = False
            user_token.save()

        user_token = user.resettoken().create(token=token, active=True)

        msg = Message('Smart Switch password reset', recipients=[args['email']])
        msg.body = "%s?resettoken=%s" % (app.config['web-client'], user_token.token)
        mail.send(msg)

        response = jsonify({"message": "Password reset token", "token": token})
        response.status_code = 200
        return response
コード例 #20
0
ファイル: app.py プロジェクト: planrich/tu_aic_13
def query(company, days):
    with db.session_scope() as session:
        took_me_ms = int(round(time.time() * 1000))
        result = calc_avg_sentiment(session, company, days)
        took_me_ms = int(round(time.time() * 1000)) - took_me_ms

        if result is not None:
            rating = result
            if rating == None:
                return jsonify(message=\
                    """Sorry. No sentiment information is stored \
    for %s. Either you mistyped the company or yahoo finance does not \
    contain articles about the compnay/product!""" % company)
            rating = format(rating, '.2f')

            details = {
                    "message": "The average sentiment of {0} is '{1}'.".format(company, rating),
                    "rating":rating,
                    "keyword":company,
                    "interval":"[0..10]. towards 0 corresponds to negative, whereas 10 is positive",
                    "timespan":"the last %d day(s)" % days
                    }
            if request.args.get('d') is not None:
                details['ms'] = took_me_ms
            return jsonify(**details)
        else:
            return jsonify(message=\
                    """Sorry. No sentiment information is stored \
for %s. Either you mistyped the company or yahoo finance does not \
contain articles about the compnay/product!""" % company)
コード例 #21
0
ファイル: app.py プロジェクト: planrich/tu_aic_13
def post_task_answer(task_id):
    #http://main-tuaic13.rhcloud.com/api/tasks/157/answers
    with db.session_scope() as session:
        task = session.query(db.Task).filter(db.Task.id == task_id).first()
        if not task:
            return jsonify(error='Task not found'), 404

        raw_answer = utils.get_raw_answer(request)
        if not raw_answer:
            return jsonify(error='Error parsing json'), 400

        worker_id = raw_answer['user']
        worker = session.query(db.Worker).filter(db.Worker.id == worker_id).first()
        if not worker:
            worker = db.Worker(worker_id, 0, 0)
            session.add(worker)
            session.commit()

        if worker.blocked == 1:
            return jsonify(error='Unfortunately, your account has been blocked'), 401

        answer = db.Answer(task, worker, raw_answer['answer'])
        session.add(answer)
        session.commit()

        if len(task.answers) == task.answers_requested:
            task.calculate_rating()

            session.add(task)
            session.commit()
            task.rate_workers()
            session.commit()

        return jsonify(answer.as_dict()), 200
コード例 #22
0
ファイル: app.py プロジェクト: Smart-Switch/backend
    def put(self):
        args = self.put_parser.parse_args()
        user_id = self.decode_token(args['token'])['user_id']
        new_password = User.encode_password(args['password'])
        user = User.find(user_id)

        if (user is None):
            response = jsonify({"message": "User not found"})
            response.status_code = 404
            return response

        tt = PasswordReset.where('token', args['token']).get().first()
        if tt is None or tt.active is 0:
            response = jsonify({"message": "Invalid token"})
            response.status_code = 401
            return response

        logger.info("id " + str(user_id))
        logger.info("passwd " + str(new_password))
        user.password = new_password
        user.save()
        tt.active = 0
        tt.save()

        response = jsonify({"message": "Password changed successfully"})
        response.status_code = 200
        return response
コード例 #23
0
def signup():
    '''
    Callback for validation of signup
    '''
    # Extracts data from the posted request
    container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form
    login = container["login"]
    password = container["password"]
    email = container["email"]
    # Checks parameters are filled
    if (not login) or (not password) or (not email): 
        return jsonify(message = "Login, password and email must be filled."), 400
    # Checks if a user with given login already exists in db
    if not user_db_service.get_user_by_login(login) is None:
        return jsonify(message = "This login is already used."), 400
    
    #
    # Here we should check that email is valid and not already registered in db.
    # Then we would send a email to this address with an hyperlink to allow the user to confirm her address.
    # For the sake of simplicity, let's forget all this stuff and let's validate the account
    #
    
    # Registers user in db
    user = User(login, password, email)
    user.signin_count += 1
    user_db_service.create_user(user)
    # Everything is ok, let's finalize the authentication 
    session["uid"] = user.uid
    session["auth"] = True
    # Redirects to user page
    return jsonify(redirect_uri = url_for("user")) 
コード例 #24
0
ファイル: base.py プロジェクト: StratusPrint/HUB
def register_peripheral():
    """
        Register Peripheral
        Registers node type. Should be done before activating node.
        ---
        tags:
          - sensors
        responses:
          200:
            description: Returns "(id) has been registered as (type)"
        """

    if request.method == "POST":
        id = int(request.form.get('id'))
        pertype = request.form.get('pertype')
        if request.form.get('is_update'):
            success = hub.conf.update_data({id: pertype})
        else:
            success = hub.conf.add_data({id: pertype})

        if success:
            return json.jsonify(
                    {
                        "message": str(id)
                        + " has been registered as " + pertype
                    })
        else:
            return json.jsonify(
                    {
                        "message": str(id)
                        + " was not registered, are you updating?"
                    })
    abort(405)
コード例 #25
0
ファイル: views.py プロジェクト: rob-nn/open_gait_analytics
def gait_sample_upload(patient_id, gait_sample_index):
    gait_sample_index = int(gait_sample_index)
    db = get_db()
    patient = db.patients.find_one({'_id': ObjectId(patient_id)})
    if not patient:
        return jsonify({'error': 'Patient not found. Oid: %s' % patient_id}), 404 
    if  'gait_samples' not in patient.keys() or gait_sample_index >= len(patient['gait_samples'] ):
        return jsonify({'error': 'Gait sample index %s for  Oid %s not found.' % (patient_id, str(gait_sample_index))}), 404 
    qtm_matlab_file = request.files['file']
    import oga_api.etl.qtm as qtm
    data = qtm.readQTMFile(qtm_matlab_file.stream)
    positional_data = {}
    positional_data['patient_id'] = ObjectId(patient_id)
    positional_data['gait_sample_index'] = gait_sample_index
    positional_data['frame_rate'] = data['frame_rate']
    positional_data['initial_frame'] = 0
    positional_data['final_frame'] = data['frames'] - 1
    positional_data['frames'] = data['frames']
    positional_data['number_markers'] = data['number_markers']
    positional_data['original_filename'] = qtm_matlab_file.filename
    markers = [];
    for i in range(data['number_markers']):
            markers.append('')
    positional_data['markers'] = markers
    #positional_data['trajectories'] = data['trajectories'].tolist()
    with open(get_file_name(positional_data), 'wb') as f:
        pickle.dump(data['trajectories'].tolist(), f)

    db.positionals_data.replace_one({'patient_id': ObjectId(patient_id), 'gait_sample_index': gait_sample_index}, positional_data, True)
    pos = db.positionals_data.find_one({'patient_id': ObjectId(patient_id), 'gait_sample_index': gait_sample_index})
    #del pos['trajectories']
    return json_util.dumps(pos, allow_nan=False), 200
コード例 #26
0
def basic_auth():
    '''
    Checks basic authentication by login/password
    '''
    # Extracts data from the posted request
    container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form
    login = container["login"]
    password = container["password"]
    # Checks parameters are filled
    if (not login) or (not password): return jsonify(message = "Login, password and email are mandatory"), 400
    # Checks if user with given login exists in db
    user = user_db_service.get_user_by_login(login)
    if user is None: return jsonify(message = "Wrong login and password combination."), 400
    # Checks user password
    if not user.check_password(password): return jsonify(message = "Wrong login and password combination."), 400
    # Registers user id in session
    session["uid"] = user.uid
    # Checks if 2fa is activated
    if user.tfa_activited():
        # 2FA activated - Redirects to tfa_challenge page
        return jsonify(redirect_uri = url_for("tfa_challenge"))
    else:
        # Basic auth only
        # Let's increase the sign_in counter in user object (for demo purpose only)
        user.signin_count += 1
        user_db_service.update_user(user)
        # Everything is ok, let's finalize the authentication 
        session["auth"] = True
        # Redirects to user page
        return jsonify(redirect_uri = url_for("user"))
コード例 #27
0
ファイル: sentences_view.py プロジェクト: vijaym123/wordseer
    def get(self, **kwargs):
        params = dict(kwargs, **request.args)
        query = Query.query.get(params["query_id"])
        # Determine the words, phrases or phrase sets that match the query in
        # order to send back information about which terms should be highlighted
        # in the UI.
        matching_words = self.get_matching_words(params)
        if query:
            # If we're being asked for a single sentence view, then just return
            # the data for that sentence.
            sentence = Sentence.query.get(params["sentence_id"])
            if sentence is not None:
                return jsonify(self.make_single_sentence_view(sentence, matching_words))
            # If not, then return the data for all the sentences that match the
            # query.
            results = []
            total = len(query.sentences)
            start = int(params["start"][0])

            end = int(params["limit"][0]) + start

            for sentence in query.sentences[start:end]:
                result = {
                    "sentence": self.make_sentence_dict(sentence, matching_words),
                    "id": sentence.id,
                    "document_id": sentence.document_id,
                    "sentence_set": " ".join([str(set.id) for set in sentence.sets]),
                }
                self.add_metadata_properties(sentence, result)
                results.append(result)
            return jsonify(results=results, total=total)
コード例 #28
0
    def get(self):
        i = request.args
        unit_no = session['unit_no']
        user_level = session['user_level']
        page, limit = int(i.get('page', 1)), int(i.get('limit', 10))

        q = db_session.query(
            func.sum(CardInfo.amount).label('amount'),
            func.sum(CardInfo.points).label('points'),
            func.count(CardInfo.card_no).label('count'),
            UnitInfo.unit_no,
            UnitInfo.unit_name
        )
        q = q.outerjoin(UnitInfo, CardInfo.unit_no == UnitInfo.unit_no)
        q = q.group_by(UnitInfo.unit_no, UnitInfo.unit_name)

        if user_level == 'unit':
            q = q.filter(UnitInfo.unit_no == unit_no)

        if user_level in ['shop', 'operator']:
            return jsonify(success=False, msg=rspmsg.PERMISSION_DENIDE)

        total = q.count()
        balances = q.limit(limit).offset((page - 1) * limit).all()
        return jsonify(success=True, total=total, page=page, limit=limit,
                       data=[{'amount': b.amount, 'points': b.points, 'count': b.count,
                              'unit_no': b.unit_no, 'unit_name': b.unit_name} for b in balances])
コード例 #29
0
    def post(self):
        class_name = request.json.get('class_name', '').strip()
        pid = request.json.get('pid', '').strip()
        pid = pid if pid else None

        if not class_name:
            return jsonify(success=False, msg=u'请输入正确的商品分类名称', show_msg=True)

        # q = db_session.query(GoodsClassInfo)
        # q = q.filter(GoodsClassInfo.class_name == class_name)
        # q = q.filter(GoodsClassInfo.unit_no == session['unit_no'])
        # if session['shop_no']:
        #     q = q.filter(GoodsClassInfo.shop_no == session['shop_no'])
        # if q.count():
        #     return jsonify(success=False, msg=u'此商品分类名称已经存在', show_msg=True)

        goods_class = GoodsClassInfo()
        goods_class.id = str(uuid.uuid4())
        goods_class.pid = pid
        goods_class.class_name = class_name
        goods_class.unit_no = session['unit_no']
        goods_class.shop_no = session['shop_no'] if session['shop_no'] else None
        db_session.add(goods_class)
        db_session.commit()
        return jsonify(success=True, msg=u'添加商品分类成功', show_msg=True,
                       data={'id': goods_class.id, 'pid': pid, 'class_name': class_name})
コード例 #30
0
ファイル: app.py プロジェクト: evroza/kabarakalumniportal
def login_authenticate():
    """
    Validates user input submitted via login form and logs them in only if they have provided valid credentials
    :return:
    """

    if request.method == "POST":
        if request.get_json(force=True)["username"] and request.get_json(force=True)["password"]:
            username = request.get_json(force=True)["username"].strip()
            password = request.get_json(force=True)["password"].strip()
            # Get the matching user from database
            user = db.fetch_user(username=username)
            if len(user) == 1:
                if check_password_hash(user[0][8], password):
                    user = [detail for detail in user[0]]
                    session["idUsers"],session["UserTypes_idUserTypes"],session["FirstName"], session["LastName"] = user[0], user[1],user[3],user[4]
                    session["email"], session["Username"], session["UserType"] = user[6], user[7], user[12]
                    print str(session)
                    return json.jsonify(session)

                else:
                    return json.jsonify(error="The password you entered is incorrect!")

            else:
                return json.jsonify(error="User not found. Invalid Details")
        else:
            return json.jsonify(error="You must fill in all fields!")
    else:
        return json.jsonify(error="There is a problem with your request. You are sending POST \
                                   instead of GET requests to this API.")
コード例 #31
0
def phrasal_verbs():
    count = int(request.args.get('count', '5'))
    return jsonify(phrasal_verbs_data.get_exact_part(count))
コード例 #32
0
def readiness():
    """Readiness probe."""
    return jsonify({"status": "ready"}), 200
コード例 #33
0
def archive_work(id):
    if id:
        db.Work.archive(id)
        return jsonify(id)
    return 'Error', 500
コード例 #34
0
def topic_q23_vocabulary(topic_value):
    topic_q23_vocabulary_data = builder.flat_file(
        "data/topics_q23/{0}.list".format(topic_value))
    return jsonify(topic_q23_vocabulary_data.get_exact_part(7))
コード例 #35
0
def verbs_with_prepositions():
    count = int(request.args.get('count', '5'))
    return jsonify(verbs_with_prep_data.get_exact_part(count))
コード例 #36
0
ファイル: app.py プロジェクト: jaredwhichard/Tech-Journal
def profile():
    """Fetching a protected resource using an OAuth 2 token.
    """
    github = OAuth2Session(client_id, token=session['oauth_token'])
    return jsonify(github.get('https://api.github.com/user').json())
コード例 #37
0
def profile():
    """Fetching a protected resource using an OAuth 2 token.
    """
    freesound = OAuth2Session(client_id, token=session['oauth_token'])
    return jsonify(freesound.get('https://freesound.org/apiv2/me').json())
コード例 #38
0
def expressions():
    count = int(request.args.get('count', '5'))
    return jsonify(expression_data.get_exact_part(count))
コード例 #39
0
def murphy():
    count = int(request.args.get('count', '4'))
    return jsonify(murphy_data.get_exact_part(count))
コード例 #40
0
def grammar():
    count = int(request.args.get('count', '4'))
    return jsonify(grammar_data.get_exact_part(count))
コード例 #41
0
def topics_q23():
    return jsonify(
        builder.wrap_flat_records(sample(topics_q23_question_data.keys(), 1)))
コード例 #42
0
def conversation_expressions():
    count = int(request.args.get('count', '5'))
    return jsonify(conv_exp_data.get_exact_part(count))
コード例 #43
0
def interview():
    key = sample(interview_question_data.keys(), 1)[0]
    return jsonify(
        builder.wrap_flat_records(interview_question_data[key].get_all()))
コード例 #44
0
def topic_q23_questions(topic_value):
    return jsonify(
        builder.wrap_flat_records(
            topics_q23_question_data[topic_value].get_all()))
コード例 #45
0
def full_chain():
    response = {
        'chain' : blockchain.chain,
        'length' : len(blockchain.chain)
    }
    return jsonify(response), 200                                       # 将json转成字符串
コード例 #46
0
ファイル: views.py プロジェクト: vivekanand1101/opinator
def plugin_response_handler():
    """It does all the talking with the plugin"""

    # Recieving data from the plugin
    product_id = request.json['product_id']
    url = request.json['url']
    website_name = request.json['website_name']

    #checking if the product was already analyzed
    outdated = False
    product = is_present(website_name, product_id)
    product_location = os.path.abspath(
        os.path.join(os.getcwd(), 'opinator/REVIEWS/%s' % product_id))
    if product is not None:
        if is_valid(product):
            bushy_pos_path = os.path.join(product_location,
                                          '%s_bushy_pos.txt' % product_id)
            bushy_neg_path = os.path.join(product_location,
                                          '%s_bushy_neg.txt' % product_id)
            google_pos_path = os.path.join(
                product_location, '%s_google_page_rank_pos.txt' % product_id)
            google_neg_path = os.path.join(
                product_location, '%s_google_page_rank_neg.txt' % product_id)

            with open(bushy_pos_path, 'r') as bp:
                bushy_pos = bp.read()
            with open(bushy_neg_path, 'r') as bn:
                bushy_neg = bn.read()
            with open(google_pos_path, 'r') as gp:
                google_pos = gp.read()
            with open(google_neg_path, 'r') as gn:
                google_neg = gn.read()

            jsonout = jsonify({
                'sentiment': {
                    'class': str(product.sentiment),
                    'score': str(product.sentiment_score)
                },
                'counts': {
                    'positive': str(product.positive_count),
                    'negative': str(product.negative_count),
                    'neutral': str(product.neutral_count),
                    'very_negative': str(product.very_negative_count),
                    'very_positive': str(product.very_positive_count),
                },
                'summary': {
                    'bushy': {
                        'positive': bushy_pos,
                        'negative': bushy_neg,
                    },
                    'google_page_rank': {
                        'positive':
                        url_for('google_pos_summary', product_id=product_id),
                        'negative':
                        url_for('google_neg_summary', product_id=product_id),
                    }
                }
            })
            return jsonout
        else:
            outdated = True

    cwd = os.getcwd()
    product_location = os.path.abspath(
        os.path.join(os.getcwd(), 'opinator/REVIEWS/%s' % product_id))
    if os.path.exists(product_location):
        os.system('rm -r %s' % product_location)

    ###################Sentiment Analysis########################

    #if not then, call the scraper and the reviews
    #The current working directory gets affected by this
    #earlier it was "opinator" folder then in order to
    #start the scraper, it is moved to "scraper" folder
    execute_scraper_and_move_output_file(website_name, product_id)

    #read the reviews in the csv file
    df = read_output_file(product_id)

    (pos_txt, neg_txt, neutral_txt) = open_files(product_id)

    (positive_count, negative_count, neutral_count, \
            very_positive_count, very_negative_count) = categorize_reviews_and_get_counts \
                                                                (df, pos_txt, neg_txt, neutral_txt)

    close_files(pos_txt, neg_txt, neutral_txt)

    (sentiment_score, sentiment) = normalize_counts (positive_count, negative_count, neutral_count, \
                                                            very_positive_count, very_negative_count)
    ##############################################################

    os.chdir(cwd)
    #print 'cwd before summary ', os.getcwd()
    ####################Summarization#############################

    #print 'product location ', product_location
    #print 'before abs ', os.path.join(os.getcwd(), 'opinator/REVIEWS')

    pos_google_page_rank = SummaryUsingGooglePageRank(os.path.join(product_location, '%s_pos.txt' % (product_id)), \
                            os.path.join(product_location, '%s_google_page_rank_pos.txt' % (product_id)))
    pos_google_page_rank.summarize()

    neg_google_page_rank = SummaryUsingGooglePageRank(os.path.join(product_location, '%s_neg.txt' % product_id), \
                            os.path.join(product_location, '%s_google_page_rank_neg.txt' % product_id))
    neg_google_page_rank.summarize()


    pos_bushy = BushyPath(os.path.join(product_location, '%s_pos.txt' % product_id), \
                            os.path.join(product_location, '%s_bushy_pos.txt' % product_id))
    pos_bushy.summarize()


    neg_bushy = BushyPath(os.path.join(product_location, '%s_neg.txt' % product_id), \
                            os.path.join(product_location, '%s_bushy_neg.txt' % product_id))
    neg_bushy.summarize()

    ##############################################################

    os.chdir(cwd)
    #update the database if necessary otherwise, add a new product to the db
    if outdated:
        update(website_name=website_name,
               product_id=product_id,
               url=url,
               sentiment_score=sentiment_score,
               sentiment=str(sentiment),
               positive_count=positive_count,
               negative_count=negative_count,
               neutral_count=neutral_count,
               very_positive_count=very_positive_count,
               very_negative_count=very_negative_count)
    else:
        insert(website_name=website_name,
               product_id=product_id,
               url=url,
               sentiment_score=sentiment_score,
               sentiment=str(sentiment),
               negative_count=negative_count,
               positive_count=positive_count,
               neutral_count=neutral_count,
               very_positive_count=very_positive_count,
               very_negative_count=very_negative_count)

    #return the json object to the plugin
    bushy_pos_path = os.path.join(product_location,
                                  '%s_bushy_pos.txt' % product_id)
    bushy_neg_path = os.path.join(product_location,
                                  '%s_bushy_neg.txt' % product_id)
    google_pos_path = os.path.join(product_location,
                                   '%s_google_page_rank_pos.txt' % product_id)
    google_neg_path = os.path.join(product_location,
                                   '%s_google_page_rank_neg.txt' % product_id)

    with open(bushy_pos_path, 'r') as bp:
        bushy_pos = bp.read()
    with open(bushy_neg_path, 'r') as bn:
        bushy_neg = bn.read()
    with open(google_pos_path, 'r') as gp:
        google_pos = gp.read()
    with open(google_neg_path, 'r') as gn:
        google_neg = gn.read()

    jsonout = jsonify({
        'sentiment': {
            'class': str(sentiment),
            'score': str(sentiment_score)
        },
        'counts': {
            'positive': str(positive_count),
            'negative': str(negative_count),
            'neutral': str(neutral_count),
            'very_negative': str(very_negative_count),
            'very_positive': str(very_positive_count),
        },
        'summary': {
            'bushy': {
                'positive': bushy_pos,
                'negative': bushy_neg,
            },
            'google_page_rank': {
                'positive': url_for('google_pos_summary',
                                    product_id=product_id),
                'negative': url_for('google_neg_summary',
                                    product_id=product_id),
            }
        }
    })

    return jsonout
コード例 #47
0
ファイル: api.py プロジェクト: SlovakNationalGallery/vampart
def getFacialModels():
    path = request.args.get('path')
    imagePath = os.path.join(fileDir, path)
    faces = getFaces(imagePath, save = False)

    return jsonify(faces)
コード例 #48
0
def random_words():
    count = int(request.args.get('count', '7'))
    return jsonify(random_words_data.get_exact_part(count))
コード例 #49
0
def create_a_message():
    #messages_keys = ["date", "lat", "long", "message", "receptant", "sender"]
    #data = {key: request.json[key] for key in USER_KEYS}

    all_data = request.json
    print(all_data)

    for key in messages_keys:

        if (key in all_data) == False:
            return json.jsonify({"error": f"falta el atributo {key}"})
        else:
            pass

    data = {}
    data_mala = {}
    contador = 0
    for key in messages_keys:

        if contador == 0:

            fecha = request.json[key]
            boleano = isinstance(fecha, str)  #vemos si fecha es un string

            if boleano == True:
                data[key] = fecha
                data_mala[key] = fecha

            else:
                data_mala[key] = fecha
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'error':
                    "Debes introducir una fecha que sea un string"
                })

        elif contador == 1:

            lat = request.json[key]
            boleano_1 = isinstance(lat, int)  #vemos si lat es un int
            boleano_2 = isinstance(lat, float)  #vemos si lat es un float

            if (boleano_1 == True or boleano_2 == True):

                data[key] = lat
                data_mala[key] = lat

            else:
                data_mala[key] = lat
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'lat':
                    data_mala["lat"],
                    'error':
                    "Debes introducir una lat que sea un int o un float"
                })

        elif contador == 2:

            variable_long = request.json[key]
            boleano_1 = isinstance(variable_long, int)  #vemos si lat es un int
            boleano_2 = isinstance(variable_long,
                                   float)  #vemos si lat es un float

            if (boleano_1 == True or boleano_2 == True):

                data[key] = variable_long
                data_mala[key] = variable_long

            else:
                data_mala[key] = variable_long
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'lat':
                    data_mala["lat"],
                    'long':
                    data_mala["long"],
                    'error':
                    "Debes introducir un long que sea un int o un float"
                })

        elif contador == 3:

            mensaje_recibido = request.json[key]
            boleano = isinstance(mensaje_recibido,
                                 str)  #vemos si mensaje es un string

            if boleano == True:
                data[key] = mensaje_recibido
                data_mala[key] = mensaje_recibido

            else:
                data_mala[key] = mensaje_recibido
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'lat':
                    data_mala["lat"],
                    'long':
                    data_mala["long"],
                    'message':
                    data_mala["message"],
                    'error':
                    "Debes introducir un mensaje que sea un string"
                })

        elif contador == 4:

            receptant = request.json[key]
            boleano = isinstance(receptant, int)  #vemos si receptant es un int

            if (boleano == True):

                lista_de_todos_los_usuarios = usuarios.find({}, {
                    "uid": 1,
                    "_id": 0
                })
                lista_con_todos_los_uid = []

                for diccionario in lista_de_todos_los_usuarios:
                    lista_con_todos_los_uid.append(diccionario["uid"])

                if (receptant in lista_con_todos_los_uid) == True:
                    data[key] = receptant
                    data_mala[key] = receptant

                else:
                    data_mala[key] = receptant
                    return json.jsonify({
                        'date':
                        data_mala["date"],
                        'lat':
                        data_mala["lat"],
                        'long':
                        data_mala["long"],
                        'message':
                        data_mala["message"],
                        'receptant':
                        data_mala["receptant"],
                        'error':
                        "Debes introducir un receptant que sea parte de los usuarios de la base de datos. Además recuerda que de debe ser del tipo int"
                    })

            else:
                data_mala[key] = receptant
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'lat':
                    data_mala["lat"],
                    'long':
                    data_mala["long"],
                    'message':
                    data_mala["message"],
                    'receptant':
                    data_mala["receptant"],
                    'error':
                    "Debes introducir un receptant que sea un int"
                })

        elif contador == 5:

            sender = request.json[key]
            boleano = isinstance(sender, int)  #vemos si sender es un int

            if (boleano == True):

                lista_de_todos_los_usuarios = usuarios.find({}, {
                    "uid": 1,
                    "_id": 0
                })
                lista_con_todos_los_uid = []

                for diccionario in lista_de_todos_los_usuarios:
                    lista_con_todos_los_uid.append(diccionario["uid"])

                if (sender in lista_con_todos_los_uid) == True:
                    data[key] = sender
                    data_mala[key] = sender

                else:
                    data_mala[key] = sender
                    return json.jsonify({
                        'date':
                        data_mala["date"],
                        'lat':
                        data_mala["lat"],
                        'long':
                        data_mala["long"],
                        'message':
                        data_mala["message"],
                        'receptant':
                        data_mala["receptant"],
                        'sender':
                        data_mala["sender"],
                        'error':
                        "Debes introducir un sender que sea parte de los usuarios de la base de datos. Además recuerda que de debe ser del tipo int"
                    })

            else:
                data_mala[key] = sender
                return json.jsonify({
                    'date':
                    data_mala["date"],
                    'lat':
                    data_mala["lat"],
                    'long':
                    data_mala["long"],
                    'message':
                    data_mala["message"],
                    'receptant':
                    data_mala["receptant"],
                    'sender':
                    data_mala["sender"],
                    'error':
                    "Debes introducir un sender que sea un int"
                })

        contador = contador + 1

    lista_de_todos_los_mensajes = list(mensajes.find({}, {"mid": 1, "_id": 0}))
    lista_con_todos_los_mid = []

    for diccionario in lista_de_todos_los_mensajes:

        lista_con_todos_los_mid.append(diccionario["mid"])

    lista_con_todos_los_mid.sort()  #ordenamos de mayor a menor los mid
    tamano_lista_con_todos_los_mid = len(lista_con_todos_los_mid)
    ultimo_mid = lista_con_todos_los_mid[tamano_lista_con_todos_los_mid - 1]
    mid_a_asignar = ultimo_mid + 1

    data["mid"] = mid_a_asignar

    mensajes.insert_one(data)

    return json.jsonify({
        'date': data["date"],
        'lat': data["lat"],
        'long': data["long"],
        'message': data["message"],
        'receptant': data["receptant"],
        'sender': data["sender"],
        'mid': data["mid"]
    })
コード例 #50
0
ファイル: api.py プロジェクト: opendev-jb/jeopardy-trainer
def mark_question():
    user = check_session(request)
    user_answer = UserAnswer(user, request.json['question_id'], request.json['correct'])
    user_answer.save(jeopardyDB)
    return jsonify(user_answer.to_dict())
コード例 #51
0
def textsearch():

    text_search_keys = ["desired", "required", "forbidden", "userId"]
    contador = 0
    data = {}
    data_mala = {}

    #all_data = request.json
    #all_data = request.data
    all_data = access_token = request.data.decode('UTF-8')

    if all_data == "":
        resultados = list(mensajes.find({}, {"_id": 0}))
        return json.jsonify(resultados)

    all_data = request.json

    if isinstance(all_data, dict) == False:
        resultados = list(mensajes.find({}, {"_id": 0}))
        return json.jsonify(resultados)

    if all_data == {}:
        resultados = list(mensajes.find({}, {"_id": 0}))
        return json.jsonify(resultados)

    if len(all_data) == 1:

        if "desired" in all_data.keys():
            palabras = all_data["desired"]

            if palabras == []:
                resultados = list(mensajes.find({}, {"_id": 0}))
                return json.jsonify(resultados)
            else:
                palabra_final = ""
                for palabra in palabras:
                    palabra_final = palabra_final + " " + palabra
                variable_a_retornar = list(
                    mensajes.find({
                        "$text": {
                            "$search": palabra_final
                        }
                    }, {
                        "score": {
                            "$meta": "textScore"
                        },
                        "mid": 1,
                        "message": 1,
                        "sender": 1,
                        "_id": 0
                    }).sort([("score", {
                        "$meta": "textScore"
                    })]))
                return json.jsonify(variable_a_retornar)

        if "required" in all_data.keys():
            palabras = all_data["required"]

            if palabras == []:
                resultados = list(mensajes.find({}, {"_id": 0}))
                return json.jsonify(resultados)
            else:
                palabra_final = ""
                for palabra in palabras:
                    palabra_final = palabra_final + """\"""" + palabra + """\" """
                variable_a_retornar = list(
                    mensajes.find({
                        "$text": {
                            "$search": palabra_final
                        }
                    }, {
                        "score": {
                            "$meta": "textScore"
                        },
                        "mid": 1,
                        "message": 1,
                        "sender": 1,
                        "_id": 0
                    }).sort([("score", {
                        "$meta": "textScore"
                    })]))
                return json.jsonify(variable_a_retornar)

        if "forbidden" in all_data.keys():
            palabras = all_data["forbidden"]  #["hola, "chao]

            if palabras == []:
                resultados = list(mensajes.find({}, {"_id": 0}))
                return json.jsonify(resultados)

            else:
                resultados = list(mensajes.find({}, {"_id": 0}))
                lista_mensajes = []
                lista_strings_a_borrar = []

                for resultado in resultados:

                    resultado_limpio = strip_accents(
                        resultado["message"].lower())
                    mensaje_id = resultado["mid"]

                    lista_mensajes.append([resultado_limpio, mensaje_id])

                for resultado in resultados:

                    resultado_limpio = strip_accents(
                        resultado["message"].lower())

                    for palabra in palabras:

                        palabra_limpia = strip_accents(palabra.lower())

                        if palabra_limpia in resultado_limpio:

                            lista_strings_a_borrar.append(resultado_limpio)
                            break

                for mensaje_borrar in lista_strings_a_borrar:

                    for lista_real in lista_mensajes:

                        if lista_real[0] == mensaje_borrar:

                            lista_mensajes.remove(lista_real)
                            break

            return json.jsonify(lista_mensajes)

        if "userId" in all_data.keys():

            user = all_data["userId"]
            resultados = list(mensajes.find({"sender": user}, {"_id": 0}))
            return json.jsonify(resultados)

    else:
        for key in text_search_keys:

            if contador == 0:

                lista_palabras_deseadas = request.json[key]
                boleano = isinstance(lista_palabras_deseadas,
                                     list)  #vemos si es una lista

                if boleano == True:
                    boleano_default = True
                    for palabra in lista_palabras_deseadas:
                        if (isinstance(palabra, str)) == True:
                            boleano_default = True
                        else:
                            boleano_default = False
                            data_mala[key] = lista_palabras_deseadas
                            return json.jsonify({
                                'desired':
                                data_mala["desired"],
                                'error':
                                "Debes introducir elementos de tipo string"
                            })

                    data[key] = lista_palabras_deseadas
                    data_mala[key] = lista_palabras_deseadas

                else:
                    data_mala[key] = lista_palabras_deseadas
                    return json.jsonify({
                        'desired':
                        data_mala["desired"],
                        'error':
                        "Debes introducir una lista en desired"
                    })

            elif contador == 1:

                lista_palabras_requeridas = request.json[key]
                boleano = isinstance(lista_palabras_requeridas,
                                     list)  #vemos si es una lista

                if boleano == True:
                    boleano_default = True
                    for palabra in lista_palabras_requeridas:
                        if (isinstance(palabra, str)) == True:
                            boleano_default = True
                        else:
                            boleano_default = False
                            data_mala[key] = lista_palabras_requeridas
                            return json.jsonify({
                                'desired':
                                data_mala["desired"],
                                'required':
                                data_mala["required"],
                                'error':
                                "Debes introducir elementos de tipo string"
                            })

                    data[key] = lista_palabras_requeridas
                    data_mala[key] = lista_palabras_requeridas

                else:
                    data_mala[key] = lista_palabras_requeridas
                    return json.jsonify({
                        'desired':
                        data_mala["desired"],
                        'required':
                        data_mala["required"],
                        'error':
                        "Debes introducir una lista en required"
                    })

            elif contador == 2:

                lista_palabras_prohibidas = request.json[key]
                boleano = isinstance(lista_palabras_prohibidas,
                                     list)  #vemos si es una lista

                if boleano == True:
                    boleano_default = True
                    for palabra in lista_palabras_prohibidas:
                        if (isinstance(palabra, str)) == True:
                            boleano_default = True
                        else:
                            boleano_default = False
                            data_mala[key] = lista_palabras_prohibidas
                            return json.jsonify({
                                'desired':
                                data_mala["desired"],
                                'required':
                                data_mala["required"],
                                'forbidden':
                                data_mala["forbidden"],
                                'error':
                                "Debes introducir elementos de tipo string"
                            })

                    data[key] = lista_palabras_prohibidas
                    data_mala[key] = lista_palabras_prohibidas

                else:
                    data_mala[key] = lista_palabras_prohibidas
                    return json.jsonify({
                        'desired':
                        data_mala["desired"],
                        'required':
                        data_mala["required"],
                        'forbidden':
                        data_mala["forbidden"],
                        'error':
                        "Debes introducir una lista en forbidden"
                    })

            elif contador == 3:

                sender_id = request.json[key]
                boleano = isinstance(sender_id,
                                     int)  #vemos si sender es un int

                if (boleano == True):

                    lista_de_todos_los_usuarios = usuarios.find({}, {
                        "uid": 1,
                        "_id": 0
                    })
                    lista_con_todos_los_uid = []

                    for diccionario in lista_de_todos_los_usuarios:
                        lista_con_todos_los_uid.append(diccionario["uid"])

                    if (sender_id in lista_con_todos_los_uid) == True:
                        data[key] = sender_id
                        data_mala[key] = sender_id

                    else:
                        data_mala[key] = sender_id
                        return json.jsonify({
                            'desired':
                            data_mala["desired"],
                            'required':
                            data_mala["required"],
                            'forbidden':
                            data_mala["forbidden"],
                            'userId':
                            data_mala["userId"],
                            'error':
                            "Debes introducir un userid que este en la base de datos"
                        })

                else:
                    data_mala[key] = sender_id
                    return json.jsonify({
                        'desired':
                        data_mala["desired"],
                        'required':
                        data_mala["required"],
                        'forbidden':
                        data_mala["forbidden"],
                        'userId':
                        data_mala["userId"],
                        'error':
                        "Debes introducir un userid que sea un int"
                    })

            contador = contador + 1

        palabra_final = """ """
        palabras_requeridas_lista = data["required"]
        for palabra in palabras_requeridas_lista:
            palabra_final = palabra_final + """\"""" + palabra + """\" """

        palabras_deseadas_lista = data["desired"]
        for palabra in palabras_deseadas_lista:
            palabra_final = palabra_final + " " + palabra

        palabra_final = palabra_final + " "

        palabras_prohibidas_lista = data["forbidden"]

        for palabra in palabras_prohibidas_lista:
            palabra_final = palabra_final + "-" + palabra + " "

        print(palabra_final)

        varibale_a_retornar = list(
            mensajes.find(
                {
                    "sender": data["userId"],
                    "$text": {
                        "$search": palabra_final
                    }
                }, {
                    "score": {
                        "$meta": "textScore"
                    },
                    "mid": 1,
                    "message": 1,
                    "sender": 1,
                    "_id": 0
                }).sort([("score", {
                    "$meta": "textScore"
                })]))

        return json.jsonify(varibale_a_retornar)
コード例 #52
0
ファイル: models.py プロジェクト: innofocus/pragmastack
def getlist(datatype,selector=None):
    app.logger.debug(' getlist : datatype / selector '+datatype+'/'+str(selector))
    cypher = reports[datatype]['cypher']
    query = reports[datatype]['query']
    editor = reports[datatype]['editor'] or []

    result=[]
    if not 'selector' in reports[datatype]:
        app.logger.debug(' getlist : no selector in reports')
        nodelist = lu.graph.run(cypher+query+' order by name').data()
    else:
        app.logger.debug(' getlist : selector : type '+str(selector)+':'+str(type(selector)))
        if selector == None:
            return json.jsonify(' Error, selector needed.')
        params =  {reports[datatype]['selector']:selector}
        nodelist = lu.graph.run(cypher + query + ' order by name',parameters=params).data()
    #app.logger.debug(' getlist : nodelist : '+str(nodelist))
    header=query.replace('\n',' ').replace(' ','').split(',')
    result.append(header)

    # lists d'autocomplete par colonne/field
    # dict of sets
    autocomplete={}
    iplist=[]
    if datatype=='network': iplist=[]
    for i in nodelist:
        tmp=[]
        for j in header:
            cell = ""
            if isinstance(i[j],list):
                cell = ',\n'.join(i[j]).decode('utf-8', errors='ignore')
            elif isinstance(i[j], int) or isinstance(i[j], float):
                cell = str(i[j])
            elif not i[j] == None:
                #app.logger.debug(' cell i,j : '+','.join(list((i[j]))))
                try:
                    cell = i[j].decode('utf-8', errors='ignore')
                except UnicodeEncodeError:
                    cell = i[j]

            tmp.append(cell)

            # construction de la list autocomplete
            if j in editor:
                if j in autocomplete:
                    autocomplete[j].add(cell)
                else:
                    autocomplete[j]=set((cell,))
            if datatype == 'network' and j == reports[datatype]['key']:
                iplist.append(i[j])

        result.append(tmp)
    if datatype == 'network':
        app.logger.debug(' getlist : selector '+str(selector))
        for i in list(IPNetwork(str(selector))):
            if not i in iplist:
                result.append([str(i),'','',''])
    # colonnes de handsontable (autocomplete = dropdown)
    columns = []
    for i in header:
        # si la colonne est editable, creer la liste des options
        if i in editor:
            columns.append({  'type': 'autocomplete', 'source': list(autocomplete[i]), 'readOnly': False})
        else:
            columns.append({  'editor': False,  'readOnly': True})
    #app.logger.debug(' getlist : result : '+str(result))
    return { 'data':result, 'columns': columns}
コード例 #53
0
ファイル: house.py プロジェクト: qq740980764/ihome_py
def release_new_houseing_sources():
    """保存房屋的基本信息
    :accept:
    {
        "title":"",
        "price":"",
        "area_id":"1",
        "address":"",
        "room_count":"",
        "acreage":"",
        "unit":"",
        "capacity":"",
        "beds":"",
        "deposit":"",
        "min_days":"",
        "max_days":"",
        "facility":["7","8"]
    }
    :return:
    """
    user_id = g.user_id
    accept_json = request.get_json()
    title = accept_json.get("title")
    price = accept_json.get("price")
    area_id = accept_json.get("area_id")
    address = accept_json.get("address")
    room_count = accept_json.get("room_count")
    acreage = accept_json.get("acreage")
    unit = accept_json.get("unit")
    capacity = accept_json.get("capacity")
    beds = accept_json.get("beds")
    deposit = accept_json.get("deposit")
    min_days = accept_json.get("min_days")
    max_days = accept_json.get("max_days")

    if not all([
            title, price, area_id, address, room_count, acreage, unit,
            capacity, beds, deposit, min_days, max_days
    ]):
        return jsonify(errno=RET.DATAERR, errmsg="data missing")
    try:
        price = float(price) * 100
        deposit = float(deposit) * 100

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="data missing")

    #判断城区ID是否存在
    try:
        area = Area.query.get(area_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="Mysql Error")
    if not area:
        return jsonify(errno=RET.NODATA, errmsg="No Data")

    # 保存房屋信息
    house = House(
        user_id=user_id,
        area_id=area_id,
        title=title,
        price=price,
        address=address,
        room_count=room_count,
        acreage=acreage,
        unit=unit,
        capacity=capacity,
        beds=beds,
        deposit=deposit,
        min_days=min_days,
        max_days=max_days,
    )
    facility = accept_json.get("facility")
    print("facility", facility)
    if facility:
        try:
            facility = Facility.query.filter(Facility.id.in_(facility)).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="Mysql Error")
        if not facility:
            return jsonify(errno=RET.NODATA, errmsg="Data Not Exist")

    if facility:
        house.facilities = facility

    #提交数据到Mysql
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="Mysql Data Commit Error")

    return jsonify(errno=RET.OK, errmsg="OK", data={"house_id": house.id})
コード例 #54
0
 def get(movie, user_first_name, user_last_name):
     """ Return an mark key information based on its movie and its user """
     mark = MarkRepository.get(movie=movie,
                               user_first_name=user_first_name,
                               user_last_name=user_last_name)
     return jsonify({"mark": mark.json})
コード例 #55
0
ファイル: house.py プロジェクト: qq740980764/ihome_py
def search_house():
    area_id = request.args.get("aid", )
    start_data = request.args.get("sd", )
    end_data = request.args.get("ed", )
    sort_key = request.args.get("sort-key", )
    page = request.args.get("page", )

    if area_id:
        try:
            area = Area.query.get(area_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="data errer ")

    #处理页数
    try:
        page = int(page)

    except Exception as e:
        current_app.logger.error(e)
        page = 1

    filter_params = []

    try:
        if start_data:
            start_data = datetime.strptime(start_data, "%Y-%m-%d")

        if end_data:
            end_data = datetime.strptime(end_data, "%Y-%m-%d")

        if start_data > end_data:
            return jsonify(errno=RET.DATAERR, errmsg="data is errer")

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="data errer ")

    #过滤参数容器
    filter_params = []
    #订单不符合列表
    order_conflict = None
    try:

        if end_data and start_data:
            order_conflict = Order.query.filter(
                Order.end_date >= start_data
                and Order.start_date <= end_data).all()
        if start_data:
            order_conflict = Order.query.filter(
                Order.end_date >= start_data).all()

        if end_data:
            order_conflict = Order.query.filter(Order.start_date <= end_data)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="mysql errer ")

    if order_conflict:
        conflict_house_ids = [conflict.id for conflict in order_conflict]

        if conflict_house_ids:
            filter_params.append(House.id.notin_(conflict_house_ids))

    if area:
        filter_params.append(area)

    if sort_key == "booking":
        House.query.filter(*filter_params).order_by(House.order_count)

    elif sort_key == "price-inc":
        House.query.filter(*filter_params).order_by(House.price)

    elif sort_key == "price-des":
        House.query.filter(*filter_params).order_by(-House.price)

    else:
        House.query.filter(*filter_params).order_by(House.update_time)
コード例 #56
0
ファイル: api.py プロジェクト: opendev-jb/jeopardy-trainer
def handle_unauthorized(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response
コード例 #57
0
def on_event():
    """Handles an event from Google Chat."""
    event = request.get_json()
    if event['type'] == 'ADDED_TO_SPACE' and not event['space'][
            'singleUserBotDm']:
        text = 'Thanks for adding me to "%s"!' % (
            event['space']['displayName']
            if event['space']['displayName'] else 'this chat')
    elif event['type'] == 'MESSAGE':
        text = 'You said: <br> `%s`' % event['message']['text']
    elif event['type'] == 'CARD_CLICKED':
        if event['action']['actionMethodName'] == 'getTrendingIssues':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Trending Issues",
                        "subtitle": "Select Duration",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            "buttons": [{
                                "textButton": {
                                    "text": "Last 7 days",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getTrendingIssues7Days"
                                        }
                                    }
                                }
                            }, {
                                "textButton": {
                                    "text": "Last 1 month",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getTrendingIssues1Month"
                                        }
                                    }
                                }
                            }, {
                                "textButton": {
                                    "text": "Last 3 Months",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getTrendingIssues3Months"
                                        }
                                    }
                                }
                            }]
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getTrendingIssues7Days':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Trending Issues",
                        "subtitle": "Last 7 days",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(TRENDING_7_DAYS_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getTrendingIssues1Month':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Trending Issues",
                        "subtitle": "Last 1 Month",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(TRENDING_1_MONTH_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getTrendingIssues3Months':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Trending Issues",
                        "subtitle": "Last 3 Months",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(TRENDING_3_MONTHS_API)
                            }
                        }]
                    }]
                }]
            })

        elif event['action']['actionMethodName'] == 'getReport':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Report",
                        "subtitle": "Select Duration",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            "buttons": [{
                                "textButton": {
                                    "text": "Last 7 days",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getReport7Days"
                                        }
                                    }
                                }
                            },
                                        {
                                            "textButton": {
                                                "text": "Last 1 month",
                                                "onClick": {
                                                    'action': {
                                                        'actionMethodName':
                                                        "getReport1Month"
                                                    }
                                                }
                                            }
                                        }, {
                                            "textButton": {
                                                "text": "Last 3 Months",
                                                "onClick": {
                                                    'action': {
                                                        'actionMethodName':
                                                        "getReport3Months"
                                                    }
                                                }
                                            }
                                        }]
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getReport7Days':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Report",
                        "subtitle": "Last 7 days",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text': getReport(REPORT_7_DAYS_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getReport1Month':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Report",
                        "subtitle": "Last 1 Month",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text': getReport(REPORT_1_MONTH_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getReport3Months':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Report",
                        "subtitle": "Last 3 Months",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text': getReport(REPORT_3_MONTHS_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getRecurringIssues':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Recurring Issues",
                        "subtitle": "Select Duration",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            "buttons": [{
                                "textButton": {
                                    "text": "Last 7 days",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getRecurringIssues7Days"
                                        }
                                    }
                                }
                            }, {
                                "textButton": {
                                    "text": "Last 1 month",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getRecurringIssues1Month"
                                        }
                                    }
                                }
                            }, {
                                "textButton": {
                                    "text": "Last 3 Months",
                                    "onClick": {
                                        'action': {
                                            'actionMethodName':
                                            "getRecurringIssues3Months"
                                        }
                                    }
                                }
                            }]
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getRecurringIssues7Days':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Recurring Issues",
                        "subtitle": "Last 7 days",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(RECURRING_7_DAYS_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action']['actionMethodName'] == 'getRecurringIssues1Month':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Recurring Issues",
                        "subtitle": "Last 1 Month",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(RECURRING_1_MONTH_API)
                            }
                        }]
                    }]
                }]
            })
        elif event['action'][
                'actionMethodName'] == 'getRecurringIssues3Months':
            return json.jsonify({
                "cards": [{
                    "header": {
                        "title": "Recurring Issues",
                        "subtitle": "Last 3 Months",
                        "imageUrl":
                        "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                        "imageStyle": "IMAGE"
                    },
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                getListOfIssuesInString(RECURRING_3_MONTHS_API)
                            }
                        }]
                    }]
                }]
            })
        if event['action']['actionMethodName'] == 'showSimilarMessage':
            return json.jsonify({
                "cards": [{
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                'Please type: <b>similar "jiraID"</b> <br>Ex: <i>similar ABLL-1234</i>'
                            }
                        }]
                    }]
                }]
            })
        if event['action']['actionMethodName'] == 'showResolutionMessage':
            return json.jsonify({
                "cards": [{
                    "sections": [{
                        "widgets": [{
                            'textParagraph': {
                                'text':
                                'Please type: <b>resolution "jiraID"</b> <br>Ex: <i>resolution ABLL-1234</i>'
                            }
                        }]
                    }]
                }]
            })

    else:
        return
    return json.jsonify({
        "cards": [{
            "header": {
                "title": "Simba Chat Bot",
                "subtitle": "This is subtitle",
                "imageUrl":
                "https://w7.pngwing.com/pngs/979/165/png-transparent-lion-king-simba-illustration-simba-nala-rafiki-mufasa-the-lion-king-hyena-mammal-cat-like-mammal-animals.png",
                "imageStyle": "IMAGE"
            },
            "sections": [{
                "widgets": [{
                    "keyValue": {
                        "iconUrl":
                        "https://seeklogo.com/images/J/jira-logo-FD39F795A7-seeklogo.com.png",
                        "topLabel": "Jira ID",
                        "content": "ABLL-1234"
                    }
                }, {
                    "keyValue": {
                        "icon": "DESCRIPTION",
                        "topLabel": "Category",
                        "content": "Shared Hosting Linux"
                    }
                }, {
                    "buttons": [{
                        "textButton": {
                            "text": "Show Trending Issues",
                            "onClick": {
                                'action': {
                                    'actionMethodName': "getTrendingIssues"
                                }
                            }
                        }
                    }, {
                        "textButton": {
                            "text": "Show Recurring Issues",
                            "onClick": {
                                'action': {
                                    'actionMethodName': "getRecurringIssues"
                                }
                            }
                        }
                    }, {
                        "textButton": {
                            "text": "Generate Report/Analysis",
                            "onClick": {
                                'action': {
                                    'actionMethodName': "getReport"
                                }
                            }
                        }
                    }, {
                        "textButton": {
                            "text": "Show Similar Jiras",
                            "onClick": {
                                'action': {
                                    'actionMethodName': "showSimilarMessage"
                                }
                            }
                        }
                    }, {
                        "textButton": {
                            "text": "Possible Resolutions by Jira",
                            "onClick": {
                                'action': {
                                    'actionMethodName': "showResolutionMessage"
                                }
                            }
                        }
                    }]
                }]
            }]
        }]
    })
コード例 #58
0
ファイル: venta.py プロジェクト: mayeg/parcialweb
 def get_cliente(self, id):
     cliente = ClienteDao().get_cliente(id).get_dict()
     return jsonify(cliente)
コード例 #59
0
ファイル: api.py プロジェクト: Dev-Learn/LearnPython
def error_return(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response
コード例 #60
0
 def get(self, test_id):
     """
     ---
     summary: Get test by id
     description: All test questions with test metainfo
     parameters:
         - in: path
           name: user_id
           schema:
             type: integer
           required: true
           description: Numeric ID of the user to get
     responses:
         200:
             description: OK
             content:
                 application/json:
                     schema: TestsSchema
                     example: {
                                 "archived": false,
                                 "id": 8,
                                 "max_time": null,
                                 "questions": [
                                     {
                                         "answer": "1",
                                         "id": 5,
                                         "manually_grading": true,
                                         "points": 0,
                                         "question": "2",
                                         "question_type": 0,
                                         "test": 5
                                     },
                                     {
                                         "answer": "1",
                                         "id": 9,
                                         "manually_grading": true,
                                         "points": 0,
                                         "question": "2",
                                         "question_type": 0,
                                         "test": 9
                                     }
                                 ],
                                 "questions_tests": [
                                     5,
                                     9
                                 ],
                                 "test_name": "45"
                             }
         404:
             description: Not found
             content:
                 application/json:
                     schema: ErrorSchema
                     example:
                       message: [Test not found]
     """
     test = application.orm.get_test(test_id)
     test_schema = TestsSchema()
     if test is None:
         return fail_response("Test is not found", code=404)
     res = test_schema.dump(test)
     questions = []
     questions_schema = QuestionsSchema()
     for question_id in res.data['questions_tests']:
         obj = application.orm.get_question(question_id)
         questions.append(questions_schema.dump(obj).data)
     res.data.update({'questions': questions})
     return jsonify(res.data)