Inspired by the Django URL configuration system, Flask-Via is designed to add similar functionality to Flask applications which have grown beyond a simple single file application.
from flask import Flask
from flask.ext.via import Via
from flask.ext.via.routers.default import Basic
app = Flask(__name__)
def foo(bar=None):
return 'Foo View!'
routes = [
Basic('/foo', foo),
Basic('/foo/<bar>', foo, endpoint='foo2'),
]
via = Via()
via.init_app(app, route_module='flask_via.examples.basic')
if __name__ == "__main__":
app.run(debug=True)
Growing your application can be quite difficult when it’s not always clear where and how your routes are discovered. This can lead to a cluttered application factory method when all your routes are defined at application creation - resulting in code which is difficult to maintain, not to mention messy.
A better solution is to define your routes in a routes.py and automatically load them at application start up. This is what Flask-Via helps to do.
Third party Flask extensions don’t always follow the same conventions for adding routes to an application, so Flask-Via has been designed to be easy for developers to write their own custom routers. For an example of this, take a look at the bundled Flask-Restful Resource router.
If you do write a custom router that is useful to you, it will probably be useful to someone else so please do contribute back :)
Flask-Via is simple to install, just use your favourite python package manage, for example pip:
$ pip install Flask-Via
Once we have installed Flask-Via we need to perform the following steps:
The following example code performs the above steps with key lines emphasised.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from flask import Flask
from flask.ext.via import Via
from flask.ext.via.routers.default import Basic
app = Flask(__name__)
def foo(bar=None):
return 'Foo View!'
routes = [
Basic('/foo', foo),
Basic('/foo/<bar>', foo, endpoint='foo2'),
]
via = Via()
via.init_app(app, route_module='path.to.here')
if __name__ == "__main__":
app.run(debug=True)
|
Lines 10-13 show how routes are defined in a list using the basic flask router class (flask_via.routers.default.Basic).
Line 16 shows how we Flask-Via looks for where routes are defined, this can be set as we have done above or using the VIA_ROUTES_MODULE application configuration variable.
Routes can live anywhere you want them too, as long as they are importable.
You can tell Flask-Via where to find routes in a couple of ways:
You can use which ever you prefer.
from flask import Flask
from flask.ext.via import Via
app = Flask(__name__)
app.config['VIA_ROUTES_MODULE'] = 'yourapp.routes'
via = Via()
via.init_app(app)
if __name__ == "__main__":
app.run(debug=True)
from flask import Flask
from flask.ext.via import Via
app = Flask(__name__)
via = Via()
via.init_app(app, routes_module='yourapp.routes')
if __name__ == "__main__":
app.run(debug=True)
The routes module should define a list of routes, by default this list is called routes:
routes = [
Basic('/', home),
Basic('/about', about),
]
You can configure Flask-Via to look for any variable name of your choosing, this is done by passing an argument named routes_name into init_app, for example:
via = Via()
via.init_app(app, routes_name='urls')
Assume we have the following application structure:
/path/to/foo
- __init__.py
- routes.py
- views.py
- app.py
Within views.py we have:
def home():
return 'Hello world!'
def about():
return 'The world is big'
Within routes.py we have:
from flask.ext.via.routers import default
urls = [
default.Basic('/', home),
default.Basic('/about', about),
]
Within app.py we have:
from flask import Flask
from flask.ext.via import Via
app = Flask(__name__)
app.config['VIA_ROUTES_MODULE'] = 'foo.routes'
via = Via()
via.init_app(app, routes_name='urls')
if __name__ == "__main__":
app.run(debug=True)
You will see we used routes_name when calling via.init_app to tell Via what variable to look for within the routes module.
Here you will find the documentation for each bundled router provided by Flask-Via.
These routers are designed to work with standard flask functional and class based pluggable views.
The flask_via.routers.default.Basic router handles basic functional based view routing.
from flask.ext.via.routers.default import Basic
def foo(bar=None):
return 'foo'
routes = [
Basic('/', foo),
Basic('/<bar>', foo, endpoint='foobar'),
]
The flask_via.routers.default.Pluggable router handles views created using Flasks pluggable views.
from flask.views import MethodView
from flask.ext.via.routers.default import Pluggable
class FooView(MethodView):
def get(self, bar=None):
return 'foo'
routes = [
Plugganle('/', view_func=FooView.as_view('foo')),
Plugganle('/<bar>', view_func=FooView.as_view('foobar')),
]
Flask-Restful is an awesome framework for building REST API’s in Flask but has it’s own way of adding routes to the Flask application, so tere is a little bit of extra work required when bootstrapping your application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from flask import Flask
from flask.ext import restful
from flask.ext.via import Via
app = Flask(__name__)
api = restful.Api(app)
via = Via()
via.init_app(
app,
routes_module='yourapp.routes',
restful_api=api)
if __name__ == '__main__':
app.run(debug=True)
|
Note that on line 12 we passed a keyword argument called restful_api with the value being the Flask-Restful api object into via.init_app. This will allow the flask_via.routers.restful.Resource router to add resouce routes to the api.
Warning
Before using this router be sure you have read the section directly above.
The flask_via.routers.restful.Resource router allows us to register Flask-Restful resources to our application.
class FooResource(restful.Resource):
def get(self, bar=None):
return {'hello': 'world'}
routes = [
Resource('/', FooResource)
Resource('/<bar>', FooResource, endpoint='foobar')
]
Sometimes you don’t want to define all your routes in one place, you want to be modular right!? You can do that too with Flask-Via.
The most basic way of including other routes is to use the flask_via.routers.Include router. This is not a intended replacement or implementation of Flask blueprints, just a simple way of putting routes somewhere else in your application.
Assume the following application structure:
/path/to/foo
- bar/
- __init__.py
- routes.py
- views.py
- __int__.py
- routes.py
In the top level routes.py we would have:
from flask.ext.via.routers import Include
routes = [
Include('foo.bar.routes')
]
In the foo.routes we would have:
from flask.ext.via.routes import default
from foo.bar.views import some_view
routes = [
default.Basic('/bar', some_view)
]
You can see this in action with the Small Application Example.
Flask Blueprints are also supported allowing Flask-Via to automatically register blueprints on the application and routes on the blueprint, this is provided by the flask_via.routers.default.Blueprint router.
Let us assume we have the following application structure:
/path/to/foo
- bar/
- templates/
- foo.html
- __init__.py
- routes.py
- views.py
- __int__.py
- routes.py
In the above structure bar is a Flask blueprint which we wish to add to our flask application, so our top level routes would look like this:
from flask.ext.via.routers.default import Blueprint
routes = [
Blueprint('bar', 'foo.bar', template_folder='templates')
]
You will note we give the blueprint a name and pass the top level module path to the blueprint rather than a path to the routes file.
In our blueprints views we can define routes as normal:
from flask.ext.via.routes import default
from foo.bar.views import some_view
routes = [
default.Basic('/bar', some_view)
]
Note
All routes will be added to the blueprint rather than the flask application, this applies to any routes included using the Include router.
Here you can find examples of how to use Flask-Via. All examples are on GitHub.
Bases: object
Handles the import of routes module and obtaining a list of routes from that module as well as loading each route onto the application
Imports a routes module and gets the routes from within that module and returns them.
Parameters: |
|
---|---|
Returns: | List of routes in the module |
Return type: | list |
Bases: flask_via.RoutesImporter
The core class which kicks off the whole registration processes.
Example
from flask import Flask
from flask.ext.via import Via
from flask.ext.via.routers.flask import Basic
app = Flask(__name__)
def foo(bar=None):
return 'Foo View!'
routes = [
Basic('/foo', foo),
Basic('/foo/<bar>', foo, endpoint='foo2'),
]
via = Via()
via.init_app(app, routes_module='path.to.here')
if __name__ == "__main__":
app.run(debug=True)
Initialises Flask extension. Bootstraps the automatic route registration process.
Parameters: | app (flask.app.Flask) – Flask application instance |
---|---|
Keyword Arguments: | |
|
|
Raises: |
|
Base router classes and utilities.
Bases: object
Base router class all routers should inherit from providing common router functionality.
Example
from flask.ext.via.routers import BaseRouter
class MyRouter(BaseRouter):
def __init__(self, arg):
...
def add_to_app(self, app):
...
Bases: flask_via.routers.BaseRouter, flask_via.RoutesImporter
Adds the ability to include routes from other modules, this can be handy when you want to break out your routes into separate files for sanity.
Note
This is not a implementation of Flask blueprints
Constructor for Include router, taking the passed arguments and storing them on the instance.
Parameters: | routes_module (str) – Python dotted path to the routes module |
---|---|
Keyword Arguments: | |
routes_name (str (optional)) – Name of the variable holding the routes in the module, defaults to routes |
Instead of adding a route to the flask application this will include and load routes similar, same as in the flask_via.Via class.abs
Parameters: |
|
---|
A set of flask specific router classes to be used when defining routes.
Example
from flask.ext.via.routes.flask import Basic, Pluggable
from yourapp.views import BarView, foo_view
routes = [
Basic('/foo', 'foo', foo_view),
Pluggable('/bar', view_func=BarView.as_view('bar')),
]
Bases: flask_via.routers.BaseRouter
A basic Flask router, used for the most basic form of flask routes, namely functionally based views which would normally use the @route decorator.
Example
from flask.ext.via.routes import flask
from yourapp.views import foo_view, bar_view
routes = [
Basic('/foo', 'foo', foo_view),
Basic('/bar', 'bar', bar_view),
]
Basic router constructor, stores passed arguments on the instance.
Parameters: |
|
---|---|
Keyword Arguments: | |
endpoint (str, optional) – Optional endpoint string, by default flask will use the view function name as the endpoint name, use this argument to change the endpoint name. |
Bases: flask_via.routers.BaseRouter, flask_via.RoutesImporter
Registers a flask blueprint and registers routes to that blueprint, similar to flask_via.routes.Include.
Example
from flask.ext.via.routers import default
routes = [
default.blueprint('foo', 'flask_via.examples.blueprints.foo')
]
Constructor for blueprint router.
Parameters: |
|
---|---|
Keyword Arguments: | |
|
Creates a Flask blueprint and registers routes with that blueprint, this means any routes defined will be added to the blueprint rather than the application.
Parameters: |
|
---|
Bases: flask_via.routers.BaseRouter
Pluggable View router class, allows Flask pluggable view routes to be added to the flask application.
Example
from flask.ext.via.routers import flask
from flask.views import MethodView
class FooView(MethodView):
def get(self):
return 'foo view'
class BarView(MethodView):
def get(self):
return 'bar view'
routes = [
flask.Pluggable('/', view_func=FooView.as_view('foo'))
flask.Pluggable('/', view_func=BarView.as_view('bar'))
]
Routers for the Flask-Restful framework.
Bases: flask_via.routers.BaseRouter
The Resource router allows you to define Flask-Restful routes and have those API resources added to the application automatically. For this to work you must at init_app time pass a optional keyword argument restful_api to init_app with its value being the restful api extension instance.
Example
app = Flask(__name__)
api = restful.Api(app)
class FooResource(restful.Resource):
def get(self):
return {'hello': 'world'}
routes = [
Resource('/foo', FooResource)
]
via = Via()
via.init_app(
app,
routes_module='flask_via.examples.restful',
restful_api=api)
if __name__ == '__main__':
app.run(debug=True)
Constructor for flask restful resource router.
Parameters: |
|
---|---|
Keyword Arguments: | |
endpoint (str, optional) – Optional, override Flask-Restful automatic endpoint naming |
Adds the restul api resource route to the application.
Parameters: | app (flask.app.Flask) – Flask application instance, this is ignored. |
---|---|
Keyword Arguments: | |
restful_api (str) – Instantiated restful API instace, used to add the route. | |
Raises: | NotImplementedError – If restful_api is not provided |
Without the work of these people or organisations this project would not be possible, we salute you.