FlaskRestful教程:API 文档


flask.ext.restful.marshal(data, fields, envelope=None)

Takes raw data (in the form of a dict, list, object) and a dict of
fields to output and filters the data based on those fields.

Parameters:
  • data – the actual object(s) from which the fields are taken from
  • fields – a dict of whose keys will make up the final serialized
    response output
  • envelope – optional key that will be used to envelop the serialized
    response
>>> from flask.ext.restful import fields, marshal
>>> data = { 'a': 100, 'b': 'foo' }
>>> mfields = { 'a': fields.Raw }
>>> marshal(data, mfields)
OrderedDict([('a', 100)])
>>> marshal(data, mfields, envelope='data')
OrderedDict([('data', OrderedDict([('a', 100)]))])
flask.ext.restful.marshal_with(fields, envelope=None)

A decorator that apply marshalling to the return values of your methods.

>>> from flask.ext.restful import fields, marshal_with
>>> mfields = { 'a': fields.Raw }
>>> @marshal_with(mfields)
... def get():
...     return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('a', 100)])
>>> @marshal_with(mfields, envelope='data')
... def get():
...     return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('data', OrderedDict([('a', 100)]))])

see flask.ext.restful.marshal()

flask.ext.restful.marshal_with_field(field)

A decorator that formats the return values of your methods with a single field.

>>> from flask.ext.restful import marshal_with_field, fields
>>> @marshal_with_field(fields.List(fields.Integer))
... def get():
...     return ['1', 2, 3.0]
...
>>> get()
[1, 2, 3]

see flask.ext.restful.marshal_with()

flask.ext.restful.abort(http_status_code, **kwargs)

Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.

Api¶

class flask.ext.restful.Api(app=None, prefix=”, default_mediatype=’application/json’, decorators=None, catch_all_404s=False, url_part_order=’bae’, errors=None)

The main entry point for the application.
You need to initialize it with a Flask Application:

>>> app = Flask(__name__)
>>> api = restful.Api(app)

Alternatively, you can use init_app() to set the Flask application
after it has been constructed.

Parameters:
  • app (flask.Flask) – the Flask application object
  • prefix (str) – Prefix all routes with a value, eg v1 or 2010-04-01
  • default_mediatype (str) – The default media type to return
  • decorators (list) – Decorators to attach to every resource
  • catch_all_404s (bool) – Use handle_error()
    to handle 404 errors throughout your app
  • url_part_order – A string that controls the order that the pieces
    of the url are concatenated when the full url is constructed. ‘b’
    is the blueprint (or blueprint registration) prefix, ‘a’ is the api
    prefix, and ‘e’ is the path component the endpoint is added with
  • errors () – A dictionary to define a custom response for each
    exception or error raised during a request
add_resource(resource, *urls, **kwargs)

Adds a resource to the api.

Parameters:
  • resource (Resource) – the class name of your resource
  • urls (str) – one or more url routes to match for the resource, standard
    flask routing rules apply. Any url variables will be
    passed to the resource method as args.
  • endpoint (str) – endpoint name (defaults to Resource.__name__.lower()
    Can be used to reference this route in fields.Url fields

Additional keyword arguments not specified above will be passed as-is
to flask.Flask.add_url_rule().

Examples:

api.add_resource(HelloWorld, '/', '/hello')
api.add_resource(Foo, '/foo', endpoint="foo")
api.add_resource(FooSpecial, '/special/foo', endpoint="foo")
error_router(original_handler, e)

This function decides whether the error occured in a flask-restful
endpoint or not. If it happened in a flask-restful endpoint, our
handler will be dispatched. If it happened in an unrelated view, the
app’s original error handler will be dispatched.
In the event that the error occurred in a flask-restful endpoint but
the local handler can’t resolve the situation, the router will fall
back onto the original_handler as last resort.

Parameters:
  • original_handler (function) – the original Flask error handler for the app
  • e (Exception) – the exception raised while handling the request
handle_error(e)

Error handler for the API transforms a raised exception into a Flask
response, with the appropriate HTTP status code and body.

Parameters: e (Exception) – the raised Exception object
init_app(app)

Initialize this class with the given flask.Flask
application or flask.Blueprint object.

Parameters: app (flask.Blueprint) – the Flask application or blueprint object

Examples:

api = Api()
api.add_resource(...)
api.init_app(app)
make_response(data, *args, **kwargs)

Looks up the representation transformer for the requested media
type, invoking the transformer to create a response object. This
defaults to (application/json) if no transformer is found for the
requested mediatype.

Parameters: data – Python object containing response data to be transformed
mediatypes()

Returns a list of requested mediatypes sent in the Accept header

mediatypes_method()

Return a method that returns a list of mediatypes

output(resource)

Wraps a resource (as a flask view function), for cases where the
resource does not directly return a response object

Parameters: resource – The resource as a flask view function
owns_endpoint(endpoint)

Tests if an endpoint name (not path) belongs to this Api. Takes
in to account the Blueprint name part of the endpoint name.

Parameters: endpoint – The name of the endpoint being checked
Returns: bool
representation(mediatype)

Allows additional representation transformers to be declared for the
api. Transformers are functions that must be decorated with this
method, passing the mediatype the transformer represents. Three
arguments are passed to the transformer:

  • The data to be represented in the response body
  • The http status code
  • A dictionary of headers

The transformer should convert the data appropriately for the mediatype
and return a Flask response object.

Ex:

@api.representation('application/xml')
def xml(data, code, headers):
    resp = make_response(convert_data_to_xml(data), code)
    resp.headers.extend(headers)
    return resp
resource(*urls, **kwargs)

Wraps a Resource class, adding it to the
api. Parameters are the same as add_resource().

Example:

app = Flask(__name__)
api = restful.Api(app)

@api.resource('/foo')
class Foo(Resource):
    def get(self):
        return 'Hello, World!'
unauthorized(response)

Given a response, change it to ask for credentials

url_for(resource, **values)

Generates a URL to the given resource.

class flask.ext.restful.Resource

Represents an abstract RESTful resource. Concrete resources should
extend from this class and expose methods for each supported HTTP
method. If a resource is invoked with an unsupported HTTP method,
the API will return a response with status 405 Method Not Allowed.
Otherwise the appropriate method is called and passed all arguments
from the url rule used when adding the resource to an Api instance. See
add_resource() for details.

ReqParse¶

class reqparse.RequestParser(argument_class=<class ‘reqparse.Argument’>, namespace_class=<class ‘reqparse.Namespace’>)

Enables adding and parsing of multiple arguments in the context of a
single request. Ex:

from flask import request

parser = RequestParser()
parser.add_argument('foo')
parser.add_argument('int_bar', type=int)
args = parser.parse_args()
add_argument(*args, **kwargs)

Adds an argument to be parsed.

Accepts either a single instance of Argument or arguments to be passed
into Argument‘s constructor.

See Argument‘s constructor for documentation on the
available options.

copy()

Creates a copy of this RequestParser with the same set of arguments

parse_args(req=None, strict=False)

Parse all arguments from the provided request and return the results
as a Namespace

Parameters: strict – if req includes args not in parser, throw 400 BadRequest exception
remove_argument(name)

Remove the argument matching the given name.

replace_argument(name, *args, **kwargs)

Replace the argument matching the given name with a new version.

class reqparse.Argument(name, default=None, dest=None, required=False, ignore=False, type=<function <lambda> at 0x1065c6c08>, location=(‘json’, ‘values’), choices=(), action=’store’, help=None, operators=(‘=’, ), case_sensitive=True, store_missing=True)
Parameters:
  • name – Either a name or a list of option strings, e.g. foo or
    -f, –foo.
  • default – The value produced if the argument is absent from the
    request.
  • dest – The name of the attribute to be added to the object
    returned by parse_args().
  • required (bool) – Whether or not the argument may be omitted (optionals
    only).
  • action – The basic type of action to be taken when this argument
    is encountered in the request. Valid options are “store” and “append”.
  • ignore – Whether to ignore cases where the argument fails type
    conversion
  • type – The type to which the request argument should be
    converted. If a type raises a ValidationError, the message in the
    error will be returned in the response. Defaults to unicode
    in python2 and str in python3.
  • location – The attributes of the flask.Request object
    to source the arguments from (ex: headers, args, etc.), can be an
    iterator. The last item listed takes precedence in the result set.
  • choices – A container of the allowable values for the argument.
  • help – A brief description of the argument, returned in the
    response when the argument is invalid with the name of the argument and
    the message passed to a ValidationError raised by a type converter.
  • case_sensitive (bool) – Whether the arguments in the request are
    case sensitive or not
  • store_missing (bool) – Whether the arguments default value should
    be stored if the argument is missing from the request.
__init__(name, default=None, dest=None, required=False, ignore=False, type=<function <lambda> at 0x1065c6c08>, location=(‘json’, ‘values’), choices=(), action=’store’, help=None, operators=(‘=’, ), case_sensitive=True, store_missing=True)
handle_validation_error(error)

Called when an error is raised while parsing. Aborts the request
with a 400 status and an error message

Parameters: error – the error that was raised
parse(request)

Parses argument value(s) from the request, converting according to
the argument’s type.

Parameters: request – The flask request object to parse arguments from
source(request)

Pulls values off the request in the provided location
:param request: The flask request object to parse arguments from

Fields¶

class fields.String(default=None, attribute=None)

Marshal a value as a string. Uses six.text_type so values will
be converted to unicode in python2 and str in
python3.

format(value)
class fields.FormattedString(src_str)

FormattedString is used to interpolate other values from
the response into this field. The syntax for the source string is
the same as the string format method from the python stdlib.

Ex:

fields = {
    'name': fields.String,
    'greeting': fields.FormattedString("Hello {name}")
}
data = {
    'name': 'Doug',
}
marshal(data, fields)
output(key, obj)
class fields.Url(endpoint=None, absolute=False, scheme=None)

A string representation of a Url

output(key, obj)
class fields.DateTime(dt_format=’rfc822′, **kwargs)

Return a formatted datetime string in UTC. Supported formats are RFC 822
and ISO 8601.

Parameters: dt_format (str) – 'rfc822' or 'iso8601'
format(value)
class fields.Float(default=None, attribute=None)

A double as IEEE-754 double precision.
ex : 3.141592653589793 3.1415926535897933e-06 3.141592653589793e+24 nan inf -inf

format(value)
class fields.Integer(default=0, **kwargs)

Field for outputting an integer value.

Parameters:
  • default (int) – The default value for the field, if no value is
    specified.
  • attribute – If the public facing value differs from the internal
    value, use this to retrieve a different attribute from the response
    than the publicly named value.
format(value)
class fields.Arbitrary(default=None, attribute=None)
A floating point number with an arbitrary precision
ex: 634271127864378216478362784632784678324.23432
format(value)
class fields.Nested(nested, allow_null=False, **kwargs)

Allows you to nest one set of fields inside another.
See 高级:嵌套字段 for more information

Parameters:
  • nested (dict) – The dictionary to nest
  • allow_null (bool) – Whether to return None instead of a dictionary
    with null keys, if a nested dictionary has all-null keys
  • kwargs – if default keyword argument is present, a nested dictionary
    will be marshaled as its value if nested dictionary is all-null keys
    (e.g. lets you return an empty JSON object instead of null)

:keyword default

output(key, obj)
class fields.List(cls_or_instance, **kwargs)

Field for marshalling lists of other fields.

See 列表字段 for more information.

Parameters: cls_or_instance – The field type the list will contain.
format(value)
output(key, data)
class fields.Raw(default=None, attribute=None)

Raw provides a base field class from which others should extend. It
applies no formatting by default, and should only be used in cases where
data does not need to be formatted before being serialized. Fields should
throw a MarshallingException in case of parsing problem.

format(value)

Formats a field’s value. No-op by default – field classes that
modify how the value of existing object keys should be presented should
override this and apply the appropriate formatting.

Parameters: value – The value to format
Raises MarshallingException:
  In case of formatting problem

Ex:

class TitleCase(Raw):
    def format(self, value):
        return unicode(value).title()
output(key, obj)

Pulls the value for the given key from the object, applies the
field’s formatting and returns the result. If the key is not found
in the object, returns the default value. Field classes that create
values which do not require the existence of the key in the object
should override this and return the desired value.

Raises MarshallingException:
  In case of formatting problem
class fields.Boolean(default=None, attribute=None)

Field for outputting a boolean value.

Empty collections such as "", {}, [], etc. will be converted to
False.

format(value)
class fields.Fixed(decimals=5, **kwargs)

A decimal number with a fixed precision.

format(value)
fields.Price

alias of Fixed

Inputs¶

flask.ext.restful.inputs.url(value)

Validate a URL.

Parameters: value (string) – The URL to validate
Returns: The URL if valid.
Raises: ValueError
flask.ext.restful.inputs.regex
flask.ext.restful.inputs.date(value)

Parse a valid looking date in the format YYYY-mm-dd

flask.ext.restful.inputs.iso8601interval(value, argument=’argument’)

Parses ISO 8601-formatted datetime intervals into tuples of datetimes.

Accepts both a single date(time) or a full interval using either start/end
or start/duration notation, with the following behavior:

  • Intervals are defined as inclusive start, exclusive end
  • Single datetimes are translated into the interval spanning the
    largest resolution not specified in the input value, up to the day.
  • The smallest accepted resolution is 1 second.
  • All timezones are accepted as values; returned datetimes are
    localized to UTC. Naive inputs and date inputs will are assumed UTC.

Examples:

"2013-01-01" -> datetime(2013, 1, 1), datetime(2013, 1, 2)
"2013-01-01T12" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 13)
"2013-01-01/2013-02-28" -> datetime(2013, 1, 1), datetime(2013, 2, 28)
"2013-01-01/P3D" -> datetime(2013, 1, 1), datetime(2013, 1, 4)
"2013-01-01T12:00/PT30M" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 12, 30)
"2013-01-01T06:00/2013-01-01T12:00" -> datetime(2013, 1, 1, 6), datetime(2013, 1, 1, 12)
Parameters: value (str) – The ISO8601 date time as a string
Returns: Two UTC datetimes, the start and the end of the specified interval
Return type: A tuple (datetime, datetime)
Raises: ValueError, if the interval is invalid.
flask.ext.restful.inputs.natural(value, argument=’argument’)

Restrict input type to the natural numbers (0, 1, 2, 3…)

flask.ext.restful.inputs.boolean(value)

Parse the string “true” or “false” as a boolean (case insensitive).
Also accepts “1” and “0” as True/False (respectively). If
the input is from the request JSON body, the type is already a native
python boolean, and will be passed through without further parsing.

flask.ext.restful.inputs.rfc822(dt)

Turn a datetime object into a formatted date.

Example:

inputs.rfc822(datetime(2011, 1, 1)) => "Sat, 01 Jan 2011 00:00:00 -0000"
Parameters: dt (datetime) – The datetime to transform
Returns: A RFC 822 formatted date string