The Collection Part 2 #Postgres_Copy_Table

To copy a table completely, including both table structure and data, you use the following statement:

CREATE TABLE new_table AS TABLE existing_table;

To copy a table structure without data, you add the WITH NO DATA clause to the CREATE TABLE statement as follows:

CREATE TABLE new_table AS TABLE existing_table WITH NO DATA;

To copy a table with partial data from an existing table, you use the following statement:

CREATE TABLE new_table AS SELECT * FROM existing_table WHERE  condition;

The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.

Note that all the statement above copy table structure and data but do not copy indexes and constraints of the existing table.

PostgreSQL copy table example

The following statement creates a new table named contacts for the demonstration:

CREATE TABLE contacts(

    id SERIAL PRIMARY KEY,

    first_name VARCHAR NOT NULL,

    last_name VARCHAR NOT NULL,

    email VARCHAR NOT NULL UNIQUE

);

In this table, we have two indexes: one index for the primary key and another for the UNIQUE constraint.

Let’s insert some rows into the contacts table:

INSERT INTOcontacts(first_name,last_name,email) VALUES('John','Doe','john.doe@postgresqltutorial.com'),

      ('David','William','david.william@postgresqltutorial.com');
 
To copy the contacts to a new table, for example, contacts_backup table, you use the following statement:
CREATE TABLE contact_backup

AS TABLE contacts;

This statement creates a new table named contact_backup whose structure is the same as the contacts table. In addition, it copies data from the contacts table to the contact_backup table.

Let’s check the data of the contact_backup table by using the following SELECT statement:

It returns two rows as expected

To examine the structure of the contact_backup table:

As you can see in the output, the structure of the contact_backup table is the same as the contacts table except for the indexes.

To add the primary key and UNIQUE constraints to the contact_backup table, you use the following ALTER TABLE statements:

ALTER TABLE contact_backup ADD PRIMARY KEY(id);

ALTER TABLE contact_backup ADD UNIQUE(email);
To view structure of the contact_backup table again, you use \d command:
In this tutorial, you have learned how to copy an existing table to a new one using the various forms PostgreSQL copy table statement.
source : postgresqltutorial.com

The Collection Part 1 #try_exception

Bagaimana cara menangani event exception pada saat kita melakukan request ke webservice ?

ada kalanya kita memerlukan sebuah function yang bisa melakukan reload ulang pada sebuah event yang kita buat jika event tersebut mengalami mal function. cara yang paling sederhana kita bisa menggunakan try exception, seperti sample di bawah ini :

class NetworkError(RuntimeError):
    pass
 
def retryer(max_retries=10, timeout=5):
    def wraps(func):
        request_exceptions = (
            requests.exceptions.Timeout,
            requests.exceptions.ConnectionError,
            requests.exceptions.HTTPError,
            requests.exceptions.SSLError,
        )
 
    def inner(*args, **kwargs):
        for i in range(max_retries):
            try:
                result = func(*args, **kwargs)
            except request_exceptions:
                time.sleep(timeout)
                continue
            else:
                return result
            else:
                raise NetworkError
        return inner
    return wraps
 
@retryer(max_retries=7, timeout=1)
def foo():
    print('Stuff')
    requests.get('https://www.google.com')

sumber : stack overflow

good lucks

Get Json Use Python Requests

Bagaimana cara mendownload json dari sebuah web service  ?

Python menyediakan sebuah library canggih bernama python requests, yang dapat kita gunakan untuk melakukan action POST dan GET ke webservice.

untuk mempermudah pembuatan object parameter GET, kita bisa menggunakan library urllib

pertama buat terlebih dahulu object parameternya :

get_param={    
    'arrivalDate':"2017-07-02",
    'departureDate':"2017-07-03",
    'countryCode':'ID'
}

 

kemudian encode dengan menggunakan urllib

params =urllib.parse.urlencode(get_param)

 

Kode lengkapnya di bawah ini

import json
import requests
import urllib.parse
get_param={    
    'arrivalDate':"2017-07-02",
    'departureDate':"2017-07-03",
    'countryCode':'ID'
}
params =urllib.parse.urlencode(get_param)
url = 'http://xxx.com/list?'+params
r = requests.get(url)
print(json.dumps(r.json()))

 

Good Lucks ….!

Multiple Replace On Python

Bagaimana untuk mereplace sebuah list ?

kita asumsikan mempunyai sebuah bilangan integer 123456, lalu kita ingin mengubahnya menjadi 1,2,3,4,5,6

untuk mengubah bilangan di atas ubah kedalam bentuk list kemudian ubah list ke string agar kita bisa menggunakan fungsi replace pada python.

 

Example

rating = "123456"
lst = list(rating)
cut = {"[": "", "'": "", "]": ""}
for x,y in cut.items():
   lst = str(lst).replace(x,y)
hotel_start = lst
print(hotel_start)

good lucks ….!

 

Implement JWT On Django Rest

Pada tutorial sebelumnya kita sudah mempelajari tentang

selanjutnya kali ini kita akan mengimplementasikan JWT pada Django Rest Framework

install jwt pada django :
pip install djangorestframework-jwt
tambahkan pada setting.py script di bawah ini untuk membuat screet key dan token expired
SECRET_KEY = "12345"
EXPIRY_TIME = datetime.timedelta(seconds=20)
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=20),  # Token expires * seconds after being issued
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=120),  # Token can be refreshed up to * seconds after being issued
 }

 

buat function untuk encode dan decode JWT
def get_token(request):
    username =request.GET.get('username')
    password = request.GET.get('password')
    if username and password is not None:
        payload = {
            'username': username,
            'password':password,
            'exp':datetime.utcnow() + settings.EXPIRY_TIME
        }
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        token =str(token).replace("b'","")
        token = str(token).replace("'", "")
        token= {'token':token}
        return HttpResponse(
            json.dumps(token)
        )
    else:
        return HttpResponse(
            json.dumps({'Error': "Invalid credentials"}),
            status=400
        )
def get_verivy_token(request):
    token =request.GET.get('token')
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithm='HS256')
        return HttpResponse(
            json.dumps(payload),
            status=200
        )
 
    except jwt.ExpiredSignature:
        return HttpResponse(json.dumps({'Error': "Token is invalid"}))
    except:
        return HttpResponse(json.dumps({'Error': "Token DoesNotExist"}))
good luck ….!