Keeping Secrets in Code

The problem of keeping secrets – usernames, passwords, API keys, etc, in code that you write is a pretty old problem. I haven’t had a solution that I liked – especially when I am putting code up on github, for a long time.

Until now. I am putting things like that in a “secrets” file, or in environment variables, which are easy to access from your code, but don’t show up in your code repository. Here’s an example in Python of keeping a “secrets” file that the script can access, and then yoinking its contents into a dictionary for easy reference:

def getSecrets():

def getSecrets():
  SECRETFILE = os.environ["SECRETFILE"]
  with open(SECRETFILE , "r") as scrts:
    return dict(line.strip().split("=====") for line in scrts)

secrets = getSecrets()

api_url = secrets["Test API URL"]
api_key = secrets["Test API Key"]

""" The file itself would look like this:

API Key=====zEV}pF_vn4g35Ye:
API URL=====https://example.com
..."""

Padding Numbers in Filenames

I sometimes find myself with scads of files in a directory that, due to the vagaries of sort() do not show up in the “right” order. For example, 1.png, 2.png, … 751.png.

I was poking around with rename, but I wasn’t finding a good way to do this. Thankfully, a poster on TLUG showed me how to use sprintf to get the results I wanted, like so:

rename -n 's/(\d+)/sprintf("%04d", $1)/e' *.png

Very neat.

Go to Date WordPress Widget

This is the widget code to have a Go to Date widget in WordPress. It requires the correct permalink structure, but it is easy to paste into a text widget and it works nicely.

<script type="text/javascript">

function gotodate() {
  var baseurl = "http://example.com/index.php/"
  
  var y = document.getElementById("year").value;
  var m = document.getElementById("month").value;
  var d = document.getElementById("day").value;
  //debug alert(y + m + d);
  
  var newloc = baseurl + y + "/" + m + "/" + d
  window.location = newloc
}



<form>
  <table>
    <tr>
      <td>Year:</td>
      <td>Month:</td>
      <td>Day:</td>
      <td> </td>
    </tr>
    <tr>
      <td><input type="text" id="year" size="4" maxlength="4" /></td>
      <td><input type="text" id="month" size="2" maxlength="2" /></td>
      <td><input type="text" id="day" size="2" maxlength="2" /></td>
      <td><input type="button" value="Go" onclick="javascript:gotodate();" /></td>
    </tr>
</table>
</form>