DEV Community

Cover image for TV Channel Website: Environment Variable & Database
Sokhavuth TIN
Sokhavuth TIN

Posted on

TV Channel Website: Environment Variable & Database

GitHub: https://github.com/Sokhavuth/TV-Channel
Vercel: https://khmerweb-tv-channel.vercel.app/

To create and use environment variables in our project, we need to install a package for that such as python-dotenv for example.

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

As for the database, we could use MongoDB Atlas. If we have already an account with this modern database, we could create an environment variable for the URL to this database and connect to it using environment variable.

However, for Python to work smoothly with MongoDB Atlas, we need to install pymongo package.

pip install pymongo
Enter fullscreen mode Exit fullscreen mode

To create and save user session, we can use Redis database by creating an account with Redis Enterprise platform and installing Redis package for Python.

pip install redis
Enter fullscreen mode Exit fullscreen mode

One more thing, to authenticate user, we can use JSON Web Token (JWT) by installing PyJWT package.

pip install PyJWT
Enter fullscreen mode Exit fullscreen mode

When everything is installed, we can create a configuration file to configure and setup database connections.

# config.py
# pip install python-dotenv
# pip install PyJWT
# pip install pymongo
# pip install redis


def settings():
    setup = {
        "siteTitle": "TV Channel",
        "pageTitle": "",
    }

    return setup


import os
from dotenv import load_dotenv
load_dotenv()
secret_key = os.getenv("SECRET_KEY")


import pymongo
client = pymongo.MongoClient(os.getenv("DATABASE_URI"))
db = client[os.getenv("DB_NAME")]


import redis
redis = redis.Redis(
    host = os.getenv("REDIS_URI"),
    port = int(os.getenv("REDIS_PORT")), 
    password = os.getenv("REDIS_PASSWORD")
)


configure = { 
    "settings": settings, 
    "secret_key": secret_key, 
    "db": db, 
    "redis": redis,
}
Enter fullscreen mode Exit fullscreen mode
# .env

SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DATABASE_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DB_NAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_PASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_PORT=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

We can import the configuration in the above file across different module. However, the best way is to store the configure object in the main application object. Doing so, we can use this configuration in any module through the request object.

# index.py

from bottle import static_file, get
from routes.frontend import index
import config


app = index.appIndex
app.config["myapp.config"] = config.configure

@app.get('/static/<filepath:path>')
def staticFile(filepath):
    return static_file(filepath, root="public")


###################################################################
import socket
host = socket.getfqdn()    
addr = socket.gethostbyname(host)
if(addr == '127.0.1.1'):
    app.run(host='localhost', port=8000, debug=True, reloader=True)

###################################################################
Enter fullscreen mode Exit fullscreen mode
# routes/frontend/index.py

from bottle import Bottle, template, get, request
from copy import deepcopy


appIndex = Bottle()

@appIndex.get('/')
def indexHandler():
    config = request.app.config["myapp.config"]
    settings = deepcopy(config["settings"])
    setup = settings()
    setup["message"] = "Hello World!"

    return template('base', data=setup)

Enter fullscreen mode Exit fullscreen mode
<!--views/base.tpl-->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>{{ data["siteTitle"] }}</title>
        <script src="/static/scripts/jquery.js"></script>
        <link href="/static/images/sitelogo.png" rel="icon" />
        <link href="/static/fonts/setup.css" rel="stylesheet" />
        <link href="/static/styles/base.css" rel="stylesheet" />
    </head>
    <body>
        {{ data["message"] }}
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay