示例#1
0
 def get(self):
     response = {
         'status': {'href': url_for('status', _external=True)},
         'ire': {'href': url_for('ire', _external=True)},
         'cots': {'href': url_for('cots', _external=True)}
     }
     return response, 200
示例#2
0
    def get(self, gametype_name):
        #Check whether gametype exists
        db_gametype = GameType.query.filter_by(name=gametype_name).first()
        if db_gametype is None:
            return create_error_response(404, "Gametype not found")

        body = GametypeBuilder(name=gametype_name)
        min_players = db_gametype.min_players

        #Check whether game type has min_players or max_players set
        if min_players is not None:
            body["min_players"] = min_players
        max_players = db_gametype.max_players
        if max_players is not None:
            body["max_players"] = max_players
        body.add_namespace("gamescr", NAMESPACE_URL)
        body.add_control(
            "self", url_for("gametyperesource", gametype_name=gametype_name))
        body.add_control("profile", PROFILE_URL)
        body.add_control("collection", url_for("gametypecollection"))
        body.add_control_edit_gametype(name=gametype_name)
        body.add_control_leaderboard(name=gametype_name)
        body.add_control_delete_gametype(name=gametype_name)

        return Response(json.dumps(body), 200, mimetype=MASON)
示例#3
0
    def get(self):
        self.get_reqparse()

        args = self.reqparse.parse_args()
        page = args['page']
        size = args['size']

        _users = User.query.paginate(page, per_page=size, error_out=False)
        if page > _users.pages:
            abort(400, message="page no can't max than pages, no users data!", error_date=fmt_date(datetime.datetime.now()))
        if not _users.items:
            abort(404, message="no users data!", error_date=fmt_date(datetime.datetime.now()))

        users = {'users': map(lambda t: marshal(t, user_fields), _users.items), 'total': _users.total,
                 'base_url': request.url_root[:-1],
                 'link': {'rel': 'self', 'href': request.url},
                 'previous': url_for('users_ep', page=_users.prev_num, size=size),
                 'next': url_for('users_ep', page=_users.next_num, size=size)}

        if not _users.has_prev:
            users.pop('previous')
        if not _users.has_next:
            users.pop('next')

        return users, 200
    def setUp(self):

        self.maxDiff = None
        self.app = create_app(Config)
        self.app_context = self.app.test_request_context()
        self.app_context.push()
        db.drop_all()
        db.create_all()
        self.client = self.app.test_client()
        self.test_password = '******'

        self.user_data = {'username': '******', 'password': self.test_password, 'email': '*****@*****.**'}
        self.updated_user_data = {'username': '******', 'email': '*****@*****.**'}

        self.user1 = User(username='******', email='*****@*****.**', password=self.test_password)
        self.user2 = User(username='******', email='*****@*****.**', password=self.test_password)
        db.session.add_all([self.user1, self.user2])
        db.session.commit()

        self.user1_BAH = make_basic_auth_headers(self.user1.username, self.test_password)
        self.user2_BAH = make_basic_auth_headers(self.user2.username, self.test_password)

        response = self.client.post(url_for('api.auth_login'), headers=self.user1_BAH)
        access_token = json.loads(response.data)['access_token']
        self.user1_token_auth_headers = make_token_auth_headers(access_token)
        response = self.client.post(url_for('api.auth_login'), headers=self.user2_BAH)
        access_token = json.loads(response.data)['access_token']
        self.user2_token_auth_headers = make_token_auth_headers(access_token)
示例#5
0
    def get(self, game_name, player_name):
        db_game = Game.query.filter_by(game_token=game_name).first()
        if db_game is None:
            return create_error_response(
                404, "No game found with name " + str(game_name))
        db_player = Player.query.filter_by(name=player_name).first()
        if db_player is None:
            return create_error_response(
                404, "No player found with name " + str(player_name))
        db_player_score = PlayerScore.query.filter_by(player=db_player,
                                                      game=db_game).first()
        if db_player_score is None:
            return create_error_response(
                404, "No score found with player name " + str(player_name) +
                " and game name " + str(game_name))

        body = ScoreBuilder(name=db_player.name, game=db_game.game_token)
        if db_player_score.score is not None:
            body["score"] = db_player_score.score
        body.add_namespace("gamescr", NAMESPACE_URL)
        body.add_control(
            "self",
            url_for("playerscoreresource",
                    game_name=game_name,
                    player_name=player_name))
        body.add_control("profile", PROFILE_URL)
        body.add_control("collection",
                         url_for("gamescoreboard", game_name=game_name))
        body.add_control_edit_playerscore(game_name=game_name,
                                          player_name=player_name)
        body.add_control_delete_playerscore(game_name=game_name,
                                            player_name=player_name)
        body.add_control_player(player_name=player_name)

        return Response(json.dumps(body), 200, mimetype=MASON)
示例#6
0
    def get(self):
        items = []
        gametypes = GameType.query.all()

        for db_gametype in gametypes:
            name = db_gametype.name
            body = GametypeBuilder(name=name)
            max_players = db_gametype.max_players
            if max_players is not None:
                body["max_players"] = max_players
            min_players = db_gametype.min_players
            if min_players is not None:
                body["min_players"] = min_players

            #Controls for an item
            body.add_control("self",
                             url_for("gametyperesource", gametype_name=name))
            body.add_control("profile", PROFILE_URL)
            items.append(body)

        body = GametypeBuilder()
        #Controls for collection
        body.add_namespace("gamescr", NAMESPACE_URL)
        body.add_control("self", url_for("gametypecollection"))
        body.add_control_add_gametype()
        body.add_control_all_games()
        body["items"] = items

        return Response(json.dumps(body), 200, mimetype=MASON)
示例#7
0
    def get(self):
        self.get_reqparse()

        args = self.reqparse.parse_args()
        page = args['page']
        size = args['size']

        _users = User.query.paginate(page, per_page=size, error_out=False)
        if page > _users.pages:
            abort(400,
                  message="page no can't max than pages, no users data!",
                  error_date=fmt_date(datetime.datetime.now()))
        if not _users.items:
            abort(404,
                  message="no users data!",
                  error_date=fmt_date(datetime.datetime.now()))

        users = {
            'users': map(lambda t: marshal(t, user_fields), _users.items),
            'total': _users.total,
            'base_url': request.url_root[:-1],
            'link': {
                'rel': 'self',
                'href': request.url
            },
            'previous': url_for('users_ep', page=_users.prev_num, size=size),
            'next': url_for('users_ep', page=_users.next_num, size=size)
        }

        if not _users.has_prev:
            users.pop('previous')
        if not _users.has_next:
            users.pop('next')

        return users, 200
def pagination_links(pagination, resource, **args):
    nav_links = {}
    per_page = pagination.per_page
    this_page = pagination.page
    last_page = pagination.pages
    nav_links["self"] = url_for(resource,
                                **args,
                                page=this_page,
                                per_page=per_page)
    nav_links["first"] = url_for(resource, page=1, per_page=per_page)
    if pagination.has_prev:
        nav_links["prev"] = url_for(resource,
                                    **args,
                                    page=this_page - 1,
                                    per_page=per_page)

    if pagination.has_next:
        nav_links["next"] = url_for(resource,
                                    **args,
                                    page=this_page + 1,
                                    per_page=per_page)

    nav_links["last"] = url_for(resource,
                                **args,
                                page=last_page,
                                per_page=per_page)

    return nav_links
示例#9
0
文件: index.py 项目: woshilapin/kirin
 def get(self):
     response = {
         "health": {"href": url_for("health", _external=True)},
         "status": {"href": url_for("status", _external=True)},
         "contributors": {"href": url_for("contributors", _external=True)},
     }
     return response, 200
示例#10
0
 def to_json(self):
     json_completion = {
         'url': url_for('api.get_completion', id=self.id),
         'habit_url': url_for('api.get_habit', id=self.habit_id),
         'target_time': self.target_time,
         'completion_time': self.completion_time
     }
     return json_completion
示例#11
0
 def test_get_user_posts_token_auth_required(self):
     response = self.client.get(
         url_for('api.post_list', user_id=self.user1.id))
     self.assertEqual(response.status_code, 401)
     response = self.client.get(url_for('api.post_list',
                                        user_id=self.user1.id),
                                headers=self.user1_token_auth_headers)
     self.assertEqual(response.status_code, 200)
示例#12
0
 def image_to_json(self, img: tuple) -> dict:
     id, name, date = img
     return {
         'name': name,
         'time': date.strftime("%Y-%m-%d %H:%M:%S"),
         'file_url': url_for('bp.itemfile', file_name=name),
         'comm_url': url_for('bp.comments', image_id=id)
     }
示例#13
0
文件: order.py 项目: io112/sem-trade
 def __init__(self):
     self.api_urls = {
         "API_ORDER_GET": url_for('order_api.Order'.lower()),
         "API_ORDER_MAKE_OP": url_for('order_api.Order'.lower()),
         "API_ORDER_BILL_GET": url_for('order_api.OrderBill'.lower()),
         "API_ORDER_UPD_GET": url_for('order_api.OrderUpd'.lower()),
         "API_ORDER_UPD_SET": url_for('order_api.OrderUpd'.lower()),
     }
示例#14
0
 def paginate_by_account(cls, name, page):
     paginate = cls.find_by_account(name).paginate(page, 5, False)
     next_url = url_for('api.post_account_list',
                        page=paginate.next_num,
                        name=name) if paginate.has_next else None
     prev_url = url_for('api.post_account_list',
                        page=paginate.prev_num,
                        name=name) if paginate.has_prev else None
     return {'posts': paginate.items, 'next': next_url, 'prev': prev_url}
示例#15
0
 def paginate_by_category(cls, category, page):
     paginate = cls.find_by_category(category).paginate(page, 5, False)
     next_url = url_for('api.post_category_list',
                        page=paginate.next_num,
                        category=category) if paginate.has_next else None
     prev_url = url_for('api.post_category_list',
                        page=paginate.prev_num,
                        category=category) if paginate.has_prev else None
     return {'posts': paginate.items, 'next': next_url, 'prev': prev_url}
 def test_delete_user(self):
     response = self.client.delete(
         url_for('api.user_detail', user_id=self.user1.id),
         headers=self.user1_token_auth_headers)
     self.assertEqual(response.status_code, 200)
     response = self.client.get(
         url_for('api.user_detail', user_id=self.user1.id),
         headers=self.user2_token_auth_headers)
     self.assertEqual(response.status_code, 404)
示例#17
0
 def paginate(cls, page):
     paginate = cls.find_all_active().paginate(page, 5, False)
     next_url = url_for(
         'api.post_list',
         page=paginate.next_num) if paginate.has_next else None
     prev_url = url_for(
         'api.post_list',
         page=paginate.prev_num) if paginate.has_prev else None
     return {'posts': paginate.items, 'next': next_url, 'prev': prev_url}
示例#18
0
    def get(self, batch_id):
        """
        Retrieves the state of batch *batch_id*.

        ** Request **

        .. sourcecode:: http

            GET /batch/:batch_id

        ** Response **

        .. sourcecode:: http

            HTTP/1.1 200 OK

        :param batch_id: batch identifier
        :type batch_id: string
        :status 200: No error
        :status 404: No such batch
        """
        log.debug('Routing to batch {} (GET)'.format(batch_id))
        res = {}
        try:
            batch = nBatch(batch_id)
        except NidabaInputException:
            return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
        except:
            return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
        res['pages'] = url_for('api.batchpages', batch_id=batch_id)
        res['tasks'] = url_for('api.batchtasks', batch_id=batch_id)
        if batch.is_running():
            res['chains'] = batch.get_extended_state()

            # replace all document tuples with URLs to the page resource
            def replace_docs(state):
                for k in state.keys():
                    if k in ['root_documents', 'result', 'doc']:
                        if state[k] is not None and isinstance(
                                state[k][0], list):
                            docs = []
                            for doc in state[k]:
                                docs.append(
                                    url_for('api.page',
                                            batch=doc[0],
                                            file=doc[1]))
                            state[k] = docs
                        elif state[k] is not None:
                            state[k] = url_for('api.page',
                                               batch=state[k][0],
                                               file=state[k][1])
                    if isinstance(state[k], dict):
                        replace_docs(state[k])

            replace_docs(res['chains'])
        return res, 200
示例#19
0
    def output(self, key, obj):
        properties = {}
        if isinstance(obj, dict) and 'properties' in obj:
            for property in obj['properties']:
                properties.setdefault(property['type'], []).append(
                    {
                        'value': property['value'],
                        'property': {
                            'id': property['id'],
                            'created_at': FieldDateTime().format(
                                property['created_at']
                            ),
                            'updated_at': FieldDateTime().format(
                                property['updated_at']
                            ),
                            'self': {
                                'href': url_for(
                                    'property',
                                    id=property['id'],
                                    _external=True
                                )
                            },
                            'key': property['key'],
                            'type': property['type']
                        }
                    }
                )

            return properties
        elif obj.properties:
            for property in obj.properties:
                prop = property.property
                properties.setdefault(prop.type, []).append(
                    {
                        'value': property.value,
                        'property': {
                            'id': prop.id,
                            'created_at': FieldDateTime().format(
                                prop.created_at
                            ),
                            'updated_at': FieldDateTime().format(
                                prop.updated_at
                            ),
                            'self': {
                                'href': url_for(
                                    'property',
                                    id=prop.id,
                                    _external=True
                                )
                            },
                            'key': prop.key,
                            'type': prop.type
                        }
                    }
                )
        return properties
示例#20
0
文件: fields.py 项目: CanalTP/Chaos
    def output(self, key, obj):
        properties = {}
        if isinstance(obj, dict) and 'properties' in obj:
            for property in obj['properties']:
                properties.setdefault(property['type'], []).append(
                    {
                        'value': property['value'],
                        'property': {
                            'id': property['id'],
                            'created_at': FieldDateTime().format(
                                property['created_at']
                            ),
                            'updated_at': FieldDateTime().format(
                                property['updated_at']
                            ),
                            'self': {
                                'href': url_for(
                                    'property',
                                    id=property['id'],
                                    _external=True
                                )
                            },
                            'key': property['key'],
                            'type': property['type']
                        }
                    }
                )

            return properties
        elif obj.properties:
            for property in obj.properties:
                prop = property.property
                properties.setdefault(prop.type, []).append(
                    {
                        'value': property.value,
                        'property': {
                            'id': prop.id,
                            'created_at': FieldDateTime().format(
                                prop.created_at
                            ),
                            'updated_at': FieldDateTime().format(
                                prop.updated_at
                            ),
                            'self': {
                                'href': url_for(
                                    'property',
                                    id=prop.id,
                                    _external=True
                                )
                            },
                            'key': prop.key,
                            'type': prop.type
                        }
                    }
                )
        return properties
示例#21
0
    def get(self, user_id):
        """Retrieve a complete list of all Collections created by a user.

        Yields:
            Identify a User object against a User model via username (id).
            jsonify a Query object to the Collections database of all
            Collection objects with field `owner` equal to the User
            model via unique username and/or id.

        Returns:
            [{dict}]: JSON Flask Response
            A complete list of Snippet objects, with all nested fields
            dereferenced.
        Note:
            This endpoint is the primary endpoint for fetching User's
            Snippets profile.
        """

        user = User.objects.get(username=user_id)
        collections = Collection.objects(owner=user).order_by("-date")

        response = [
            {
                "_id": str(ObjectId(doc["id"])),
                "name": doc["name"],
                "owner": doc["owner"]["username"],
                "private": doc["private"],
                "url": url_for(
                    "mycollectionapi", user_id=user_id, id=str(ObjectId(doc["id"]))
                ),
                "snippets": [
                    {
                        "_id": str(ObjectId(k["id"])),
                        "title": k["title"],
                        "filename": k["filename"],
                        "description": k["description"],
                        "language": k["language"],
                        "value": k["value"],
                        "addedBy": k["addedBy"]["username"],
                        "likedBy": [elem["username"] for elem in k["likedBy"]],
                        "tags": k["tags"],
                        "addedOn": k["addedOn"],
                        "updatedOn": k["updatedOn"],
                        "private": k["private"],
                        "source": k["source"],
                        "url": url_for("snippetapi", id=str(ObjectId(doc["id"]))),
                    }
                    for k in doc["snippets"]
                ],
            }
            for doc in collections
        ]

        return jsonify(response)
示例#22
0
文件: api.py 项目: amitdo/nidaba
 def replace_docs(state):
     for k in state.keys():
         if k in ['root_document', 'result', 'doc']:
             if state[k] is not None and isinstance(state[k][0], list):
                 docs = []
                 for doc in state[k]:
                     docs.append(url_for('api.page', batch=doc[0], file=doc[1]))
                 state[k] = docs
             elif state[k] is not None:
                 state[k] = url_for('api.page', batch=state[k][0], file=state[k][1])
         if isinstance(state[k], dict):
             replace_docs(state[k])
示例#23
0
文件: api.py 项目: lxj0276/nidaba
 def replace_docs(state):
     for k in state.keys():
         if k in ['root_documents', 'result', 'doc']:
             if state[k] is not None and isinstance(state[k][0], list):
                 docs = []
                 for doc in state[k]:
                     docs.append(url_for('api.page', batch=doc[0], file=doc[1]))
                 state[k] = docs
             elif state[k] is not None:
                 state[k] = url_for('api.page', batch=state[k][0], file=state[k][1])
         if isinstance(state[k], dict):
             replace_docs(state[k])
示例#24
0
    def get(self, id):
        """Retrieve a complete list of all Snippets `liked` by a user.

        Yields:
            Identify a User object against a User model via username.
            jsonify a Query object to the Snippets database of all
            Snippet objects with a `likedBy` list field that includes the
            User.

        Returns:
            [{dict}]: JSON Flask Response
            A complete list of Snippet objects, with all nested fields
            dereferenced.
        Note:
            This API response is modeled to be received as a Collection object,
            even though it is a pure computation of values in nested document
            fields. This is done to simplofy frontend handlers as the `Faves`
            endpoint's UI is rendered as a unique `collection`.

        """
        user = User.objects.get(username=id)
        snips = Snippet.objects(likedBy=user)
        response = [
            {
                "_id": "faves",
                "name": "Faves",
                "owner": id,
                "private": False,
                "url": url_for("myfavesnippetsapi", id=id),
                "snippets": [
                    {
                        "_id": str(ObjectId(k["id"])),
                        "title": k["title"],
                        "filename": k["filename"],
                        "description": k["description"],
                        "language": k["language"],
                        "value": k["value"],
                        "addedBy": k["addedBy"]["username"],
                        "likedBy": [elem["username"] for elem in k["likedBy"]],
                        "tags": k["tags"],
                        "addedOn": k["addedOn"],
                        "updatedOn": k["updatedOn"],
                        "private": k["private"],
                        "source": k["source"],
                        "url": url_for("myfavesnippetsapi", id=user),
                    }
                    for k in snips
                ],
            }
        ]

        return jsonify(response)
 def test_update_user_token_auth_required(self):
     response = self.client.put(
         url_for('api.user_detail', user_id=self.user1.id),
         headers={},
         data=json.dumps(self.updated_user_data),
         content_type='application/json')
     self.assertEqual(response.status_code, 401)
     response = self.client.put(
         url_for('api.user_detail', user_id=self.user1.id),
         headers=self.user1_token_auth_headers,
         data=json.dumps(self.updated_user_data),
         content_type='application/json')
     self.assertEqual(response.status_code, 200)
示例#26
0
 def test_create_user_post_error_on_not_equal_user_id_in_post_data(self):
     response = self.client.post(url_for('api.post_list',
                                         user_id=self.user1.id),
                                 data=json.dumps(self.post_data2),
                                 headers=self.user1_token_auth_headers,
                                 content_type='application/json')
     self.assertEqual(response.status_code, 403)
     response = self.client.post(url_for('api.post_list',
                                         user_id=self.user1.id),
                                 data=json.dumps(self.post_data1),
                                 headers=self.user1_token_auth_headers,
                                 content_type='application/json')
     self.assertEqual(response.status_code, 201)
 def test_update_user_on_email_already_used(self):
     response = self.client.put(
         url_for('api.user_detail', user_id=self.user1.id),
         headers=self.user1_token_auth_headers,
         data=json.dumps({'email': self.user2.email}),
         content_type='application/json')
     self.assertEqual(response.status_code, 400)
     self.assertIn(exceptions.EmailAddressAlreadyUsed.description,
                   str(response.data))
     response = self.client.put(
         url_for('api.user_detail', user_id=self.user1.id),
         headers=self.user1_token_auth_headers,
         data=json.dumps({'email': '*****@*****.**'}),
         content_type='application/json')
     self.assertEqual(response.status_code, 200)
示例#28
0
 def put(self, id):
     args = self.reqparse.parse_args()
     query = models.Course.update(**args).where(models.Course.id == id)
     query.execute()
     return (add_reviews(models.Course.get(models.Course.id == id)), 200, {
         'Location': url_for('resources.courses.course', id=id)
     })
示例#29
0
    def put(self, player_name):
        if not request.json:
            return create_error_response(415, "Unsupported Media Type", "use JSON")
            
        db_player = Player.query.filter_by(name=player_name).first()
        if db_player is None:
            return create_error_response(404, "Player not found")
        try: 
            validate(request.json, PlayerBuilder.playerSchema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))
        
        new_name = request.json["name"]
        #If the new name already in use, return 409
        if new_name != player_name:
            db_player_new_name = Player.query.filter_by(name=new_name).first()
            if db_player_new_name is not None:
                return create_error_response(409, "Alredy exists", "Player already exists with name " + str(new_name))
        db_player.name = new_name
        db.session.add(db_player)
        db.session.commit()

        #Return the location in the header in case the name changes
        return Response(status=201, headers={
            "Location": url_for("playerresource", player_name=new_name)
        })
示例#30
0
 def _handle_view(self, name, **kwargs):
     """ Override builtin _handle_view to redirect users """
     if not self.is_accessible():
         if current_user.is_authenticated:
             abort(hcodes.HTTP_BAD_FORBIDDEN)  # permission denied
         else:  # login
             return redirect(url_for('security.login', next=request.url))
示例#31
0
def setup_channel(profile_id):
    service = build_service_from_id(profile_id)

    from .api import CalendarEvent

    body = {
        'id':
        uuid.uuid4().hex,
        'token':
        app.config['API_TOKEN'],
        'type':
        'web_hook',
        'address':
        url_for(CalendarEvent.endpoint,
                profile_id=profile_id,
                _external=True,
                _scheme='https'),
        'params': {
            'ttl': '2592000'  # 30 days, maximum allowed
        }
    }

    res = service.events().watch(calendarId='primary', body=body).execute()

    expiration = int(res['expiration']) // 1000
    redis.zadd('schedule', expiration, profile_id)

    return res
示例#32
0
 def post(self):
     """用户登录
     @@@
     #### args
         json
         {
             "login_id":"a",
             "password":"******"
         }
     #### return
         json
         {
            "code": 200,
            "msg": "login successful!",
            "data":
             {
                 "id": user_id,
                 "login_id": login_id
             },
            "token": token
         }
     @@@
     """
     return {
         "code": 200,
         "msg": "login successful!",
         "data": {
             "id": g.user.user_id,
             "login_id": g.user.login_id
         },
         "token": g.user.generate_auth_token().decode("ascii")
     }, {
         "Location": url_for("api.User", id=g.user.user_id, _external=True)
     }
示例#33
0
文件: fields.py 项目: Tisseo/Chaos
 def output(self, key, obj):
     properties = {}
     if obj.properties:
         for property in obj.properties:
             prop = property.property
             properties.setdefault(prop.type, []).append(
                 {
                     'value': property.value,
                     'property': {
                         'id': prop.id,
                         'created_at': FieldDateTime().format(
                             prop.created_at
                         ),
                         'updated_at': FieldDateTime().format(
                             prop.updated_at
                         ),
                         'self': {
                             'href': url_for(
                                 'property',
                                 id=prop.id,
                                 _external=True
                             )
                         },
                         'key': prop.key,
                         'type': prop.type
                     }
                 }
             )
     return properties
示例#34
0
 def post(self):
     args = self.reqparse.parse_args()
     subject = models.Subject.create(**args)
     return (findCourses(subject), 201, {
         'Location':
         url_for('resources.subjects.subject', id=subject.id)
     })
示例#35
0
    def get(self, player_name):
        db_player = Player.query.filter_by(name=player_name).first()
        if db_player is None:
            return create_error_response(404, "Player not found")
        body = PlayerBuilder(
                name = player_name
            )
        body.add_namespace("gamescr", NAMESPACE_URL)
        body.add_control("self", url_for("playerresource", player_name=player_name))
        body.add_control("profile", PROFILE_URL)
        body.add_control("collection", url_for("playercollection"))
        body.add_control_edit_player(name=player_name)
        body.add_control_leaderboard(name=player_name)
        body.add_control_delete_player(name=player_name)

        return Response(json.dumps(body), 200, mimetype=MASON)
示例#36
0
文件: api.py 项目: amitdo/nidaba
    def post(self):
        """
        Creates a new batch and returns it identifier.

        ** Request **
    
        .. sourcecode:: http
    
            POST /batch
    
        ** Response **
    
        .. sourcecode:: http
    
            HTTP/1.1 201 CREATED

            {
                "id": "78a1f1e4-cc76-40ce-8a98-77b54362a00e", 
                "url": "/batch/78a1f1e4-cc76-40ce-8a98-77b54362a00e"
            }
    
        :status 201: Successfully created
        """
        log.debug('Routing to batch with POST')
        batch = SimpleBatch()
        data = {'id': batch.id, 'url': url_for('api.batch', batch_id=batch.id)}
        log.debug('Created batch {}'.format(batch.id))
        return data, 201
示例#37
0
文件: api.py 项目: amitdo/nidaba
    def get(self, batch_id):
        """
        Retrieves the state of batch *batch_id*.
    
        ** Request **
    
        .. sourcecode:: http
    
            GET /batch/:batch_id
    
        ** Response **
    
        .. sourcecode:: http
    
            HTTP/1.1 200 OK

        :param batch_id: batch identifier
        :type batch_id: string
        :status 200: No error
        :status 404: No such batch
        """
        log.debug('Routing to batch {} (GET)'.format(batch_id))
        res = {}
        try:
            batch = SimpleBatch(batch_id)
        except:
            return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
        res['pages'] = url_for('api.batchpages', batch_id=batch_id)
        res['tasks'] = url_for('api.batchtasks', batch_id=batch_id)
        if batch.is_running():
            res['chains'] = batch.get_extended_state()
            # replace all document tuples with URLs to the page resource
            def replace_docs(state):
                for k in state.keys():
                    if k in ['root_document', 'result', 'doc']:
                        if state[k] is not None and isinstance(state[k][0], list):
                            docs = []
                            for doc in state[k]:
                                docs.append(url_for('api.page', batch=doc[0], file=doc[1]))
                            state[k] = docs
                        elif state[k] is not None:
                            state[k] = url_for('api.page', batch=state[k][0], file=state[k][1])
                    if isinstance(state[k], dict):
                        replace_docs(state[k])
            replace_docs(res['chains'])
        return res, 200
示例#38
0
文件: fields.py 项目: CanalTP/Chaos
    def output(self, key, obj):
        if isinstance(obj, dict) and 'disruption_id' in obj:
            disruption_id = obj['disruption_id']
        else:
            disruption_id = obj.disruption_id

        return {'href': url_for('disruption',
                                id=disruption_id,
                                _external=True)}
示例#39
0
 def post(self):
     """POST: Creates a new TODO."""
     args = self.reqparse.parse_args()
     try:
         todo = models.Todo.create(**args)
     except Exception as error:
         return {"message": str(error)}, 400
     else:
         return (marshal(todo, todo_fields), 201, {
             'Location': url_for('resources.todos.todo', todo_id=todo.id)})
示例#40
0
文件: utils.py 项目: zayng/myApp
def query_page(pagination, endpoint_name, page, envelope, **kwargs):
    obj_items = pagination.items
    count = pagination.total
    if count == 0:
        return {'message': "Query collection is empty!"}
    if count < 6:
        return {envelope: [item.to_dict() for item in obj_items], 'count': pagination.total}

    prev_page = None
    if pagination.has_prev:
        prev_page = url_for(endpoint_name, page=page - 1, _external=True, **kwargs)
    next_page = None
    if pagination.has_next:
        next_page = url_for(endpoint_name, page=page + 1, _external=True, **kwargs)

    return {envelope: [item.to_dict() for item in obj_items],
            'prev': prev_page,
            'next': next_page,
            'count': pagination.total
            }
示例#41
0
文件: api.py 项目: amitdo/nidaba
    def post(self, batch_id):
        """
        Adds a page (really any type of file) to the batch identified by
        *batch_id*.

        ** Request **

            POST /batch/:batch/pages

        ** Response **

            HTTP/1.1 201 OK
            
            [
                {
                    "name": "0033.tif", 
                    "url": "/pages/63ca3ec7-2592-4c7d-9009-913aac42535d/0033.tif"
                }
            ]

        :form scans: file(s) to add to the batch

        :status 201: task created
        :status 403: file couldn't be created
        :status 404: batch not found
        """
        args = self.parser.parse_args()
        log.debug('Routing to pages {} of {} (POST)'.format(
                    [x.filename for x in args['scans']], batch_id))
        try:
            batch = SimpleBatch(batch_id)
        except:
            return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
        data = []
        for file in args['scans']:
            try:
                fp = storage.StorageFile(batch_id, file.filename, 'wb')
            except NidabaStorageViolationException as e:
                log.debug('Failed to write file {}'.format(file.filename),
                          exc_info=True)
                return {'message': str(e)}, 403
            else:
                with fp:
                    file.save(fp)
                    file.close()
                    if args['auxiliary'] is False:
                        log.debug('Adding {}/{} to {}'.format(fp.storage_path[0], 
                                                              fp.storage_path[1],
                                                              batch_id))
                        batch.add_document(fp.storage_path)
            data.append({'name': file.filename,
                         'url': url_for('api.page', batch=batch_id, file=file.filename)})
        return data, 201
示例#42
0
文件: api.py 项目: amitdo/nidaba
 def arg_conversion(s):
     # JSON does not support booleans
     if s in ['True', 'true']:
         return True
     elif s in ['False', 'false']:
         return False
     # XXX: find a nicer way to rewrite page URLs
     base_url = url_for('api.page', batch=batch_id, file='')
     if isinstance(s, basestring) and s.startswith(base_url):
         rem = s.replace(base_url, '', 1)
         return (batch_id, rem)
     return s
示例#43
0
 def delete(self, id):
     try:
         review = models.Review.select().where(
             models.Review.created_by == g.user,
             models.Review.id == id
         ).get()
     except models.Review.DoesNotExist:
         return make_response(json.dumps(
             {'error': 'That review does not exist or is not editable'}
         ), 403)
     query = review.delete()
     query.execute()
     return '', 204, {'Location': url_for('resources.reviews')}
示例#44
0
 def put(self, todo_id):
     """PUT: Updates a single TODO."""
     args = self.reqparse.parse_args()
     cleaned_args = {key: value for (key, value) in args.items()
                     if value is not None}
     query = models.Todo.update(**cleaned_args).where(
         models.Todo.id == todo_id)
     try:
         query.execute()
     except Exception as error:
         return {"message": str(error)}, 400
     return (marshal(todo_or_404(todo_id), todo_fields), 200,
             {"Location": url_for('resources.todos.todo', todo_id=todo_id)})
示例#45
0
    def put(self, id):
        args = self.reqparse.parse_args()
        try:
            review = models.Review.select().where(
                models.Review.created_by == g.user,
                models.Review.id == id
            ).get()
        except models.Review.DoesNotExist:
            return make_response(json.dumps(
                {'error': 'That review does not exist or is not editable'}
            ), 403)

        query = review.update(**args)
        query.execute()
        review = add_restaurant(review_or_404(id))
        return review, 200, {'Location': url_for('resources.reviews.review', id=id)}
示例#46
0
def get_url(jobID, *paths):
    """
    Returns the URL on the api server for a file tuple.
    Args:
        jobID (unicode): A unique job ID
        *path (unicode): A list of path components that are concatenated to
        calculate the absolute path.

    Returns:
        (unicode): A string containing the absolute path of the storage tuple.
    """
    from nidaba import api
    app = api.create_app()
    app.config['SERVER_NAME'] = nidaba_cfg['nidaba_server']
    with app.app_context():
        return url_for('api.page', batch=jobID, file=os.path.join(*paths))
    raise NidabaStorageViolationException('Invalid path')
示例#47
0
文件: api.py 项目: amitdo/nidaba
    def get(self, batch_id):
        """
        Returns the list of pages associated with the batch with *batch_id*.

        ** Request **
    
        .. sourcecode:: http
    
            GET /batch/:batch/pages
    
        ** Response **
    
        .. sourcecode:: http
    
            HTTP/1.1 200 OK

            [
                {
                    "name": "0033.tif", 
                    "url": "/pages/63ca3ec7-2592-4c7d-9009-913aac42535d/0033.tif"
                }, 
                {
                    "name": "0072.tif", 
                    "url": "/pages/63ca3ec7-2592-4c7d-9009-913aac42535d/0072.tif"
                }, 
                {
                    "name": "0014.tif", 
                    "url": "/pages/63ca3ec7-2592-4c7d-9009-913aac42535d/0014.tif"
                }
            ]

        :status 200: success
        :status 404: batch not found
        """
        log.debug('Routing to pages of {} (GET)'.format(batch_id))
        try:
            batch = SimpleBatch(batch_id)
        except:
            return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
        data = []
        for doc in batch.get_documents():
            data.append({'name': doc[1],
                         'url': url_for('api.page', batch=doc[0], file=doc[1])})
        return data, 200
示例#48
0
文件: api.py 项目: amitdo/nidaba
  def post(self, batch_id):
      """
      Executes batch with identifier *batch_id*
  
      ** Request **
  
      .. sourcecode:: http
  
          POST /batch/:batch_id
  
      ** Response **
  
      .. sourcecode:: http
  
          HTTP/1.1 202 ACCEPTED
 
      :param batch_id: batch's unique id
      :type batch_id: string 
      :status 202: Successfully executed
      :status 400: Batch could not be executed
      :status 404: No such batch
      :status 409: Trying to reexecute an already executed batch
      """
      log.debug('Routing to batch {} (POST)'.format(batch_id))
      try:
          batch = SimpleBatch(batch_id)
      except:
          log.debug('Batch {} not found'.format(batch_id))
          return {'message': 'Batch Not Found: {}'.format(batch_id)}, 404
      if batch.get_state() == 'NONE':
          try:
              batch.run()
              return {'id': batch_id, 'url': url_for('api.batch', batch_id=batch_id)}, 202
          except:
              log.debug('Batch {} could not be executed'.format(batch_id), exc_info=True)
              return {'message': 'Batch could not be executed'}, 400
      else:
          log.debug('Batch {} already executed'.format(batch_id))
          return {'message': 'Batch already executed'}, 409
示例#49
0
def setup_channel(profile_id):
    service = build_service_from_id(profile_id)

    from .api import CalendarEvent

    body = {
        'id': uuid.uuid4().hex,
        'token': app.config['API_TOKEN'],
        'type': 'web_hook',
        'address': url_for(CalendarEvent.endpoint,
                           profile_id=profile_id,
                           _external=True,
                           _scheme='https'),
        'params': {
            'ttl': '2592000'  # 30 days, maximum allowed
        }
    }

    res = service.events().watch(calendarId='primary', body=body).execute()

    expiration = int(res['expiration']) // 1000
    redis.zadd('schedule', expiration, profile_id)

    return res
示例#50
0
 def post(self):
     args = self.reqparse.parse_args()
     restaurant = models.Restaurant.create(**args)
     return restaurant, 201, {'Location': url_for('resources.restaurants.restaurant', id=restaurant.id)}
示例#51
0
def add_restaurant(review):
    review.for_restaurant = url_for('resources.restaurants.restaurant', id=review.restaurant.id)
    return review
示例#52
0
 def get(self):
     response = {
         'status': {'href': url_for('status', _external=True)},
         'ire': {'href': url_for('ire', _external=True)}
     }
     return response, 200
示例#53
0
 def to_dict(self):
     dict = self.delugetorrent.to_dict()
     dict.update({'_link': url_for('TorrentEntityResource', id=self.delugetorrent.id)})
     return dict
示例#54
0
 def delete(self, todo_id):
     """DELETE: Deletes a single TODO."""
     todo = todo_or_404(todo_id)
     todo.delete_instance()
     return '', 204, {'Location': url_for('resources.todos.todos')}
示例#55
0
 def delete(self, id):
     query = models.Restaurant.delete().where(models.Restaurant.id == id)
     query.execute()
     return '', 204, {'Location': url_for('resources.restaurants')}
示例#56
0
 def put(self, id):
     args = self.reqparse.parse_args()
     query = models.Restaurant.update(**args).where(models.Restaurant.id == id)
     query.execute()
     return models.Restaurant.get(models.Restaurant.id == id), 200, {'Location': url_for('resources.restaurants.restaurant', id=id)}
示例#57
0
def add_reviews(restaurant):
    restaurant.reviews = [url_for('resources.reviews.review', id=review.id)
                            for review in restaurant.review_set]
    return restaurant
def index():
    return redirect(url_for('static', filename='index.html'))
示例#59
0
文件: fields.py 项目: Tisseo/Chaos
 def output(self, key, obj):
     return {'href': url_for('disruption',
                             id=obj.disruption_id,
                             _external=True)}