Inspecting and replaying requests with ngrok

A very cool feature of ngrok is the web interface. With this interface you can inspect requests and replay them. Very handy for debugging purposes.

The web interface can be reached on http://localhost:4040.

In the web interface you can view both the request received and response sent. The default view of the request and response is a summary of the post data, but it can be viewed in raw format or binary format. This is really useful when debugging webhooks.

Another great feature of this web interface is the replay functionality. Instead of having to run through the code again to get to the problem, you can just hit the resend button and the request will be resent.

Flask error loading config file in instance directory

I have been dealing with a really frustrating problem today. Yesterday my code was working and today it was failed without any code changes.

This is the piece of code causing the problem.

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.cfg')

And this is the error.

Traceback (most recent call last):
  File "run.py", line 1, in 
    from project import app
  File "C:\Python27\env\vod_test\src\project\__init__.py", line 37, in 
    load_config()
  File "C:\Python27\env\vod_test\src\project\__init__.py", line 33, in load_config
    app.config.from_pyfile('config.cfg')
  File "C:\Python27\env\vod_test\lib\site-packages\flask\config.py", line 129, in from_pyfile
    with open(filename) as config_file:
IOError: [Errno 2] Unable to load configuration file (No such file or directory): 'C:\\Python27\\env\\vod_test\\var\\project-instance\\config.cfg'

Flask is trying to load the config file from C:\\Python27\\env\\vod_test\\var\\project-instance\\config.cfg instead of from C:\\Python27\\env\\vod_test\\project\\instance\\config.cfg. Where is the var coming from? And why is there a hyphen between project and instance?

The strange thing was that the problem only occurred when I was running my test cases from the command line. In PyCharm the code was working. How frustrating. It turned out that PyCharm was using a different virtualenv than the command line. After comparing the output of ‘pip freeze’ I discovered that some libraries had different versions.

To solve the problem I added the following code.

import os
from flask import Flask


def load_instance_config_fix(filename):
    config = {}
    with app.open_instance_resource(filename) as f:
        for line in f:
            if line[0] == "#":
                continue
            name, value = line.partition("=")[::2]
            config[name.strip()] = value.strip()
    return config


def handle_incorrect_instance_path(f):
    def handle_load_instance_config():
        try:
            f()
        except IOError:
            app.instance_path = os.path.join(os.path.abspath(os.curdir), 'instance')
            config = load_instance_config_fix('config.cfg')
            app.config.update(config)

    return handle_load_instance_config


@handle_incorrect_instance_path
def load_config():
    app.config.from_object('config')
    app.config.from_pyfile('config.cfg')


app = Flask(__name__, instance_relative_config=True)

load_config()


@app.route('/')
def hello_world():
    return 'Hello, World!'

Just some nice syntactic sugar with a decorator to keep the code nice and concise.

Another way to solve the problem is by setting the instance_path when initializing Flask. What fun would that be 🙂

import os
from flask import Flask


app = Flask(__name__, instance_path=os.path.join(os.path.abspath(os.curdir), 'instance'), instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.cfg')


@app.route('/')
def hello_world():
    return 'Hello, World!'

Back to real coding 🙂

Git quickstart

Just some short notes to remember how to get started with Git.

Check version

$ git --version

Setting-up

Set the following configuration items if using Git for the first time, as these values are used for each commit made.

$ git config --global user.name "Your Name"
$ git config --global user.email "your.email@address.com"

Initializing a new Git repository

Make sure you are in the top-level folder of your project and then run the following command.

$ git init

Create the .gitignore file

Git has a special file called ‘.gitignore’ that allows you to specify which files to NOT include in your repository.  The following file is based on the recommended .gitignore file for Python from GitHub.

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
 
# PyCharm files
.idea/
 
# Instance Folder - used for sensitive configuration parameters
/instance

Setting remote repository
Make sure you are in the top-level folder of your project and set up the remote repository.

$ git remote add origin git@gitlab.com:nidkil/name-of-repository.git

Check the remote repository has been set correctly.

$ git remote -v

Staging files
The standard flow for adding files to your git repository is to create/edit the files, add them to the staging area, and then commit them to your repository.

$ git status
$ git add .
$ git status

Initial commit
The following command makes the first commit to the repository, including a message describing the commit.

git commit -m "Initial version"

You can confirm that the commit was successful by checking the log of the repository.

git log

Push to the remote repository
To push the local Git repository to the remote Git repository.

$ git push -u origin master

Working with a feature branch
A common method of developing features is to create a feature branch where you implement specific functionality and then merge the changes back into the master or development branch. Follow the process: create a new feature branch, make changes and merge changes back into the ‘master’ branch.

Create a new feature branch.

$ git checkout -b name_of_feature_branch

Check new feature branch was created (the star next to ‘name_of_feature_branch’ branch indicates it is the current branch that we are working in).

$ git branch

The following commands stage, commit and merge the changes into the local repository.

$ git add .
$ git status
$ git commit -m “Added use of templates and Bootstrap”
$ git checkout master
$ git merge add_templates

Delete the branch.

$ git branch -d add_templates

Push the changes into the remote repository.

$ git push -u origin master

Marshmallow not respecting ordered=True

I had a little fight with Marshmallow and the ordered=True in class Meta. When ordered=True is set the fields should be outputed in the order specified in the property fields of the class Meta.

Example:

class AuthorSchema(ma.Schema):
    id = base_fields.Int(dump_only=True)

    absolute_url = ma.AbsoluteURLFor('api.author', id='<id>')

    links = ma.Hyperlinks({
        'self': ma.URLFor('api.author', id='<id>'),
        'collection': ma.URLFor('api.authors')
    })

    @post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'authors' if many else 'author'
        return {
            key: data
        }

    class Meta:
        fields = (
            'id',
            'name',
            'links',
            'absolute_url',
        )
        ordered = True

This was the output.

{
  "author": {
    "absolute_url": "http://localhost:8080/api/v4/authors/123",
    "id": 123,
    "links": {
      "collection": "/api/v4/authors/",
      "self": "/api/v4/authors/123"
    },
    "name": "Fred Douglass"
  }
}

After some Googeling I found out that the culprit was Flask.jsonify. It orders output alphabetically by default. The following setting switches this off.

app.config['JSON_SORT_KEYS'] = False

After this the output was in the specified order.

{
  "author": {
    "id": 123,
    "name": "Fred Douglass",
    "links": {
      "self": "/api/v4/authors/123",
      "collection": "/api/v4/authors/"
    },
    "absolute_url": "http://localhost:8080/api/v4/authors/123"
  }
}

Hope this saves someone else time.

Changing location of virtual environments breaks virtualenvwrapper-win

Today I wanted to move the location of my virtual environments to Dropbox. Makes life easier if I ever have to change computers. I moved the directory that contains the virtual environments and set the system variable WORKON_HOME to the new location. Then I tried it out. Activating the virtual environment with command workon worked just fine. Then I wanted to switch to the virtual environment with the command cdvirtualenv and it failed with an error saying that the location did not exist.

Puzzled I checked the system variables with the command set (I’m running Windows 10) and I noticed the system variable VIRTUAL_ENV that was pointing to the old location. I checked my variable settings under “System” → “Advanced system settings” → “Environment Variables” and could not find it there. Which meant it was being set somewhere when activating the virtual environment. After searching all the virtualenvwrapper-win scripts I could not find “SET VIRTUAL ENV=”. Then I noticed that the “workon.bat” file called “activate.bat” located in the script directory of the virtual environment. Here I found the “SET VIRTUAL ENV=” which contained a hard coded location, which was the old WORKON_HOME location as the virtual environment already existed.

To fix the problem I had to change this line of each “activate.bat” file manually. After that it worked like a dream. Problem solved!

By the way this isn’t a virtualenvwrapper-win problem, but a virtualenv problem.

UPDATE 4-1-2017

During a little break laying in the bath I came up with a much quicker and easier approach to solving the problem… Creating a symbolic link from the old location to the new location.

Just fire up a console with administrator rights and execute the following command.

mklink /d <old directory location> <new directory location>

Hmmmmm, that was quick 🙂

More Flask debugging tricks

I was busy debugging a rest services I’m building in Flask and Flask-Restplus. I needed a way to log the request and response. I found some code that can be used as a wrapper of the WSGI application that does just this.

Create a file called dubug.py that contains the following code.

import pprint

class RequestLoggingWrapper(object):
    def __init__(self, app):
        self._app = app

    def __call__(self, environ, resp):
        errorlog = environ['wsgi.errors']
        pprint.pprint(('REQUEST', environ), stream=errorlog)

        def log_response(status, headers, *args):
            pprint.pprint(('RESPONSE', status, headers), stream=errorlog)
            return resp(status, headers, *args)

        return self._app(environ, log_response)

This wrapper works independently from Flask and wraps the WSGI application. It shows exactly what request is going in and what response is going out.

When running Flask with the built-in server you can use it as follows.

from debug import RequestLoggingWrapper

if __name__ == '__main__':
    app.wsgi_app = RequestLoggingWrapper(app.wsgi_app)
    app.run()

The output goes to the wgi.error stream. For the built Flask server it is printed to stderr.

Flask request debugging

I needed to debug the Flask request. After googeling around for a while I ran into a cool trick on Stack Overflow using the pprint module. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.

import pprint
str = pprint.pformat(request.environ, depth=5)

This same trick can be used with all the Flask variables.

  • request.args: the key/value pairs in the URL query string
  • request.form: the key/value pairs in the body, as sent by a HTML POST form
  • request.files: the files in the body, which Flask keeps separate from form
  • request.values: combined args and form, preferring args if keys overlap

Cheatsheet virtualenvwrapper

This is a cheatsheet for virtualwrapper.

Install virtualenvwrapper

pip install virtualenv

pip install virtualenvwrapper-win

Set environment variable

Add an environment variable WORKON_HOME to specify the path to store environments. By default, this is %USERPROFILE%\Envs. I have set it to the following.

WORKON_HOME=%PYTHON27%\env

Main commands

mkvirtualenv <name>

lsvirtualenv

workon <name>

cdvirtualenv

deactivate

add2virtualenv <full or relative path>

setprojectdir <full or relative path>

cdproject

cdsitepackages

lssitepackages