Example #1
0
    def post(self):
        data = GameCreator.parser.parse_args()

        try:
            count = mongo.db.questions.count()
            if count < 1:
                return {'message': 'No questions found'}, 500
            question_indices = random.sample(range(count), min(10, count))
            questions_db = mongo.db.questions.find()
            questions = [questions_db[x]
                         for x in range(0, count)
                         if x in question_indices]

            game_id = mongo.db.games.insert_one({
                "time_limit": data['time_limit'],
                "game_state": "waiting",
                "questions": questions,
                "players": [],
                "cur_question": -1,
                "cur_time": datetime.datetime.utcnow(),
                "cur_question_end_time": datetime.datetime.utcnow() + datetime.timedelta(seconds=data['time_limit']),
                "next_question_start_time": datetime.datetime.utcnow() + datetime.timedelta(seconds=60),
                "next_question_end_time": datetime.datetime.utcnow() + datetime.timedelta(seconds=(60 + data['time_limit']))
            }).inserted_id
            game_created = mongo.db.games.find_one({"_id": game_id})
        except:
            return {'message': 'An error occured creating the Game'}, 500

        return json_util._json_convert(game_created), 201
Example #2
0
    def post(self):
        data = QuestionList.parser.parse_args()

        try:
            questions_created = []
            for question in data['questions']:
                question_id = mongo.db.questions.insert_one({
                    "question":
                    question['question'],
                    "A":
                    question['A'],
                    "B":
                    question['B'],
                    "C":
                    question['C'],
                    "D":
                    question['D'],
                    "answer":
                    question['answer']
                }).inserted_id
                question_created = mongo.db.questions.find_one(
                    {"_id": question_id})
                questions_created.append(
                    mongo.db.questions.find_one({"_id": question_id}))
        except:
            return {'message': 'An error occured creating the Questions'}, 500

        return json_util._json_convert({"questions": questions_created}), 201
Example #3
0
    def post(self):
        data = QuestionCreator.parser.parse_args()

        try:
            # try **data later
            question_id = mongo.db.questions.insert_one({
                "question":
                data['question'],
                "A":
                data['A'],
                "B":
                data['B'],
                "C":
                data['C'],
                "D":
                data['D'],
                "answer":
                data['answer']
            }).inserted_id
            question_created = mongo.db.questions.find_one(
                {"_id": question_id})
        except:
            return {'message': 'An error occured inserting the Question'}, 500

        return json_util._json_convert(question_created), 201
Example #4
0
    def get(self):
        try:
            requests = mongo.db.requests.find()
        except:
            return {"message": "there was an error looking up the resource requests"}

        return {"requests": json_util._json_convert(requests)}, 200
Example #5
0
    def get(self, id=None):

        if id is not None:
            room_info = self.db.room.find_one({"_id": ObjectId(id)})
            if room_info:
                return json_util._json_convert(room_info)

        return {"response": "no room found for {}".format(id)}
Example #6
0
	def get(self):
		client = MongoClient()
		db = client.devcoders
		users = db.users

		result = users.find()

		return {'Users':json_util._json_convert([i for i in result])},200
Example #7
0
    def get(self, _id):
        try:
            supply = mongo.db.supplies.find_one({"_id": ObjectId(_id)})
        except:
            return {"message": "An error occurred looking up the supply"}, 500

        if supply:
            return json_util._json_convert(supply), 200
        return {"message": "supply not found"}, 404
Example #8
0
    def get(self, _id):
        try:
            request = mongo.db.requests.find_one({"_id": ObjectId(_id)})
        except:
            return {"message": "An error occurred looking up the request"}, 500

        if request:
            return json_util._json_convert(request), 200
        return {"message": "request not found"}, 404
Example #9
0
    def get(self):
        try:
            questions = mongo.db.questions.find()
        except:
            return {
                'message': 'An error occured trying to look up these Questions'
            }, 500

        return json_util._json_convert(questions), 200
Example #10
0
def get():
    db = get_connection()['tgju']
    data = dict()
    for collection in db.collection_names():
        if collection == 'system.indexes':
            continue
        data[collection] = _json_convert(db[collection].find())

    return jsonify(**data)
    def test_arrange_list_happy_flow(self):
        """Test API can create a arrangement (POST request)"""

        res = self.app.get('http://127.0.0.1:5000/v1/arrange')

        data = json_util._json_convert(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertTrue(len(data) > 1)
Example #12
0
    def test_room_creation_unhappy_flow(self):
        """Test API can create a roomment (POST request)"""
        room = {"room": "roomment Test Title", "code": "ABC123"}

        res = self.app.post('http://127.0.0.1:5000/v1/room', data=room)

        data = json_util._json_convert(res.data)

        self.assertEqual(res.status_code, 400)
        self.assertEqual(data, str('{"_id": null}\n'))
Example #13
0
def check_manager(Particular_Date):
    Paticular_Day_Details = mongo.db.Testcase_Details
    Day_wise_Details = Paticular_Day_Details.find(
        {'TimeStamp': {
            '$regex': Particular_Date
        }})
    if Day_wise_Details:
        return jsonify({'result': json_util._json_convert(Day_wise_Details)})
    else:
        return jsonify({'result': 'no data found'})
Example #14
0
 def get(self, id):
     try:
         game = mongo.db.games.find_one({"_id": ObjectId(id)})
     except:
         return {
             'message': 'An error occured trying to look up this Game'
         }, 500
     if game:
         return json_util._json_convert(game), 200
     return {'message': 'Game not found'}, 404
 def get(self, id):
     prod = prods.find_one({'_id': ObjectId(id)})
     print(prod)
     auxP = prod
     auxOi = _json_convert(auxP["_id"])
     auxP["_id"] = auxOi["$oid"]
     prod = auxP
     data = {}
     data["product"] = prod
     return data
Example #16
0
    def get(self, _id):
        try:
            shipment = mongo.db.shipments.find_one({"_id": ObjectId(_id)})
        except:
            return {
                "message": "An error occurred looking up the shipment"
            }, 500

        if shipment:
            return json_util._json_convert(shipment), 200
        return {"message": "shipment not found"}, 404
Example #17
0
    def get(self, _id):
        try:
            provider = mongo.db.providers.find_one({"_id": ObjectId(_id)})
        except:
            return {
                "message": "An error occurred looking up the provider"
            }, 500

        if provider:
            return json_util._json_convert(provider), 200
        return {"message": "provider not found"}, 404
Example #18
0
    def get(self):
        try:
            providers = mongo.db.providers.find()
        except:
            return {
                "message": "An error occurred looking up all of the providers"
            }, 500

        if providers.count():
            return {"providers": json_util._json_convert(providers)}, 200
        return {"message": "No providers were found"}, 404
Example #19
0
    def get(self, _id):
        try:
            resource = mongo.db.resources.find_one({"_id": ObjectId(_id)})
        except:
            return {
                "message": "An error occurred looking up the Resource"
            }, 500

        if Resource:
            return json_util._json_convert(resource), 200
        return {"message": "resource not found"}, 404
Example #20
0
    def get(self, id):
        try:
            question = mongo.db.questions.find_one({"_id": ObjectId(id)})
        except:
            return {
                'message': 'An error occured trying to look up this Question'
            }, 500

        if question:
            return json_util._json_convert(question), 200
        return {'message': 'Question not found'}, 404
Example #21
0
    def get(self):
        try:
            resource = mongo.db.resources.find()
        except:
            return {
                "message": "An error occurred looking up all of the resource"
            }, 500

        if resource.count():
            return {"resource": json_util._json_convert(resource)}, 200
        return {"message": "No resource(s) were found"}, 404
Example #22
0
    def get(self, _id):
        try:
            hospital = mongo.db.hospitals.find_one({"_id": ObjectId(_id)})
        except:
            return {
                "message": "An error occurred looking up the hospital"
            }, 500

        if hospital:
            return json_util._json_convert(hospital), 200
        return {"message": "hospital not found"}, 404
Example #23
0
    def get(self):
        try:
            hospitals = mongo.db.hospitals.find()
        except:
            return {
                "message": "An error occurred looking up all of the hospitals"
            }, 500

        if hospitals.count():
            return {"hospitals": json_util._json_convert(hospitals)}, 200
        return {"message": "No hospitals were found"}, 404
Example #24
0
    def get(cls, username):
        try:
            # look for first document in users collection to have a username equal to ata['username']
            user = mongo.db.users.find_one({"username": username})
        except:
            return {"message": "An error occurred looking up the user"}, 500

        if user:
            # return user converted to json
            return json_util._json_convert(user), 200
        return {"message": "user not found"}, 404
Example #25
0
 def default(self, obj):
     if isinstance(obj, BaseDocument):
         try:
             return neo_json_convert(obj.transform())
         except:
             return neo_json_convert(obj.to_mongo())
     elif isinstance(obj, QuerySet):
         return json_util._json_convert(obj.as_pymongo())
     elif isinstance(obj, ObjectId):
         return str(obj)
     else:
         return super(MongoEngineJSONEncoder, self).default(obj)
Example #26
0
def Weekly_Details():
    From_Date = request.json['from_Date']
    To_Date = request.json['to_Date']
    print(From_Date)
    p = From_Date.split("-")
    print(p[0])
    reslut = mongo.db.Testcase_Details.find(
        {"TimeStamp": {
            "$gt": From_Date,
            "$lt": To_Date
        }})
    result = json_util._json_convert(reslut)
    return jsonify({'result': result})
 def get(self):
     prod = (list(prods.find().sort("productName", pymongo.ASCENDING)))
     for i in range(len(prod)):
         auxP = prod[i]
         auxOi = _json_convert(auxP["_id"])
         auxP["_id"] = auxOi["$oid"]
         prod[i] = auxP
     if prod:
         data = {}
         data["products"] = prod
         data = dumps(data)
         resp = Response(data, status=200, mimetype='application/json')
         return resp
Example #28
0
def getDeviceInfo(id):
    deviceInfo = services.getDeviceInfo(id)
    filterDeviceInfo = list(
        map(
            lambda x:
            ({
                "fans": x['inventoryDetailsDTO']['fans'],
                "ipInterfaces": x['inventoryDetailsDTO']['ipInterfaces'],
                "sensors": x['inventoryDetailsDTO']['sensors'],
                "summary": x['inventoryDetailsDTO']['summary'],
                "powerSupplies": x['inventoryDetailsDTO']['powerSupplies']
            }), deviceInfo))
    return createResponse(json_util._json_convert(filterDeviceInfo))
Example #29
0
    def get(self, game_id):
        try:
            game = mongo.db.games.find_one({"_id": ObjectId(game_id)})
            print(game_id)
        except:
            return {
                'message': 'An error occured trying to look up this Game'
            }, 500

        if (game):
            players = mongo.db.players.find({'game_id': game_id})
            if (players):
                return json_util._json_convert(players), 200
        return {'message': 'Game not found'}, 404
Example #30
0
def get_test_result():
    project_id = request.args.get('pro_id', "")
    result_id = request.args.get('id', '')
    page_index = request.args.get('p', 1, type=int)
    page_size = request.args.get('ps', 30, type=int)
    tag = request.args.get('tag', None)
    if result_id:
        result_data = Result().get(result_id)
    elif not project_id:
        return json_response("", status='fail', error_msg='id required')
    else:
        result_data = Result().get_page(project_id, tag, page_index, page_size)
    result_data = json_util._json_convert(result_data)
    return json_response(result_data)
    def test_arrange_creation_unhappy_flow(self):
        """Test API can create a arrangement (POST request)"""
        arrange = {
            "title": "Arrangement Test Title",
            "room": "ABC123",
            "start_at": 1349960286,
            "end_at": 1349960286
        }

        res = self.app.post('http://127.0.0.1:5000/v1/arrange', data=arrange)

        data = json_util._json_convert(res.data)

        self.assertEqual(res.status_code, 400)
        self.assertEqual(data, str('{"_id": null}\n'))
Example #32
0
    def __init__(self, ensure_ascii=False, **kwargs):
        try:
            import simplejson as json
        except ImportError:
            import json
        finally:
            try:
                from bson.json_util import _json_convert
                dumps = lambda obj, *args, **kwargs: json.dumps(
                    _json_convert(obj), *args, **kwargs
                )
            except ImportError:
                dumps = json.dumps

        self.dumps = lambda obj: dumps(obj, ensure_ascii, **kwargs)
Example #33
0
def jsonify(obj, *args, **kwargs):
    """ jsonify with support for MongoDB ObjectId
    """
    return Response(dumps(_json_convert(obj),*args, **kwargs), mimetype='application/json')
Example #34
0
def basequeryset_adapter(obj, request):
    if isinstance(obj, BaseQuerySet):
        return json_util._json_convert(obj.as_pymongo())
Example #35
0
def basedocument_adapter(obj, request):
    if isinstance(obj, BaseDocument):
        return json_util._json_convert(obj.to_mongo())
Example #36
0
 def default(self,obj):
     if isinstance(obj,BaseDocument):
         return json_util._json_convert(obj.to_mongo())
     elif isinstance(obj,BaseQuerySet):
         return json_util._json_convert(obj.as_pymongo())
     return JSONEncoder.default(self, obj)
 def to_native(self, value):
     if value is not None:
         return json_util._json_convert(self.model_field.to_mongo(value))
Example #38
0
 def to_dict(self):
     return json_util._json_convert(self.to_mongo());
Example #39
0
 def default(self, obj):
     if isinstance(obj, BaseDocument):
         return json_util._json_convert(obj.to_mongo())
     elif isinstance(obj, QuerySet):
         return json_util._json_convert(obj.as_pymongo())
     return superclass.default(self, obj)