Mastering Python – Coding Python like a Pro

Subscribe for free YouTube tutorial

In this YouTube series we turn you into a Python Master! Subscribe for free to this new series on YouTube.

Get the source code

Please support our effort and purchase the source code that we created in the YouTube Series:

#1 – Setting up Virtual Environment with Miniconda and Anaconda

In this episode you learn how to install Miniconda and Anaconda and how to setup a virtual environment for Python.

YouTube:

Miniconda:

Download (Linux):

mkdir -p ~/miniconda3
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh

Install (Linux)

bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3
~/miniconda3/bin/conda init bash
Activate conda in current shell session
eval "$(~/miniconda3/bin/conda shell.bash hook)"

Prevent autoactivation of  conda’s base environment on terminal startup

conda config --set auto_activate_base false

Anaconda:

Download (Linux):

curl https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh --output /tmp/anaconda.sh
Install (Linux):
bash /tmp/anaconda.sh -b
Activate conda in current shell session
eval "$(~/anaconda3/bin/conda shell.bash hook)"
conda init

Prevent autoactivation of  conda’s base environment on terminal startup

conda config --set auto_activate_base false

Conda commands:

Create Virtual Environment:

conda create -n <projectname> python=3.10.0

Activate Virtual Environment:

conda activate <projectname>

Deactivate Virtual Environment:

conda deactivate

Delete Virtual Environment and its packages:

conda remove -y -n <projectname> --all

Load environment variables from .env file

.env file:

MY_KEY=4711

app.py:

from dotenv import load_dotenv
import os

load_dotenv()

MY_KEY = os.environ.get("MY_KEY")

def main():
    # Print the result
    print(f"Greetings from Hello World App. My key is: {MY_KEY}")

if __name__ == "__main__":
    main()

#2 – Flask App in a Class

In this episode we dive into Object Oriented Programming (OOP) with Python. In paticular we show you how to wrap a Flask App in a python class. This is especially useful if you want to include Flask based APIs in your object oriented python app.

YouTube:

 app.py:

from flask import Flask

class Flask_OOP():

    @property
    def app(self) -> Flask:
        return self._app
  
    @app.setter
    def app(self, app: Flask):
        self._app = app

    def __init__(self) -> None:
        self.app = Flask(__name__)
        self.register_endpoints()

    def register_endpoints(self):
        self.app.add_url_rule(rule='/', endpoint='helloworld', view_func=self.helloworld, methods=['GET'])

    def helloworld(self):
        return "Greetings from Flask OOP App"

    def run(self, *args, **kwargs):
        self.app.run(*args, **kwargs)

if  __name__ == "__main__":
    myFlaskApp = Flask_OOP()
    myFlaskApp.run(debug=False, port=5100)

#3 – Pass self to another class

Learn how to pass self to the constructor of another class and still take advantage of static type checking in Python. We show you how to fix the ImportError: cannot import name from partially initialized module (most likely due to a circular import) by implementing a Protocol Class.

app.py:

from flask import Flask

from endpoint_helloworld import Endpoint_Helloworld

class Flask_OOP():

    @property
    def app(self) -> Flask:
        return self._app 

    @app.setter
    def app(self, app: Flask):
        self._app = app

    def __init__(self) -> None:
        self.app = Flask(__name__)
        self.register_endpoints()

    def register_endpoints(self):
        helloworld_endpoint = Endpoint_Helloworld(self)
        helloworld_endpoint.register_endpoint()    

    def run(self, *args, **kwargs):
        self.app.run(*args, **kwargs)

if  __name__ == "__main__":
    myFlaskApp = Flask_OOP()
    myFlaskApp.run(debug=False, port=5100)

 app_stub.py:

from flask import Flask
from typing import Protocol

class Flask_OOP_Stub(Protocol):
    @property
    def app(self) -> Flask: ...

endpoint_helloworld.py:

from app_stub import Flask_OOP_Stub

class Endpoint_Helloworld():

    def __init__(self, flask_oop: Flask_OOP_Stub) -> None:
        self.flask_oop = flask_oop
        self.route = '/'
        self.endpoint = 'helloworld'
        self.callback_function = self.helloworld
        self.methods = ['GET']    

    def helloworld(self):
        return "Greetings from Flask OOP App"      

    def register_endpoint(self):    
        self.flask_oop.app.add_url_rule(rule=self.route, endpoint=self.endpoint, view_func=self.callback_function, methods=self.methods)

 #4 – Derive from Base Class

In this video you learn how to create an abstract base class in Python and how to derive your child classes from it. We create an abstract class for endpoints and inherit unique endpoints from this class.

app.py:

from flask import Flask

from endpoint_helloworld import Endpoint_Helloworld

from endpoint_index import Endpoint_Index

class Flask_OOP():

    @property
    def app(self) -> Flask:
        return self._app
 
    @app.setter
    def app(self, app: Flask):
        self._app = app

    def __init__(self) -> None:
        self.app = Flask(__name__)
        self.register_endpoints()

    def register_endpoints(self):
        index_endpoint = Endpoint_Index(self)
        index_endpoint.register_endpoint()

        helloworld_endpoint = Endpoint_Helloworld(self)
        helloworld_endpoint.register_endpoint()    

    def run(self, *args, **kwargs):
        self.app.run(*args, **kwargs)

if  __name__ == "__main__":
    myFlaskApp = Flask_OOP()
    myFlaskApp.run(debug=False, port=5100)

 app_stub.py:

from flask import Flask
from typing import Protocol

class Flask_OOP_Stub(Protocol):
    @property
    def app(self) -> Flask: ...

endpoint_abstract.py:

from app_stub import Flask_OOP_Stub
from abc import ABC

class Endpoint_Abstract(ABC):
    route: str = None
    endpoint: str = None
    callback_function: str = None
    methods: list = None  
  
    def __init__(self, flask_oop: Flask_OOP_Stub) -> None:
        self.flask_oop = flask_oop

    def register_endpoint(self):    
        self.flask_oop.app.add_url_rule(rule=self.route, endpoint=self.endpoint, view_func=self.callback_function, methods=self.methods)

endpoint_index.py:

from app_stub import Flask_OOP_Stub
from endpoint_abstract import Endpoint_Abstract

class Endpoint_Index(Endpoint_Abstract):

    def __init__(self, flask_oop: Flask_OOP_Stub) -> None:
        super().__init__(flask_oop)

        self.route = '/'
        self.endpoint = 'index'
        self.callback_function = self.index
        self.methods = ['GET']    

    def index(self):
        return "Greetings from Flask OOP Index Endpoint"

endpoint_helloworld.py:

from app_stub import Flask_OOP_Stub
from endpoint_abstract import Endpoint_Abstract

class Endpoint_Helloworld(Endpoint_Abstract):
    def __init__(self, flask_oop: Flask_OOP_Stub) -> None:
        super().__init__(flask_oop)

        self.route = '/helloworld'
        self.endpoint = 'helloworld'
        self.callback_function = self.helloworld
        self.methods = ['GET']    

    def helloworld(self):
        return "Greetings from Flask OOP Helloworld Endpoint"

Need further support or consulting?

Please checkout our Consulting hours.

Leave a Reply

Your email address will not be published. Required fields are marked *