Introduction to Flask

Like most popular open source projects, Flask has very good documentation, available at http://flask.pocoo.org/docs/0.10/. If any of the examples are unclear, you can be sure to find the answer on the project documentation.

I would also highly recommend Miguel Grinberg's (https://blog.miguelgrinberg.com/) work related to Flask. His blog, book, and video training has taught me a lot about Flask. In fact, Miguel's class Building Web APIs with Flask inspired me to write this chapter. You can take a look at his published code on GitHub: https://github.com/miguelgrinberg/oreilly-flask-apis-video.

Our first Flask application is contained in one single file, namely chapter9_1.py:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_networkers():
return 'Hello Networkers!'

if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)

This will almost always be your design pattern for Flask initially. We create an instance of the Flask class with the first argument as the name of the application's module package. In this case, we used a single module; while doing this yourselves, type the name of your choice to indicate whether it is started as an application or imported as a module. We then use the route decorator to tell Flask which URL should be handled by the hello_networkers() function; in this case, we indicated the root path. We end the file with the usual name (https://docs.python.org/3.5/library/__main__.html). We only added the host and debug options, which allow more verbose output and also allow you to listen on all the interfaces of the host (by default, it only listens on loopback). We can run this application using the development server:

(venv) $ python chapter9_1.py
* Running on http://0.0.0.0:5000/
* Restarting with reloader

Now that we have a server running, let's test the server response with an HTTP client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.50