Created
June 2, 2017 09:23
-
-
Save dboyliao/9bb9e00a8df83423a69bf70862deb1ac to your computer and use it in GitHub Desktop.
A simple example using flask endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from __future__ import print_function | |
| from flask import Flask, url_for, redirect | |
| import argparse | |
| app = Flask(__name__) | |
| # If you look at the source code of `Flask.route`, | |
| # endpoint is just a key for Flask to route incoming | |
| # request to view function (like `hello` function here). | |
| # In this case, all request to `/` or `/<name>` will be | |
| # handled by `hello`. | |
| # By default, if the endpoint is not specified, it will | |
| # be setup as function name. ("hello" in this case if you | |
| # remove endpoint="hello_func") | |
| @app.route("/") | |
| @app.route("/<name>", endpoint="hello_func") | |
| def hello(name = None): | |
| return "Hello, {}".format(name is None and "World" or name) | |
| # Here you can see the benefit of using endpoint. | |
| # You can redirect incomming request to other view | |
| # function via endpoint which you assigned to it. | |
| # In this case, you redirect the request to `/test` | |
| # to `/endpoint_example`. | |
| @app.route("/test") | |
| def test(): | |
| return redirect(url_for("hello_func", name="endpoint_example")) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("-p", "--port", dest="port", default=3333, type=int, help="port number (default: 3333)", metavar="INT") | |
| parser.add_argument("-H", "--host", dest="host", default="127.0.0.1", help='host address (default: localhost)', metavar="ADDR") | |
| parser.add_argument("-d", "--debug", action="store_true", help="running in debug mode (default: False)") | |
| args = vars(parser.parse_args()) | |
| app.run(**args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment