TV Channel Website: Environment Variable & Database
Tags: webdev, tutorial, python, bottle
Published: 2022-08-23 07:54:00

GitHub: [https://github.com/Sokhavuth/TV-Channel](https://github.com/Sokhavuth/TV-Channel)
Vercel: [https://khmerweb-tv-channel.vercel.app/](https://khmerweb-tv-channel.vercel.app/)
<br/>

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

```
pip install python-dotenv
```
<p>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.</p>

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

```
pip install pymongo
```
<p>To create and save user session, we can use Redis database by creating an account with <a href="https://redis.com/redis-enterprise-software/overview/">Redis Enterprise</a> platform and installing Redis package for Python.</p>

```
pip install redis
```
<p>One more thing, to authenticate user, we can use JSON Web Token (JWT) by installing PyJWT package.</p>

```
pip install PyJWT
```
<p>When everything is installed, we can create a configuration file to configure and setup database connections.</p>

```python
# 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,
}
```
```
# .env

SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DATABASE_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DB_NAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_PASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
REDIS_PORT=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
<p>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.</p>

```python
# 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)

###################################################################
```

```python
# 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)

```

```html
<!--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>
```