8.23.2017

Use httpie to play with your APIs

Got tired of using curl. I switched to httpie.

1. Install
$ pip3 install httpie

2. I use jwt
$ pip3 install -U httpie-jwt-auth

3. First get token
$ http POST :8001/api-token-auth/ 'username=admin' 'password=abc123'

4. Now set env variables
$ export JWT_AUTH_TOKEN=your_token
$ export JWT_AUTH_PREFIX=JWT

5. Now do whatever
$ http --auth-type=jwt :8001/users/

6. If this error is encountered...
SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Use --verify=no as in...

$ http --verify=no POST ...

8.17.2017

Django LDAP Logging

Got from here

Add in settings.py

import logging, logging.handlers
logfile = "/tmp/django-ldap-debug.log"
my_logger = logging.getLogger('django_auth_ldap')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
   logfile, maxBytes=1024 * 500, backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
my_logger.addHandler(handler)

8.10.2017

Angular Starter Project with Material

Follow angular setup from this post.
Reference posts from here and here. And from a starter project.

1. Create angular project
$ ng new management-gui
$ cd management-gui

2. Get Angular Material
$ yarn add @angular/material @angular/animations @angular/cdk

3. Get HammerJs and add to .angular-cli.json
$ yarn add hammerjs
$ vi .angular-cli.json
"scripts": [
  "../node_modules/hammerjs/hammer.min.js"
],

4. Add Angular Material on to app.module.ts
$ vi src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import 'hammerjs';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5. Set global styles.css with an Angular Material theme
$ vi src/styles.css
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

6. Add Material icons in index.html
$ vi src/index.html



8.09.2017

Django Development Production Settings

I choose the 2nd solution from this post

Dir structure:
[myapp]$ tree
.
├── __init__.py
├── settings
│   ├── __init__.py
│   ├── defaults.py
│   ├── development.py
│   ├── production.py
│   └── staging.py

### __init.py__
from myapp.settings.development import *

### defaults.py
### sensible choices for default settings

### dev.py
from myapp.settings.defaults import *
DEBUG = True
### other development-specific stuff

### production.py
from myapp.settings.defaults import *
DEBUG = False
### other production-specific stuff

### staging.py
from myapp.settings.defaults import *
DEBUG = True
### other staging-specific stuff

7.26.2017

Django Data Seeding

This is a more flexible way of seeding data

1. Create required directories and files
$ mkdir testapp/management
$ mkdir testapp/management/commands
$ touch testapp/management/__init__.py
$ touch testapp/management/commands/__init__.py

2. Write code that populates the db
$ vi testapp/management/commands/populate_db.py
from django.core.management.base import BaseCommand
from testapp.models import Region
from django.db import connection

class Command(BaseCommand):
    args = ''
    help = 'Management script that populates the database with initial seed'

    def _truncate_region(self):
        cursor = connection.cursor()
        cursor.execute("TRUNCATE TABLE `testapp_region`")

    def _create_regions(self):
        regions = (
        ('REG001', [
                {"name": "vmk-4027","vlanId":4027,"usefor":["vsan","nfs"]},
                {"name": "vmk-4028","vlanId":4028,"usefor":["traffic"]},
                {"name": "vmk-102","vlanId":102,"usefor":["pub"]},
            ]),
        ('REG002', [
                {"name": "vmk-4029","vlanId":4029,"usefor":["vsan","nfs"]},
                {"name": "vmk-4030","vlanId":4030,"usefor":["traffic"]},
                {"name": "vmk-102","vlanId":103,"usefor":["pub"]},
            ]),
        )
        for item in regions:
            region = Region(name=item[0], vlans=item[1])
            region.save()

    def handle(self, *args, **options):
        self._truncate_region()
        self._create_regions()

3. Execute the program
$ python manage.py populate_db


7.25.2017

Async Background Tasks with Celery on Django

From this post and this post and this post

1. Install Redis - got from here
$ brew install redis
$ ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist
$ redis-cli PING
PONG

2. Install celery with redis support bundle
$ pip3 install -U "celery[redis]"

3. Create celery.py in django project
$ vi sample_project/sample_project/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample_project.settings')

app = Celery('sample_project')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

4. Import celery app in __init__.py
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

5. Add config in settings.py
$ vi sample_project/sample_project/settings.py
# celery
CELERY_BROKER_URL = 'redis://localhost:6379/0'

6. Create app
$ python3 manage.py startapp testapp
$ vi sample_project/sample_project/settings.py
INSTALLED_APPS = (
    # (...)
    'testapp',
)

7. Create task
$ vi sample_project/sample_project/testapp/tasks.py
from __future__ import absolute_import

from celery import shared_task

@shared_task
def test(param):
    return 'The test task executed with argument "%s" ' % param

8. Testing

Run server
$ python3 manage.py runserver

Run worker
$ celery -A sample_project worker --loglevel=info

From another terminal...
$ python3 manage.py shell
Python 3.6.2 (default, Jul 17 2017, 16:44:45)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from testapp.tasks import test
>>> test.delay('This is a test')


From the worker terminal
2017-07-26 00:50:54,529: INFO/MainProcess] Received task: testapp.tasks.test[4f1ab1d4-645d-480b-a1b5-6e2887e34b52]
[2017-07-26 00:50:54,533: INFO/ForkPoolWorker-2] Task testapp.tasks.test[4f1ab1d4-645d-480b-a1b5-6e2887e34b52] succeeded in 0.0010309600038453937s: 'The test task executed with argument "This is a test" '

9. For results backend using Django ORM

a. $ pip3 install django-celery-results

b. Install app in settings.py
INSTALLED_APPS = (
    ...,
    'django_celery_results',
)

c. Create celery database tables
$ python3 manage.py migrate django_celery_results

d. Configure Celery to use the django-celery-results backend.
In settings.py...
CELERY_RESULT_BACKEND = 'django-db'

Django with Postgres on Mac

1. Create virtual env following this post
2. Install django
(my_env) $ pip3 install psycopg2
(my_env) $ pip3 install django
3. Create django project
(my_env) $ django-admin startproject sample_project
(my_env) $ python3 manage.py runserver
4. Install postgres following this post
5. Create database
$ createdb -U postgres testdb
6. Modify settings in django
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'testdb',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
7. Migrate
$ python3 manage.py migrate
8. Create superuser
$ python3 manage.py createsuperuser