Пример #1
0
def server(filename):
    print filename

    storage_setup = current_app.config['storage']


    if 'local' in storage_setup and 'absolut_path' in storage_setup['local']:
            STORAGE = storage_setup['local']['absolut_path']
    else:
            STORAGE = '.'

    filename = filename.split('.')[0]

    node = CaliopeDocument.pull(filename)
    file = open(os.path.join(STORAGE, filename), 'rb')
    data = wrap_file(request.environ, file)
    headers = Headers()

    try:
        mimetype  = node.mimetype
    except:
        mimetype = 'application/octet-stream'

    rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
                                        direct_passthrough=False)
    return rv
Пример #2
0
def jsonify(*args, **kwargs):
    """flask.json.jsonify with cls=MongoJsonEncoder passed to flask.json.dumps

    Body copied from flask==1.0.2 (latest);
    """
    indent = None
    separators = (",", ":")

    if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
        indent = 2
        separators = (", ", ": ")

    if args and kwargs:
        raise TypeError(
            "jsonify() behavior undefined when passed both args and kwargs")
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators, cls=MongoJsonEncoder)
        + "\n",
        mimetype=current_app.config["JSONIFY_MIMETYPE"],
    )
Пример #3
0
def server(filename):
    print filename

    storage_setup = current_app.config['storage']

    if 'local' in storage_setup and 'absolut_path' in storage_setup['local']:
        STORAGE = storage_setup['local']['absolut_path']
    else:
        STORAGE = '.'

    filename = filename.split('.')[0]

    node = CaliopeDocument.pull(filename)
    file = open(os.path.join(STORAGE, filename), 'rb')
    data = wrap_file(request.environ, file)
    headers = Headers()

    try:
        mimetype = node.mimetype
    except:
        mimetype = 'application/octet-stream'

    rv = current_app.response_class(data,
                                    mimetype=mimetype,
                                    headers=headers,
                                    direct_passthrough=False)
    return rv
Пример #4
0
def jsonify(*args, **kwargs):
    indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
        and not request.is_xhr:
        indent = 2
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=indent),
        mimetype='application/json', content_type='application/json; charset=utf-8')
Пример #5
0
def image(shorturl=None):
    if shorturl :
        img = get_image(shorturl)
        if img :
            return current_app.response_class(img.image, mimetype=img.mimetype, direct_passthrough=False)
        else:
            abort(404)
    return render_template('index.html')
Пример #6
0
def image(shorturl=None):
    if shorturl :
        row = get_image(shorturl)
        if row :
            return current_app.response_class(row[0], mimetype=row[2], direct_passthrough=False)
        else:
            abort(404)
    return render_template('index.html')
Пример #7
0
def csvify(*args, **kwargs):
    """
    Creates a :class:`~flask.Response` with the CSV representation of the given arguments with an `text/csv` mimetype.

    Example usage::
 
        @app.route('/_get_logs')
        def get_current_user():
            return csvify(
                as_download=True,
                headers=['date', 'message'],
                rows=[
                    {
                        'date': '2012-12-12',
                        'message': 'foo'
                    },
                    {
                        'date': '2011-11-11',
                        'message': 'bar'
                    },
                ]
            )

    This will send a CSV file response like this to the client::

        date,message
        2012-12-12,foo
        2011-11-11,bar
    """
    headers = [str(header) for header in kwargs.pop('headers', [])]
    assert len(headers) > 0, 'Cannot write CSV without Headers!'
    rows = kwargs.pop('rows', [])

    def generateCsv():
        """Write the header and the iterate over the rows."""
        ##########################################################################
        # write the header
        yield '{}\n'.format(','.join(headers))
        ##########################################################################
        # Write the body of the document
        # ----> First generate the format string reused for each row in the csv
        #       file such that row_string = '{},{},{},{},...\n'
        row_string = u'{}\n'.format(u','.join([u'"{}"' for header in headers]))
        # ---> Then use that format string as the output to the next row
        for row in rows:
            # Get a value for each header, making sure to escape quotes and
            # normalize for unicode along the way
            csv_line = [_escapeQuotes(header, row) for header in headers]
            csv_line = row_string.format(*csv_line)
            yield unicodedata.normalize('NFKD', csv_line).encode('ascii', 'ignore')

    filename = kwargs.pop('filename', 'file.csv')
    as_download = kwargs.pop('as_download', False)
    response_headers = None
    if as_download:
        response_headers = Headers([('Content-Disposition', "attachment;filename={filename}".format(filename=filename))])

    return current_app.response_class(generateCsv(), mimetype='text/csv', headers=response_headers)
Пример #8
0
 def inner(*args, **kwargs):
     #            try:
     view_result = f(*args, **kwargs)
     json_resp = JsonResp.make_success_resp(view_result)
     #            except Exception, e:
     #                json_resp = JsonResp.make_failed_resp(500, e.message);
     return current_app.response_class(json.dumps(
         json_resp, indent=None if request.is_xhr else 2),
                                       mimetype='application/json')
Пример #9
0
def jsonify_list(array):
    """jsonify list object

    :param list array: jsonifed
    :return: Rseponse
    """
    indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
        indent = 2
    return current_app.response_class(dumps(array, indent=indent), mimetype='application/json')
Пример #10
0
 def handle(cls, errors):
     data_errors = [cls.format_openapi_error(err) for err in errors]
     data = {
         'errors': data_errors,
     }
     data_error_max = max(data_errors, key=lambda x: x['status'])
     status = data_error_max['status']
     return current_app.response_class(dumps(data),
                                       status=status,
                                       mimetype='application/json')
Пример #11
0
 def handle(cls, errors):
     data_errors = [cls.format_openapi_error(err) for err in errors]
     data = {
         "errors": data_errors,
     }
     data_error_max = max(data_errors, key=cls.get_error_status)
     status = data_error_max["status"]
     return current_app.response_class(dumps(data),
                                       status=status,
                                       mimetype="application/json")
Пример #12
0
        def inner(*args, **kwargs):
#            try:
            view_result = f(*args, **kwargs)
            json_resp = JsonResp.make_success_resp(view_result);
#            except Exception, e:
#                json_resp = JsonResp.make_failed_resp(500, e.message);
            return current_app.response_class(
                json.dumps(json_resp,
                           indent=None if request.is_xhr else 2),
                mimetype='application/json'
            );
Пример #13
0
 def inner(*args, **kwargs):
     view_result = f(*args, **kwargs)
     json_resp = JsonResp.make_success_resp(view_result)
     jsonp_resp = json.dumps(json_resp,
                             indent=None if request.is_xhr else 2)
     callback = request.args.get('callback', False)
     if callback:
         content = str(callback) + '(' + jsonp_resp + ')'
         mimetype = 'application/javascript'
         return current_app.response_class(content, mimetype=mimetype)
     else:
         return jsonp_resp
Пример #14
0
 def inner(*args, **kwargs):
     view_result = f(*args, **kwargs)
     json_resp = JsonResp.make_success_resp(view_result);
     jsonp_resp = json.dumps(json_resp,
                    indent=None if request.is_xhr else 2)
     callback = request.args.get('callback', False)
     if callback:
         content = str(callback) + '(' + jsonp_resp + ')'
         mimetype = 'application/javascript'
         return current_app.response_class(content, mimetype=mimetype)
     else:
         return jsonp_resp
Пример #15
0
def get_buffer():
    dict_ = parse_qs(request.query_string)
    kwargs = dict([(k, int(e[0])) for (k, e) in dict_.items()])
    rbio = RandomBytesIO(**kwargs)
    fsize = rbio.size()
    headers = Headers()
    headers['Content-Length'] = fsize
    filename = make_csv_fifo(rbio)
    file_ = open(filename, 'rb')
    data = wrap_file(request.environ, file_)
    return current_app.response_class(data,
                                      mimetype='text/csv',
                                      headers=headers,
                                      direct_passthrough=True)
Пример #16
0
def print_fleet(fleetid: int) -> Response:
    cached_members = member_info.get_cache_data(fleetid)
    if cached_members is None:
        crest_fleet = db.session.query(CrestFleet).get(fleetid)
        members: Dict[int, FleetMember] = member_info.get_fleet_members(
            fleetid, crest_fleet.comp)
        if members is None:
            return make_response("No cached or new info")
        cached_members = members
    return current_app.response_class(json.dumps(
        cached_members,
        indent=None if request.is_xhr else 2,
        cls=FleetMemberEncoder),
                                      mimetype='application/json')
Пример #17
0
    def __init__(self, *args, **kwargs):
        # Construct and store a new response object.
        self._handle = current_app.response_class()

        # Complete the initialization.
        super(Response, self).__init__(*args, **kwargs)

        # If we're dealing with an asynchronous response, we need
        # to have an asynchronous queue to give to WSGI.
        if self.asynchronous:
            from gevent import queue
            self._queue = queue.Queue()

        # Initialize the response headers.
        self.headers = ResponseHeaders(self, self._handle)
Пример #18
0
def send_zip(zipfilename, filename_path_list):
    #s = "<body><h1>HELLO</h1></body>"
    #response = iter(list(s))
    response = zip_iter(filename_path_list)
    headers = Headers()
    attachment_filename = zipfilename
    headers.add('Content-Disposition',
                'attachment',
                filename=attachment_filename)

    mimetype = 'application/zip'
    return current_app.response_class(response=response,
                                      mimetype=mimetype,
                                      headers=headers,
                                      direct_passthrough=True)
Пример #19
0
    def __init__(self, *args, **kwargs):
        # Construct and store a new response object.
        self._handle = current_app.response_class()

        # Complete the initialization.
        super(Response, self).__init__(*args, **kwargs)

        # If we're dealing with an asynchronous response, we need
        # to have an asynchronous queue to give to WSGI.
        if self.asynchronous:
            from gevent import queue
            self._queue = queue.Queue()

        # Initialize the response headers.
        self.headers = ResponseHeaders(self, self._handle)
Пример #20
0
def publish(id):
    try:
        received_json = request.get_json()
        my_dump = json.dumps(received_json)
        print my_dump

        # projects/the-depot/topic/hack-it 
        print received_json['topic'].split('/')[1]
        pubsub_client = pubsub.Client(project=received_json['topic'].split('/')[1])

        print 'got a pubsub client!!!', received_json['topic'].split('/')[3] 
        topic_name = received_json['topic'].split('/')[3]
        print topic_name
        topic = pubsub_client.topic(topic_name)
        print 'get topic from client!!!!'

        #topic_name_list = list()
        #for t in pubsub_client.list_topics():
            #topic_name_list.append(t.name)

        #if topic_name not in topic_name_list:
            #topic.create()

        print 'Creating datastore facade'
        gds = google_datastore.GoogleDataStore()
        print 'fetching...'
        result = gds.fetch(id)
        print 'got the result:'
        print result

        if result == None:
            return jsonify(code=404, message='Capital record not found'), 404

        print json.dumps(result)
        data = json.dumps(result)
        data = data.encode('utf-8')

        print 'Publishing on topic {}...'.format(topic_name)
        message_id = topic.publish(data)
        print 'Published on topic {}'.format(topic_name)

        print('Message {} published.'.format(message_id))
        return current_app.response_class(('{ "messageId": ' + str(message_id) + ' }', '\n'), mimetype=current_app.config['JSONIFY_MIMETYPE']), 200

    except Exception as e:
        print e
        return jsonify(code=500, message='Unexpected error'), 500
Пример #21
0
def jsonify(*args, **kwargs):
    """Creates a :class:`~flask.Response` with the JSON representation of
    the given arguments with an `application/json` mimetype.  The arguments
    to this function are the same as to the :class:`dict` constructor.

    Example usage::

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

    This will send a JSON response like this to the browser::

        {
            "username": "******",
            "email": "admin@localhost",
            "id": 42
        }

    This requires Python 2.6 or an installed version of simplejson.  For
    security reasons only objects are supported toplevel.  For more
    information about this, have a look at :ref:`json-security`.

    .. versionadded:: 0.2
    """
    status_code = kwargs.pop('status_code', None)

    response = current_app.response_class(
        json.dumps(
            dict(*args, **kwargs),
            indent=None if request.is_xhr else 4,
            default=defaultEncoder
        ),
        mimetype='application/json'
    )

    if status_code is not None:
        response.status_code = status_code

    return response
Пример #22
0
def jsonify(*args, **kwargs):

    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        json.dumps(data, indent=indent, separators=separators) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE']
    )
Пример #23
0
def jsonify(*args, **kwargs):
    """ flask.json.jsonify with cls=MongoJsonEncoder passed to flask.json.dumps

    Body copied from flask==1.0.2 (latest);
    """
    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators, cls=MongoJsonEncoder) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE']
    )
Пример #24
0
def status_for_user(username):
    """
    Return the latest status for one user.
    """
    status = api.get_latest_status(username)
    return current_app.response_class(simplejson.dumps(status, default=unknown_struct), mimetype='application/json')
Пример #25
0
def status():
    """
    Return the latest status for each user.
    """
    statuses = api.list_statuses()
    return current_app.response_class(simplejson.dumps(statuses, default=unknown_struct), mimetype='application/json')
Пример #26
0
def jsonify(*args, **kwargs):
    """This function wraps :func:`dumps` to add a few enhancements that make
    life easier.  It turns the JSON output into a :class:`~flask.Response`
    object with the :mimetype:`application/json` mimetype.  For convenience, it
    also converts multiple arguments into an array or multiple keyword arguments
    into a dict.  This means that both ``jsonify(1,2,3)`` and
    ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.

    For clarity, the JSON serialization behavior has the following differences
    from :func:`dumps`:

    1. Single argument: Passed straight through to :func:`dumps`.
    2. Multiple arguments: Converted to an array before being passed to
       :func:`dumps`.
    3. Multiple keyword arguments: Converted to a dict before being passed to
       :func:`dumps`.
    4. Both args and kwargs: Behavior undefined and will throw an exception.

    Example usage::

        from flask import jsonify

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

    This will send a JSON response like this to the browser::

        {
            "username": "******",
            "email": "admin@localhost",
            "id": 42
        }


    .. versionchanged:: 0.11
       Added support for serializing top-level arrays. This introduces a
       security risk in ancient browsers. See :ref:`json-security` for details.

    This function's response will be pretty printed if the
    ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the
    Flask app is running in debug mode. Compressed (not pretty) formatting
    currently means no indents and no spaces after separators.

    .. versionadded:: 0.2
    """

    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE']
    )
Пример #27
0
def jsonify(**kwargs):
    return current_app.response_class(
        dumps(kwargs, ensure_ascii=False, cls=Serializer),
        mimetype='application/json; charset=utf-8'
    )
Пример #28
0
def mongo_jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2, cls=MongoEngineEncoder), mimetype='application/json')
Пример #29
0
def jsonify(*args, **kwargs):
    """本函数打包了 :func:`dumps` 函数是为了增强一下更容易使用。
    本函数把 JSON 结果变成一个 :class:`~flask.Response` 对象,
    该类实例对象含有 :mimetype:`application/json` 媒体类型。
    为了方便起见,本函数也把多参数转换成一个列表或者
    把多关键字参数转换成一个字典。意思就是 ``jsonify(1,2,3)`` 和
    ``jsonify([1,2,3])`` 都会序列化成 ``[1,2,3]`` 。

    为了明确, JSON 序列化行为与 :func:`dumps` 函数有如下不同之处:

    1. 单个参数:直接代入到 :func:`dumps` 函数中。
    2. 多参数:转换成列表后再代入 :func:`dumps` 函数中。
    3. 多关键字参数:转换成字典后再代入 :func:`dumps` 函数中。
    4. 同时使用 args 和 kwargs 参数时:没有定义行为并会抛出一个例外类型。

    示例用法::

        from flask import jsonify

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

    这种用法会发送一个 JSON 响应对象,就像浏览器中的::

        {
            "username": "******",
            "email": "admin@localhost",
            "id": 42
        }


    .. versionchanged:: 0.11
       增加了支持序列化顶层阵列。
       否则在老旧的浏览器中会导致一项安全风险。
       查看 :ref:`json-security` 了解细节。

    如果 ``JSONIFY_PRETTYPRINT_REGULAR`` 配置项设置成 `True` 的话,
    或者 Flask 网络应用运行在调试模式中的话,
    本函数的响应对象会是良好格式输出。
    压缩的格式(非良好格式)当前意思就是在分隔符后没有缩进和没有空格。

    .. versionadded:: 0.2
    """

    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError(
            'jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE'])
Пример #30
0
 def inner(*args, **kwargs):
     return current_app.response_class(json.dumps(method(*args, **kwargs), indent=None, default=default_handler), mimetype='application/json')
Пример #31
0
def jsonify(*args, **kwargs):
    """This function wraps :func:`dumps` to add a few enhancements that make
    life easier.  It turns the JSON output into a :class:`~flask.Response`
    object with the :mimetype:`application/json` mimetype.  For convenience, it
    also converts multiple arguments into an array or multiple keyword arguments
    into a dict.  This means that both ``jsonify(1,2,3)`` and
    ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.

    For clarity, the JSON serialization behavior has the following differences
    from :func:`dumps`:

    1. Single argument: Passed straight through to :func:`dumps`.
    2. Multiple arguments: Converted to an array before being passed to
       :func:`dumps`.
    3. Multiple keyword arguments: Converted to a dict before being passed to
       :func:`dumps`.
    4. Both args and kwargs: Behavior undefined and will throw an exception.

    Example usage::

        from flask import jsonify

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

    This will send a JSON response like this to the browser::

        {
            "username": "******",
            "email": "admin@localhost",
            "id": 42
        }


    .. versionchanged:: 0.11
       Added support for serializing top-level arrays. This introduces a
       security risk in ancient browsers. See :ref:`json-security` for details.

    This function's response will be pretty printed if the
    ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the
    Flask app is running in debug mode. Compressed (not pretty) formatting
    currently means no indents and no spaces after separators.

    .. versionadded:: 0.2
    """

    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE']
    )
Пример #32
0
 def wrapper(*args, **kwargs):
     data = func(*args, **kwargs)
     return current_app.response_class(json.dumps(data, indent=2),
                                       mimetype='application/json')