예제 #1
0
def show_request_result(request_result):
    """Translates a :any:`RequestResult` to a string suitable for logging."""
    rr = request_result
    parts = []
    log = parts.append

    def _indent(s):
        """Adds extra spaces to the beginning of every newline."""
        indent_str = "  "
        return ("\n" + indent_str).join(s.split("\n"))

    if rr.query:
        query_string = "?" + "&".join(
            ("%s=%s" % (k, v) for k, v in sorted(rr.query.items())))
    else:
        query_string = ""

    log("Fauna %s /%s%s\n" % (rr.method, rr.path, query_string))
    if rr.request_content is not None:
        log("  Request JSON: %s\n" %
            _indent(to_json(rr.request_content, pretty=True)))
    log("  Response headers: %s\n" %
        _indent(to_json(dict(rr.response_headers), pretty=True)))
    log("  Response JSON: %s\n" %
        _indent(to_json(rr.response_content, pretty=True)))
    log("  Response (%i): Network latency %ims\n" %
        (rr.status_code, int(rr.time_taken * 1000)))

    return u"".join(parts)
예제 #2
0
    def put(self, post_id):
        request_json = request.get_json()

        data = {}
        data['id'] = request_json['id']

        if "title" in request_json:
            data['title'] = request_json['title']
        if "tags" in request_json:
            data['tags'] = request_json['tags']

        query = q.create(q.class_expr("posts"), data)

        try:
            result = client.query(query)
        except fauna_error.NotFound as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to update post ' + data['id'] +
                                    ' - post not found.'),
                            status=404,
                            mimetype='application/json')
        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to update post ' + data['id'] +
                                    '.'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=201,
                        mimetype='application/json')
예제 #3
0
 def _perform_request(self, action, path, data, query, headers):
     """Performs an HTTP action."""
     url = self.base_url + "/" + path
     req = Request(action,
                   url,
                   params=query,
                   data=to_json(data),
                   auth=self.auth,
                   headers=headers)
     return self.session.send(self.session.prepare_request(req))
예제 #4
0
 async def _perform_request(self, action, path, data, query, headers):
     """Performs an HTTP action."""
     url = self.base_url + "/" + path
     data = to_json(data) if data else None
     resp = await self.session.request(action,
                                       url,
                                       params=query,
                                       data=data,
                                       auth=self.auth,
                                       headers=headers)
     return resp
예제 #5
0
    def post(self, post_title=None):
        json = request.get_json()
        data = []

        # validate and format incoming data
        if not "posts" in json:

            # if "posts" has been omitted and this is just a list of post data, reformat
            if isinstance(json, list) and "title" in json[0]:
                json = {"posts": json}
            elif not isinstance(json, list) and "title" in json:
                json_list = []
                json_list.append(json)
                json = {"posts": json_list}
            else:
                app.logger.debug(json)
                return Response(jsonify('Invalid post information.'),
                                status=422,
                                mimetype='application/json')

        for post in json['posts']:
            if not "title" in post:
                return Response(jsonify('Missing title in post.'),
                                status=422,
                                mimetype='application/json')

            data.append({"title": post['title'], "tags": post.get('tags', [])})

        query = q.map_expr(
            lambda post_data: q.create(q.class_expr("posts"),
                                       {"data": {
                                           "title": post_data
                                       }}), data)

        try:
            result = client.query(query)
        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to create post(s).'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=200,
                        mimetype='application/json')
예제 #6
0
    def delete(self, post_id):
        try:
            post_id = post_id.encode('ascii', 'ignore')
            result = client.query(q.delete(q.ref(q.class_("posts"), post_id)))
        except fauna_error.NotFound as e:
            app.logger.debug(e)
            return Response(
                jsonify('Failed to delete a post - post not found.'),
                status=404,
                mimetype='application/json')
        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to delete a post.'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=204,
                        mimetype='application/json')
예제 #7
0
    def get(self, post_title=None):
        try:
            if post_title:
                posts = client.query(
                    q.map_(
                        lambda x: q.get(x),
                        q.paginate(
                            q.match(q.index("posts_by_title"), post_title))))
            else:
                posts = client.query(
                    q.map_(lambda x: q.get(x),
                           q.paginate(q.match(q.index("all_posts")))))

        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to fetch posts.'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=200,
                        mimetype='application/json')
예제 #8
0
 def __init__(self, client, expression, options):
     self._client = client
     self.options = options
     self.conn = None
     self._fields = None
     if isinstance(self.options, dict):
         self._fields = self.options.get("fields", None)
     elif hasattr(self.options, "fields"):
         self._fields = self.options.field
     if isinstance(self._fields, list):
         union = set(self._fields).union(VALID_FIELDS)
         if union != VALID_FIELDS:
             raise Exception("Valid fields options are %s, provided %s." %
                             (VALID_FIELDS, self._fields))
     self._state = "idle"
     self._query = expression
     self._data = to_json(expression).encode()
     try:
         self.conn = HTTP20Connection(self._client.domain,
                                      port=self._client.port,
                                      enable_push=True)
     except Exception as e:
         raise StreamError(e)
예제 #9
0
 def assertToJson(self, obj, json):
     self.assertEqual(to_json(obj, sort_keys=True), json)
 def assertJson(self, obj, expected):
     self.assertEqual(to_json(obj, sort_keys=True), expected)