Build a Blog App using Flask, Angular and MySql using Ubuntu (Part 2) - Setup Flask

Subscribe to my newsletter and never miss my upcoming articles

Part - 2 Setting Up Flask App

So first you need to setup the virtualenv for your project. For this project we will be using python3.6. We need to install virtualenv first. If you dont have virtualenv installed follow the below instructions:

$ sudo apt-get install python-virtualenv

Virtualenv is installed. Now to use it for my project:

$ cd flask-boilerplate
$ virtualenv -p python3.6 venv --no-site-packages

This will create a venv folder and activate python3.6 for my project. To check:

$ python -V Python 3.6.3
$ pip -V pip 9.0.1

Next I will be setting up flask for my project

$ pip install flask

This will setup flask for my project, Quickly setting up a route to check if everything works fine

Create a app.py

from flask import Flask
app = Flask(__name__)


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

if __name__ == '__main__'
   app.run(host="0.0.0.0",port=3000,debug=True)

Run the script in the project directory :

$ python app.py

Opening up http://localhost:3000 , It displays Hello, World!

Now I want to change the structure of the project, so that it can be bit modular

/flask-boilerplate /myapp -__init__.py /templates /layouts /forms /pages -home.html -blog.html /venv run.py

Lets create blog.html and home.html for our routes inside the templates/pages folder

home.html

<!doctype html>
<html>
   <body>

      <h1>Hello, World ! </h1>

   </body>
</html>

Similarly, blog.html

<!doctype html>
<html>
   <body>

      <h1>Our Blog </h1>

   </body>
</html>

We need to initialize myapp package using "init.py" inside myapp folder

inside init.py

from flask import Flask, render_template
app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('/pages/home.html')

@app.route('/blog')
def blog():
    return render_template('/pages/blog.html')

inside run.py

```python
from myapp import app

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

Now I can run the app using

$ python run.py

You can also add a FLASK configuration variable to run the app using flask command

$ export FLASK_APP = run.py

Now you can run the app using the below command :

$ flask run

In the next part we will be setting up Flask SQLAlchemy for setting up our models and Database to save our Data.

No Comments Yet