官术网_书友最值得收藏!

Response

In the previous examples, we've used the jsonify() function, which creates a Response object from the mapping returned by the view.

The Response object is, technically, a standard WSGI application you could use directly. It's wrapped by Flask, and called with the WSGI's environ, and the start_response function is received from the web server.

When Flask picks a view via its URL mapper, it expects it to return a callable object that can receive the environ and start_response arguments.

This design may seem a little awkward since the WSGI environ is already parsed into a Request object by the time the Response object is called with the WSGI environ again. But, in practice, this is just an implementation detail. When your code needs to interact with the request, it can use the global Request object, and ignore what's happening inside the Response class.

In case the returned value is not a callable, Flask will try to convert it into a Response object if it's one of the following cases:

  • str: The data gets encoded as UTF-8 and used as the HTTP response body.
  • bytes/bytesarray: Used as the body.
  • A (response, status, headers) tuple: Where response can be a Response object or one of the previous types. status is an integer value that overwrites the response status, and headers is a mapping that extends the response headers.
  • A (response, status) tuple: Like the previous one, but without specific headers
  • A (response, headers) tuple: Like the preceding one, but with just extra headers.

Any other case will lead to an exception.

In most cases, when building microservices, we'll use the built-in jsonify() function, but in case you need your endpoints to produce another content type, creating a function that will convert the generated data into a Response class is easy enough.

Here's an example with YAML: the yamlify() function will return a (response, status, headers) tuple, which will be converted by Flask into a proper Response object.

    from flask import Flask 
import yaml # requires PyYAML

app = Flask(__name__)

def yamlify(data, status=200, headers=None):
_headers = {'Content-Type': 'application/x-yaml'}
if headers is not None:
_headers.update(headers)
return yaml.safe_dump(data), status, _headers

@app.route('/api')
def my_microservice():
return yamlify(['Hello', 'YAML', 'World!'])

if __name__ == '__main__':
app.run()

The way Flask handles requests can be summarized as follows:

  1. When the application starts, any function decorated with @app.route() is registered as a view, and stored into the app.url_map.
  2. A call is dispatched to the right view depending on its endpoint and method.
  1. A Request object is created in a thread-safe thread-local execution context.
  2. A Response object wraps the content to send back.

These four steps are roughly all you need to know to start building apps using Flask. The next section will summarize the most important built-in features that Flask offers alongside this request-response mechanism.

主站蜘蛛池模板: 临洮县| 汾西县| 贡嘎县| 镇远县| 建瓯市| 北碚区| 东城区| 永吉县| 云阳县| 新津县| 陆丰市| 博湖县| 饶阳县| 阜宁县| 惠安县| 十堰市| 自贡市| 江北区| 大荔县| 阿坝| 达尔| 新宁县| 永胜县| 资阳市| 华容县| 财经| 长寿区| 滁州市| 彰化县| 五家渠市| 梁平县| 康平县| 三江| 岳普湖县| 黎平县| 朝阳市| 任丘市| 上虞市| 隆回县| 平顺县| 大渡口区|