Get json results from mysql with python

This is just simple trick to retrieve data from mysql rows and turn into json.

#!/usr/bin/env python
import MySQLdb as mdb
import sys

con = mdb.connect('localhost', 'root', 'pass123', 'mydb1', charset='utf8')
cur = con.cursor(mdb.cursors.DictCursor)

def get_post():
    list = []
    gw = {}
    cur.execute("select * from tbl1_core")
    rows = cur.fetchall()
    for i in rows:
        tes = []
        # we want to fetch row to store in results
        gw["content"] = i["content"]
        tes.append(gw)
        list.append(tes)
        tes = []
        gw = {}
    return list
tes = get_post()
print tes

Setup docker + jenkins + nginx

Let’s setup jenkins with docker with local url : jenkins.local

First, add local url to /etc/hosts

$ sudo echo -e "127.0.0.1\tjenkins.local" >> /etc/hosts

Install docker and pull newest jenkins image

$ sudo apt-get install docker.io
$ sudo docker pull jenkins
$ sudo docker run -itd --name jenkins --publish 8080:8080 --publish 50000:50000 jenkins

Setup nginx

$ sudo vim /etc/nginx/conf.d/jenkins.conf

nginx conf:

server {
  listen 80;
  server_name jenkins.local;
  charset utf-8;
  gzip_vary on;
  access_log /var/log/nginx/jenkins.access.log;
  error_log /var/log/nginx/jenkins.error.log;
  location / {
    proxy_pass http://127.0.0.1:8080;
  }
}

Save config and restart nginx

$ sudo service nginx restart

Open browser, and navigate to http://jenkins.local


How to change wordpress homepage URL

I moved my wordpress blog from my localhost to new hosting (new domain), and I was lazy to install the new one and I just copied all of my directory and upload it to new hosting. After a few configuration, my blog back to online with new domain, but the home page url was still referring to old url (my localhost url).

Few minutes later after googled the problem, I found out these two lines need to be added in wp-config.php, just put these damn codes at the top before database configuration.

define('WP_HOME','http://your-new-url.com');
define('WP_SITEURL','http://your-new-url.com');

and save to override the homepage url stuck.


WordPress basic htaccess

My wordpress blog fucked up because I didn’t realize I moved from nginx to apache, and apache needs .htaccess file for permalink my links in wp.
This is just default htaccess config :

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Install and Create Virtualenv Python in ubuntu machine

Let’s say I want to have a project called webproject, and this project has own user with the same name to access the project directory. And this is supposed to be a python project and it needs virtual environment. also I want the project has specific python version 2.7 with virtualenv. So let’s get started.

First you may have to check your python version if it is already installed python 2.7 otherwise you’re gonna have to download and install it, but if you prefer to not use python 2.7, let’s say version 2.6, or whatever. That’s fine as well.

Something related:

Install different version of Python in linux

Let’s start with install the virtualenv via apt in ubuntu

$ apt-get install python-virtualenv virtualenvwrapper

Create user and setup home directory

$ useradd -m webproject -d /srv/webproject

Change user to webproject, until you’re inside the home directory project

$ sudo su - webproject

Create virtual environment with virtualenv with python version 2.7

$ virtualenv ~/venv --python=2.7

Or, if you prefer not to use spesific python version, just run the command like this:

$ virtualenv ~/venv

Now, inside your home directory, there is a new directory named venv that contained your python binary.

You might want to put this line of code inside your .bash_history or .profile inside your home directory, so whenever you try to change user, it is automatically activate your python virtual environment.

$ vim ~/.profile
....
....
source ~/venv/bin/activate

and save the file.

Now, try to change user to webproject:

$ sudo su - webproject
(venv)webproject@localhost:~$

Create simple arg parse in python

argparse is a module to make user-friendly command-line interfaces. It’s probably the one of the most frequently used module when I create a script in python that needs to parse some arguments. Check this out.

$ vim test.py
#!/usr/bin/python
import argparse

def init_args():
  parser = argparse. ArgumentParser(description="This is the description")
  parser.add_argument("--arg1", required=True, type=str, help="This is arg1")
  parser.add_argument("--allow", required=False, action="store_true", help="Allow mode")
  return parser.parse_args()

def main(arg1):
  return "arg1: %s"%(arg1)

if __name__ == "__main__":
  args = init_args()
  main(args.arg1)

See what happens when we run it

$ ./test.py --arg1 "showme"
arg1: showme

Sometimes we want to create an argumen but only store it as a True variable. we can just create simple test like this.

$ vim test.py
#!/usr/bin/python
import argparse

def init_args():
  parser = argparse. ArgumentParser(description="This is the description")
  parser.add_argument("--arg1", required=False, action="store_true", help="Enable arg1")
  return parser.parse_args()

def main():
  return "arg1 is enabled"

if __name__ == "__main__":
  args = init_args()
  if args.arg1:
    main()
  else:
    print "arg1 parse is not enabled"

Try to run it

$ ./test.py --arg1
arg1 is enabled