Python – Storing Keys In JSON File & Using .gitignore

Overview
When using a public GitHub repository, you don’t want to expose your server name, passwords, API key, or JWT Token Secret etc. One way to avoid this, is to use a JSON file to store your keys and a Git Ignore (.gitignore) file to omit them from the GitHub repository.
If you do not have a repository, create one on GitHub and clone it to your machine.
Move all of your python related files over to this folder.
In the root folder of your project create a file labeled “.gitignore“.
Inside .gitignore use the following:
# Application Keys
appkeys.json
# Distribution / packaging
.Python
build/
dist/
downloads/
vflask/
venv/
s/
~/
.vscode/
Create a file labeled appkeys.json and put in the following information.
{"driver": "{SQL Server Native Client 11.0}", "server":"YOUR_PC_NAME;", "database":"YOUR_DB_NAME", "password":"YOUR_PASSWORD", "trusted": "yes;"}
From your Flask Application add the following code to get the keys from your JSON file and connect to your MS SQL Server database.
You will need to import the following libraries.
import pyodbc
import json
from flask import Flask, render_template, request
All together for the python file.
import pyodbc
import json
from flask import Flask, render_template, request
app = Flask(__name__)
with open('./appkeys.json') as f:
__data = json.load(f)
__driver = __data['driver']
__server = __data['server']
__database = __data['database']
__password = __data['password']
__trusted = __data['trusted']
__connection = pyodbc.connect(Driver=__driver,
Server=__server,
Database=__database,
Trusted_Connection=__trusted)
cursor = __connection.cursor()
@app.route('/')
def index():
data = cursor.execute('SELECT * FROM Companies')
return render_template('search.html' , data=data)
Remember double underline before a variable ” __ variable” sets it to Private.
For the html template under the templates folder
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-12">
<table class="table mt-5">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{item.Id}}</td>
<td>{{item.Company}}</td>
<td>{{item.TickerSymbol}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}
You must be logged in to post a comment.