使用场景
flask restless 可以快速的把传统数据库的数据封装成一个restful的API。
如果使用的是Nosql,可以使用flask restful开启API。运行demo后使用 http://127.0.0.1:5000/api/person 进行访问
quick start
下面演示了如何构建一个简易的flask_restless demo.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-01-18 17:40:43
# @Author : zhuhua (zhuhuasml@163.com)
import flask
import flask_sqlalchemy
import flask_restless
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = flask_sqlalchemy.SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.Unicode)
birth_date = db.Column(db.Unicode)
# Create the database tables.
db.create_all()
for i in range (100):
db.session.add(Person(name="robin{}".format(i),birth_date="1989-06-0{}".format(i)))
db.session.commit()
# Create the Flask-Restless API manager.
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'],results_per_page=30,max_results_per_page=10000)
# start the flask loop
app.run()
Tips
create_api实际上是调用了create_api_blueprint,代码如下:
def create_api_blueprint(self, model, app=None, methods=READONLY_METHODS,
url_prefix='/api', collection_name=None,
allow_patch_many=False, allow_delete_many=False,
allow_functions=False, exclude_columns=None,
include_columns=None, include_methods=None,
validation_exceptions=None, results_per_page=10,
max_results_per_page=100,
post_form_preprocessor=None, preprocessors=None,
postprocessors=None, primary_key=None,
serializer=None, deserializer=None):
"""Creates and returns a ReSTful API interface as a blueprint, but does
not register it on any :class:`flask.Flask` application.
The endpoints for the API for ``model`` will be available at
``<url_prefix>/<collection_name>``. If `collection_name` is ``None``,
the lowercase name of the provided model class will be used instead, as
accessed by ``model.__tablename__``. (If any black magic was performed
on ``model.__tablename__``, this will be reflected in the endpoint
URL.) For more information, see :ref:`collectionname`.
This function must be called at most once for each model for which you
wish to create a ReSTful API. Its behavior (for now) is undefined if
called more than once.
This function returns the :class:`flask.Blueprint` object which handles
the endpoints for the model. The returned :class:`~flask.Blueprint` has
already been registered with the :class:`~flask.Flask` application
object specified in the constructor of this class, so you do *not* need
to register it yourself.
`model` is the SQLAlchemy model class for which a ReSTful interface
will be created. Note this must be a class, not an instance of a class.
`app` is the :class:`Flask` object on which we expect the blueprint
created in this method to be eventually registered. If not specified,
the Flask application specified in the constructor of this class is
used.
`methods` specify the HTTP methods which will be made available on the
ReSTful API for the specified model, subject to the following caveats:
* If :http:method:`get` is in this list, the API will allow getting a
single instance of the model, getting all instances of the model, and
searching the model using search parameters.
* If :http:method:`patch` is in this list, the API will allow updating
a single instance of the model, updating all instances of the model,
and updating a subset of all instances of the model specified using
search parameters.
* If :http:method:`delete` is in this list, the API will allow deletion
of a single instance of the model per request.
* If :http:method:`post` is in this list, the API will allow posting a
new instance of the model per request.
The default set of methods provides a read-only interface (that is,
only :http:method:`get` requests are allowed).
`collection_name` is the name of the collection specified by the given
model class to be used in the URL for the ReSTful API created. If this
is not specified, the lowercase name of the model will be used.
`url_prefix` the URL prefix at which this API will be accessible.
If `allow_patch_many` is ``True``, then requests to
:http:patch:`/api/<collection_name>?q=<searchjson>` will attempt to
patch the attributes on each of the instances of the model which match
the specified search query. This is ``False`` by default. For
information on the search query parameter ``q``, see
:ref:`searchformat`.
If `allow_delete_many` is ``True``, then requests to
:http:delete:`/api/<collection_name>?q=<searchjson>` will attempt to
delete each instance of the model that matches the specified search
query. This is ``False`` by default. For information on the search
query parameter ``q``, see :ref:`searchformat`.
`validation_exceptions` is the tuple of possible exceptions raised by
validation of your database models. If this is specified, validation
errors will be captured and forwarded to the client in JSON format. For
more information on how to use validation, see :ref:`validation`.
If `allow_functions` is ``True``, then requests to
:http:get:`/api/eval/<collection_name>` will return the result of
evaluating SQL functions specified in the body of the request. For
information on the request format, see :ref:`functionevaluation`. This
if ``False`` by default. Warning: you must not create an API for a
model whose name is ``'eval'`` if you set this argument to ``True``.
If either `include_columns` or `exclude_columns` is not ``None``,
exactly one of them must be specified. If both are not ``None``, then
this function will raise a :exc:`IllegalArgumentError`.
`exclude_columns` must be an iterable of strings specifying the columns
of `model` which will *not* be present in the JSON representation of
the model provided in response to :http:method:`get` requests.
Similarly, `include_columns` specifies the *only* columns which will be
present in the returned dictionary. In other words, `exclude_columns`
is a blacklist and `include_columns` is a whitelist; you can only use
one of them per API endpoint. If either `include_columns` or
`exclude_columns` contains a string which does not name a column in
`model`, it will be ignored.
If you attempt to either exclude a primary key field or not include a
primary key field for :http:method:`post` requests, this method will
raise an :exc:`IllegalArgumentError`.
If `include_columns` is an iterable of length zero (like the empty
tuple or the empty list), then the returned dictionary will be
empty. If `include_columns` is ``None``, then the returned dictionary
will include all columns not excluded by `exclude_columns`.
If `include_methods` is an iterable of strings, the methods with names
corresponding to those in this list will be called and their output
included in the response.
See :ref:`includes` for information on specifying included or excluded
columns on fields of related models.
`results_per_page` is a positive integer which represents the default
number of results which are returned per page. Requests made by clients
may override this default by specifying ``results_per_page`` as a query
argument. `max_results_per_page` is a positive integer which represents
the maximum number of results which are returned per page. This is a
"hard" upper bound in the sense that even if a client specifies that
greater than `max_results_per_page` should be returned, only
`max_results_per_page` results will be returned. For more information,
see :ref:`serverpagination`.
网友评论