发布于 2015-09-02 07:54:12 | 716 次阅读 | 评论: 0 | 来源: 网络整理
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: |
|
---|
>>> 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)]))])
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]
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.
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: |
|
---|
add_resource
(resource, *urls, **kwargs)¶Adds a resource to the api.
Parameters: |
|
---|
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: |
|
---|
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 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.
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.
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.
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: |
|
---|
__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.
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)¶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)¶fields.
Url
(endpoint=None, absolute=False, scheme=None)¶A string representation of a Url
output
(key, obj)¶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)¶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)¶fields.
Integer
(default=0, **kwargs)¶Field for outputting an integer value.
Parameters: |
|
---|
format
(value)¶fields.
Arbitrary
(default=None, attribute=None)¶format
(value)¶fields.
Nested
(nested, allow_null=False, **kwargs)¶Allows you to nest one set of fields inside another. See 高级:嵌套字段 for more information
Parameters: |
|
---|
:keyword default
output
(key, obj)¶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)¶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 |
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:
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 |