Accessing an sqlite3 database

To access sqlite3 from the command line.

$ sqlite3

Now you are in the sqlite3 shell. Next connect to an sqlite3 database called db.sqlite3

sqlite> .open db.sqlite3

List tables in database

sqlite> .tables

Let us see what is in the table called table_name

sqlite> select * from table_name;

Not forgetting the trailing semicolon.
Ctrl+D will allow you exit this shell.
To view a table’s field names,

sqlite> PRAGMA table_info(table_name);

To view a table’s schema,

sqlite> .schema table_name

Setting up Python Virtual Environment using Command Line

It is easy to set up virtual environments using an IDE such as PyCharm, but here is how to do it with the command line. Here the virtual environment is called ‘gummienv’.
First set up a directory and cd into it.

$ mkdir gummi
$ cd gummi/
$ sudo pip install virtualenv
$ virtualenv gummienv,

Activate the virtual environment using,

$ source gummienv/bin/activate

Notice the name of the virtual environment is now in the command line prompt.

Selection_010
The virtual environment can be deactivated with,

$ deactivate

Python Dictionary into HTML Template

The following Python code will find instances of {body} in a file template.html and replace it with a string. Then a new file index.html is created with this change.

generate.py

with open('template.html','r') as template_file:
    template = template_file.read()

tokens = {'title': 'My Title in a Dictionary', 'header':'Stuff for heading', 'body': 'The body stuff', 'footer': 'This is the footer'}
content = template

for token in tokens:
    content = content.replace('{' + token + '}', tokens[token])

with open('index.html', 'w') as content_file:
     content_file.write(content)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{title}</title>
</head>
    <div><p>{header}</p></div>
    <div><p>{body}</p></div>
    <div><p>{footer}</p></div>
</html>

Simple Python into HTML

The following Python code will find instances of {body} in a file template.html and replace it with a string. Then a new file index.html is created with this change.

generate.py

with open('template.html','r') as template_file:
    template = template_file.read()

content = template
tokens = {'body': 'Body stuff can go here'}
replaced = 'Body stuff can go here.'
content = content.replace('{' + 'body' + '}', replaced)

with open('index.html', 'w') as content_file:
     content_file.write(content)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
    <div><p>{body}</p></div>
</html>

Running Python unittests from Command Line

This script will allow a Python unittest to be run from the command line.

import unittest
import testFile
suite = unittest.TestLoader().loadTestsFromModule(testFile)
unittest.TextTestRunner().run(suite)

testFile.py

import unittest
from fun import add

class test_function(unittest.TestCase):
     def test_one(self):
           result = add(2,3)
           self.assertEquals(result, 5)

fun.py

def add(a,b):
     return a+b

Using Python to Connect to a MongoDB

This code uses Python to connect to a mongoDB, allowing for print out of the names of all the databases and the names of the collections in a given database, which is in this example is called ‘mydb’.

import pymongo
def mongo_connect():
    try:
         conn = pymongo.MongoClient()
         print "Mongo is connected"
         return conn
    except pymongo.errors.ConnectionFailure, e:
         print "Could not connect to MongoDB: %s" % e
conn  = mongo_connect()
print "Database names: %s" % conn.database_names()
db = conn.mydb
coll = db.collection_names()

print "Database name: %s" % db.name
print "Collection names: %s" % coll

Simple Python Unit Test

This simple Python unit-test tests two function. The first function adds two numbers and the second function uses list comprehensions to make a list of numbers from to 0 to n which are divisible by m.
testFile.py

import unittest
from add import addition, make_list

class test_add_function(unittest.TestCase):

    def test_for_add(self):
        result = addition(1, 5)
        self.assertEqual(result, 6)

    def test_multiples_of_3_less_than_10(self):
        result = make_list(10, 3)
        self.assertEquals(result, [0, 3, 6, 9])

The file containing the functions,
add.py

def addition(a,b):
    return a+b

def make_list(n, m):
    return [i for i in range(n) if i%m == 0]

Part 1: Setting up Django and virtualenv

First create a new directory for your project

$ mkdir djangoCRUD

Move to that directory

$ cd djangoCRUD

Set up a virtual environment.

$ virtualenv .

$ source bin/activate

Use pip list to see the modules in this virtual environment.

$ pip list

Now we can install the Django package

$ pip install django

Run pip list again and you will see that django is now part of this environment.

If requested to do so, it is a good idea to upgrade pip,

$ pip install --upgrade pip

Next set up your Django project

$ django-admin startproject crudProject

Change directory into your Django project directory,

$ cd crudProject

Now create an app for your project. To do this you must be in the same directory as the manage.py file.

$ python manage.py startapp crudapp

Note: it is also possible to start a new app using with,

$ django-admin startapp crudapp

Make the database tables with,

$ python manage.py makemigrations
$ python manage.py migrate

After this has been done we can create a super user.

$ python manage.py createsuperuser

Next we will turn on the server,

$ python manage.py runserver

Navigate in your browser to localhost:8000

sqlite is the default database. Ignore the following if you do not want to use a mysql database.
Presuming you have a mysql database set up and running with a user associated with it then in mysite/settings.py

DATABASES = {
    `default' = {
        `ENGINE' : `django.db.backends.mysql',
        `NAME' : `&lt db-name>',
        `USER' : `&lt db-user>',
        `PASSWORD' : `&lt password>',
        `HOST' : `localhost', 
        `PORT' : `',
   }
}

Part 2: Setting up Django, URLs & Views

Angular Service Example

The following code demonstrates how a service can be created in AngularJS.

index.html

<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.min.js"></script>
 <script src="app.js"></script>
 <script src="anotherModule.js"></script>
 </head>
 <body>
 <div ng-app="mainModule" ng-controller="mainController as alias">
 <b>Invoice:</b>
 <p>The input is: {{alias.quantity}}</p>
 <div>
 Quantity: <input type="number" min="0" ng-model="alias.quantity"required>
 </div>
 <div><p>Add 4 and double it!</p></div>
 <div>
 <b>Result:</b>
 <span>{{alias.total(alias.quantity)}}</span>
 <button class="btn" ng-click="alias.paid(alias.total(alias.quantity))">Pay</button>
 </div>
 </div>
 </body>
</html>

app.js

angular.module('mainModule', ['dependencyModule'])
.controller('mainController', ['theService', function(theService) {

  this.quantity = 1;

  this.total = function total(number) {
    return theService.inService(number + 4);
  };

  this.paid = function pay(parameter) {
    window.alert(parameter);
  };

}]);

anotherModule.js

angular.module('dependencyModule', [])
  //currencyConverter is the service
.factory('theService', function() {

  var functionInService = function (parameter2) {
    return parameter2 * 2;
  };

  return {
    inService: functionInService
  };
});

Services can be used to share code across controllers.

Install Mongodb on Fedora 23

To install Mongodb on Fedora 23 go to

https://www.mongodb.org/downloads

On the Linux tab go to version RHEL 7 Linux 64-bitmongodbSreenshot

$ wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.2.3.tgz

Untar the tarball

$ tar -zxvf mongodb-linux-x86_64-rhel70-3.2.3.tgz
$ echo $PATH
$ sudo ln -s ~/Downloads/mongodb-linux-x86_64-rhel70-3.2.3/bin/mongo /usr/local/bin/mongod
$ mongod --version
MongoDB shell version: 3.2.3
$ mongo --version
MongoDB shell version: 3.0.8

Make the directory /data/db

$ mkdir -p /data/db/

Change the permissions on both /data and /data/db

$ sudo chmod 777 /data
$ sudo chmod 777 /data/db

Make sure you are in the mongo directory in /Downloads, ~/Downloads/mongodb-linux-x86_64-rhel70-3.2.3/bin/mongo . Next copy all here to /usr/local/bin/

$ cp * /usr/local/bin

From anywhere run the server with

$ mongod

At the end of the output you should get

 ....... waiting for connections on port 27017

In your browser navigate to localhost:27017
Selection_005
I found that on Fedora both mongod and mongo start the server. mongo should start the Mongodb shell only.

$ mongo

Should run the mongo shell, however on fedora you will need to use,

 $ sudo mongod

And this only works when the Mongodb server is already running.
Continue to Basics of MongoDB Shell