Monday, July 22, 2019

Sunday, July 21, 2019

Working on community driven Online E-Commerce Portal!

Why community-driven?

I feel community-driven business is really good to start with where you don't have to worry about building an in-house team of experts. It is like outsourcing someone to do the work and give them loyalty. Building a kind of online artist community, sell their arts and give them loyalty.

What is the name?

ArtSeptor: A community for artist
The name came after Loki's Septor. 

Technology Stack

Python/Django and there is a really very good eCommerce package written in Python/Django called Django-Shuup! It's quite active in terms of development and I've already tested the feature and I feel it's easy to set up and ready to use.

Launch Date and Hiring Developer

Open to talk to contributors and YES, we are about to launch the portal in October 2019.
Contributors can only join if the idea excites you!



Share:

Generate wildcard certificate with Let's Encrypt/Certbot and install on GoDaddy, cPanel.

Why there is a need for an SSL certificate?

SSL is the backbone of our secure Internet and it protects your sensitive information as it travels across the world's computer networks. The primary reason why SSL is used is to keep sensitive information sent across the Internet encrypted so that only the intended recipient can access it.

If you don't have SSL then google-chrome or any browser will flag your website as Not-Secure which means, if you do any kind of transaction then there is a high chance that your data will be compromised.



In this blog, I'm going to generate one wild-card certificate for my blog site, ashishtiwari.me. A WildCard certificate can be used with subdomain as well, for example -
blog.ashishtiwari.me, contact.ashishtiwari.me, tech.ashishtiwari.me

1. Set up your machine to generate the SSL certificate [ Ubuntu ]. 

apt-get update
apt-get install git-core

2. Install Let's Encrypt/Certbot 

apt-get install letsencrypt

3. Generate SSL certificate using Certbot 

Now with the help of Certbot, we will generate wildcard certificate for our test domain ashishtiwari.me

certbot-auto certonly --manual --preferred-challenges=dns --email writetoashishtiwari@gmail.com
--server https://acme-v02.api.letsencrypt.org/directory --agree-tos -d *.ashishtiwari.me

4. Setup DNS TXT record to authenticate Ownership.

For wildcard certificates, the only challenge method Let’s Encrypt accepts is the DNS challenge, which we can invoke via the preferred-challenges=dns flag.

After executing the above command, the Certbot will share a text record to add to your DNS TXT field.


Please deploy a DNS TXT record under the name

_acme-challenge.ashishtiwari.me with the following value:
iroa8XXXhpTah-h4Az4UZuuXslHCdkxIuDiL2XXXv2Y

Create TXT record via DNS console and setup key and value

TXT Record Name  :  _acme-challenge
TXT Record Value  :  iroa8XXXhpTah-h4Az4UZuuXslHCdkxIuDiL2XXXv2Y

4. Finally, Generate the Certificate.

Once you authenticate the domain ownership; by setting up DNS TXT record, Certbot generates the ssl certificate and required keys [ PEM/CERTIFICATE ].


IMPORTANT NOTES:

 - Congratulations! Your certificate and chain have been saved at:
    /etc/letsencrypt/live/ashishtiwari.me/fullchain.pem
    Your key file has been saved at:
    /etc/letsencrypt/live/ashishtiwari.me/privkey.pem

    Your cert will expire on 2019-10-14. To obtain a new or tweaked
    version of this certificate in the future, simply run certbot
    again. To non-interactively renew *all* of your certificates, run
    "certbot renew"

  - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

5. Complete Logs.

Plugins selected: Authenticator manual, Installer None
Obtaining a new certificate
Performing the following challenges:
dns-01 challenge for ashishtiwari.me
dns-01 challenge for ashishtiwari.me

-------------------------------------------------------------------------------
Please deploy a DNS TXT record under the name

_acme-challenge.ashishtiwari.me with the following value:
iroa8XXXhpTah-h4Az4UZuuXslHCdkxIuDiL2XXXv2Y

Before continuing, verify the record is deployed.
-------------------------------------------------------------------------------
Press Enter to Continue
-------------------------------------------------------------------------------

Please deploy a DNS TXT record under the name

_acme-challenge.ashishtiwari.me with the following value:
V781k3nW6GaSdpyfbTYJBJpt1IJYBehMQa1je2gFg3Q
Before continuing, verify the record is deployed.
-------------------------------------------------------------------------------

Press Enter to Continue
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:

 - Congratulations! Your certificate and chain have been saved at:
    /etc/letsencrypt/live/ashishtiwari.me/fullchain.pem
    Your key file has been saved at:
    /etc/letsencrypt/live/ashishtiwari.me/privkey.pem
    Your cert will expire on 2019-10-14. To obtain a new or tweaked
    version of this certificate in the future, simply run certbot
    again. To non-interactively renew *all* of your certificates, run
    "certbot renew"

 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

6. Install SSL on cPanel.
Share:

Wednesday, April 17, 2019

Flask Minimal Setup and Hello World with NGROK


Setup VirtualEnv, Flask Installation and Project Directory

pip3 install virtualenv
virtualenv -p /usr/bin/python3 flask-sample
source flask-sample/bin/activate
pip install flask
mkdir flask-demo && cd flask-demo
touch main.py

Edit main.py file

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

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

Run Flask app and visit localhost:5000

python main.py

Console Log
 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

NGROK Setup

Signup for NGROK and get AuthToken

wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
unzip ngrok-stable-linux-amd64.zip
./ngrok authtoken 
./ngrok http 5000
Console Log
ngrok by @inconshreveable                                                                                                                                                                                                                                       (Ctrl+C to quit)                                                                                                                                                                                                                                                                                
Session Status                online                                                                                                                                                                                                                                            
Account                       Ashish Tiwari (Plan: Free)                                                                                                                                                                                                                        
Version                       2.3.25                                                                                                                                                                                                                                            
Region                        United States (us)                                                                                                                                                                                                                                
Web Interface                 http://127.0.0.1:4040                                                                                                                                                                                                                             
Forwarding                    http://b6ad4280.ngrok.io -> http://localhost:5000                                                                                                                                                                                                 
Forwarding                    https://b6ad4280.ngrok.io -> http://localhost:5000                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                
Connections                   ttl     opn     rt1     rt5     p50     p90                                                                                                                                                                                                       
                              0       0       0.00    0.00    0.00    0.00         

App is running on http://b6ad4280.ngrok.io
Share:

Tuesday, March 5, 2019

Believe in yourself :Photography In Layman's Voice Part-1


First of all, I'm not a professional Photographer but I know a few tricks. :)
So, this post is not for professional photographers those who have already mastered their camera features.
Let's Start.

Believe In Your Skills.


If you are just starting the Photography Walk then I'm sure you already have an account on Instagram.
If you go through your photographs on instagram you will see the pattern, the trail of your Photography journey and believe me you are clicking really awesome shots.
Just go through your instagram feed from the beginning. I knew it! You loved your photographs.

My Journey as The_Travelling_Monk

“Your first 10,000 photographs are your worst.” - Henri Cartier-Bresson


Read More About Henri At : https://en.wikipedia.org/wiki/Henri_Cartier-Bresson
Share:

Monday, March 4, 2019

Sunday, February 24, 2019

Fuzzy Django Flask App : Django Like Project Structure


While I was going through some legacy system which had 75,000 lines of code written in python/flask. I was wondering why it's not borken up into applications.

After discussion with other developers I came to know about that those codes were written by ex-developers 2 yrs back.

It seems those legends only knew about hello-world-in-flask from documentation because everything is written in myflaskapplication.py file ( 75,000 lines ).
Because, models, controller, blueprints, admin, forms and etc etc were written in myflaskapplication.py file.

Now big pain is to break this system into small application and then into microservices.
Since I've spend so much time working with python/django it wasn't difficult to break system's structure into small application and divide task between other developers.


Sample app can be found at, https://github.com/codetarsier/fuzzy-django-flask
Here is the sample structure.

Project Folders
- common : models and serializer for other application
- <application_structure> : contains, models, views, helpers, serializer, urls and views.
- static : contains all css, js, images
- templates : contains html files and broken into application structure like, templates/portal_setup and templates/common
- config : database, packages, secret settings
Project Structure
├── common
│   ├── __init__.py
│   ├── models.py
│   └── serializers.py
├── config
│   ├── constants.py
│   ├── __init__.py
│   ├── sample_secrets.json
│   └── settings.py
├── config.py
├── manage.py
├── portal_setup
│   ├── admin.py
│   ├── forms.py
│   ├── helpers.py
│   ├── __init__.py
│   ├── models.py
│   ├── serializers.py
│   ├── urls.py
│   └── views.py
├── README.md
├── reports.json
├── requirements.txt
├── static
│   └── portal_setup
│       ├── css
│       └── js
└── templates
    └── portal_setup
        ├── add_portal.html
        ├── base.html
        ├── edit_portal.html
        ├── index.html
        └── portal_details.html













Share:

Wednesday, December 5, 2018

Tuesday, December 4, 2018

Monday, November 19, 2018

Working with Multiple Databases in Django.

Working with Multiple Databases in Django.

As usual django-doc is great to start with any topics. I was just giving a try to use multiple database in single application.

1. Database Settings

First step is to tell your django application that you want to use more than one database. So look for the DATABASES in your project's settings.py file.
project/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'blogs': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'blogs_db.sqlite3')
    }
}
Here I'm going to store all the blog entries into "blogs" ( blogs_db.sqlite3 ) and rest data will be stored in into "default" database ( db.sqlite3 ).

2. Define Model

blogs/models.py

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=200)

3. Setup Database Router

You can define a database router that implements a policy constraining the availability of particular models.
project/settings.py
DATABASE_ROUTERS = ['blogs.router.BlogRouter']
blogs/router.py

class BlogRouter:
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label == 'blogs':
            return 'blogs'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label == 'blogs':
            return 'blogs'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'blogs' or \
           obj2._meta.app_label == 'blogs':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if app_label == 'blogs':
            return db == 'blogs'
        return None
That's it. Now test whether the settings are working fine or not?
./manage.py makemigrations --database=default
./manage.py makemigrations --database=blogs

4. Create Blog

There are multiple ways to create blog entry in blogs_db,

4.1. By using "using()" to create entry in perticular db.
example,
from blogs.models import Blog
Blog.objects.using('blogs').create(title='python goes here')

4.2. Create a blog through admin interface.

blogs/admin.py

from django.contrib import admin
from .models import Blog

admin.site.register(Blog)

5. Test Your Config Using Shell

Create a blog entry using the admin site and will check which database has stored the blog info.
./manage.py shell

from blogs.models import Blog

 # This will run on the DEFAULT-DATABASE/BLOG-DATABASE
Blog.objects.all() 
QuerySet [Blog: Blog object (1)]

 # This will run on the BLOGS-DATABASE
Blog.objects.using('blogs').all()
QuerySet [Blog: Blog object (1)]
# returns blogs

 #This will run on the DEFAULT-DATABASE
Blog.objects.using('default').all()

    301             return Database.Cursor.execute(self, query)
    302         query = self.convert_query(query)
--> 303         return Database.Cursor.execute(self, query, params)
    304
    305     def executemany(self, query, param_list):
OperationalError: no such table: blogs_blog
returns error.
For more detail please visit, https://docs.djangoproject.com/en/2.1/topics/db/multi-db/
Share:

Sunday, August 12, 2018

Beauty of Gateway Of India and Tajmahal Palace Hotel


The Taj Mahal Palace Hotel

The Taj Mahal Palace Hotel is a heritage, five-star luxury hotel in the Colaba region of Mumbai, Maharashtra, India, situated next to the Gateway of India. Historically it was known as the "Taj Mahal Hotel" or the "Taj Palace Hotel" or simply "the Taj".

The Gateway of India

The Gateway of India is an arch monument built during the 20th century in BombayIndia. The monument was erected to commemorate the landing of King George V and Queen Mary at Apollo Bunder on their visit to India in 1911.


Share:

Thursday, August 2, 2018

Python Selenium : Generating the HTML Test Report and Screenshot feature.

Python Selenium : HtmlTestRunner and Screenshot feature.

Introduction

HtmlTest runner
HtmlTest runner is a unittest test runner that save test results in Html files, for human readable presentation of results.

Screenshots
In automation, it is mandatory to take the screenshot for verification so that can prove also that your test case has covered certain functionality or not. Screenshots help you a lot when your test case will fail so that you can identify what went wrong in your script or in your application.

1. HtmlTestRunner Installation

You can install and read more about HtmlTestRunner from the Github..
HtmlTestRunner Github Page
Using pip, you can install selenium like this:
pip install html-testRunner

2. Sample Selenium Test

create pythonorg-sample.py

import unittest
import HtmlTestRunner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys


class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")

        # take screen shot
        self.driver.save_screenshot("python-org.png")

        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)

        # take screen shot after search
        self.driver.save_screenshot("python-org-after-search.png")

        assert "No results found." not in driver.page_source

    def test_error(self):
        """ This test should be marked as error one. """
        raise ValueError

    def test_fail(self):
        """ This test should fail. """
        self.assertEqual(1, 2)

    def tearDown(self):
        self.driver.close()


if __name__ == "__main__":
    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='report'))

3. Run Selenium Test

python pythonorg-sample.py

4. Screenshots

HtmlTestRunner
Console Log

Running tests...
----------------------------------------------------------------------
 This test should be marked as error one. ... ERROR (1.961452)s
 This test should fail. ... FAIL (1.838222)s
 test_search_in_python_org (__main__.PythonOrgSearch) ... OK (12.246906)s

======================================================================
ERROR [1.961452s]: This test should be marked as error one.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "pythonorg-sample.py", line 31, in test_error
    raise ValueError
ValueError

======================================================================
FAIL [1.838222s]: This test should fail.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "pythonorg-sample.py", line 35, in test_fail
    self.assertEqual(1, 2)
AssertionError: 1 != 2

----------------------------------------------------------------------
Ran 3 tests in 0:00:16

FAILED
 (Failures=1, Errors=1)

Generating HTML reports...

Share:

Wednesday, August 1, 2018

Getting Started with Python Selenium on Mac OS X

1. Introduction

Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Ie, Chrome, Remote etc. The current supported Python versions are 2.7, 3.5 and above.

2. Downloading Python bindings for Selenium and Installation

You can download Python bindings for Selenium from the PyPI page for selenium package. However, a better approach would be to use pip to install the selenium package. Python 3.6 has pip available in the standard library. Using pip, you can install selenium like this:
pip install selenium

3. Drivers

download chrome driver

Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run. Make sure it’s in your PATH, e. g., place it in /usr/bin or /usr/local/bin.
cp chromedriver /usr/local/bin/

4. Sample Selenium Test

create main.py file

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

5. Run Script

python main.py
Share:

Saturday, June 16, 2018

Thursday, April 19, 2018

Friday, February 9, 2018

Music for workspace


Best of Synthwave And Retro Electro Music Mix




One workspace dedicated to music on mac, and another completely for getting things done Or you can attach a dedicated monitor for music.

I came across this amazing playlist collection of electro music which is quite impressive and it won't disturb you while you are working.
Share: