Monday, April 1, 2019

Shyama Sankar Vellore: Getting started with Flask: Hello World

In this post, we will learn how to create a very basic "Hello World" web application using Flask and run it locally.

Installation and setup

In this section, we will install Flask and set up our project environment.
Note: The commands I am providing are for setting it up on a MacBook. If you use a different OS, refer to Flask's installation guide: http://flask.pocoo.org/docs/1.0/installation/#installation. But the steps basically remain the same. 
  • Install Python. I am using Python3.
  • Create a directory for your project, say, "hello" and go inside the directory.
  • mkdir hello
    cd hello
  • Now create a virtual environment and activate it.
  • python3 -m venv venv
    . venv/bin/activate
  • Then install Flask within the virtual environment.
  • pip install Flask

Create the Hello World application

Now let us create our Hello World application.
  • Within the project directory, 'hello', create a file, 'hello.py'. This is where we are going to write the code for our application.
  • First, we need to import the module flask and create an instance of class Flask.
    from flask import Flask
    app = Flask(__name__)
    The Flask class implements a WSGI (Web Server Gateway Interface) application. We should pass the name of the Python module or package of our application to it. In this case, we are not creating a package. We are simply creating a module 'hello.py'. Note that __name__ here refers to the name of the module.
  • Next, we will define our hello world method.
    This method returns whatever we want to show in our app.
  • def hello_world():
    return "Hello World!"
  • Finally, we should link this method with a URL. In Flask, we can use the route() decorator to define which URL should trigger a function.
  • @app.route('/')
    def hello_world():
    return "Hello World!"
    This would make the application display "Hello World!" to the console when we go to our website's base URL.
So, now we have a file hello.py with the following content:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
return "Hello World!"

Run the application locally

In this section we will see how to run our application locally on our device.
  • First, tell the terminal which flask application to run. In our case, the application is defined by the 'hello.py' module. Flask uses the environment variable 'FLASK_APP' while looking for the application. So let us set its value.
  • export FLASK_APP=hello.py
  • Now run the application. We have two options for running a flask application.
    1. Using flask run
      flask run
    2. Using python -m flask
      python -m flask run
    This should display something like this on the console:
    Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
  • Let it run and go to a browser and enter the URL "http://127.0.0.1:5000/" in it. You should see our application in action.

Useful tips

Development environment

Earlier, when we ran our flask application, you would have seen an output like:
flask run                      
* Serving Flask app "hello.py"
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
This basically means that we were using "production" environment with "debug" mode turned on for our development purposes. One issue with this during development is that, whenever we make a code change, we would have to restart the application.
Flask provides a "development" environment for dev purposes and this can be very helpful. In "development" environment, the application is reloaded automatically whenever we make a code change. Also, the debug mode gets enabled and the debugger gets activated. You can change the environment by using the "FLASK_ENV" variable:
export FLASK_ENV=development
flask run
* Serving Flask app "hello.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 299-503-654
You may also choose to just enable the debug mode by using environment variable "FLASK_DEBUG":
flask run                  
* Serving Flask app "hello.py" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 299-503-654

Logging

Logging is another important feature that is useful while getting started. Flask provides a preconfigured logger(since version 0.3). This is a standard Python logger. Sample usage:
app.logger.info('Info message...')
app.logger.debug('Debug message...')
app.logger.warning('Warning message...')
app.logger.error('Error message...')

Conclusion

We discussed how to create a very basic "Hello World" app using Flask and run it in our local environments.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...