Thursday, May 25, 2017

python mysql connect

sudo apt-get install libmysqlclient-dev
pip install MySQL-python

#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","root","p@ssowr9d","store_db")
cursor = db.cursor()
sql = "select * from food_tbl"
try:
    cursor.execute(sql)
    #data = cursor.fetchone()
    data = cursor.fetchall()
    for row in data:
        id = row[0]
        name = row[1]
        catagory = row[2]
        price = row[3]
        print "%d %s %s %d " % (id, name, catagory, price)
except:
    print "Error: unable to fetch data"

db.close()

Tuesday, May 23, 2017

python pip and virtualenv and virtualenvwrappers

Virtualenv way that you can separate different python enviroment for different porjects
eg. different package versions for different projects

pip install virtualenv
pip install pyOpenSSL ndg-httpsclient pyasn1

You may need runtime/development packages for python and openssl as well in order for the build to succeed, e.g. python-dev libssl-dev libffi-dev on Ubuntu 14.04.

pip install --upgrade pip
pip list

#To export all package and version numbers for other projects

pip freeze  --local >> requirements.txt
# in new enviroment import/install package version
pip install -r requirements.txt


deactivate  # to getout of VE


# specify specific version of python to use
virtualenv -p /usr/bin/python2.7 py27_env
source py27_env/bin/activate

pip install -r requirements.txt


#virtualenvwrapper  allows to switch between different virtualenv
# Setup:

pip install virtualenvwrapper
path to virtualenvwrapper.sh  is mostly /usr/local/bin/virtualenvwrapper.sh

#  1. Create a directory to hold the virtual environments.
#     (mkdir $HOME/.virtualenvs).
#  2. Add a line like "export WORKON_HOME=$HOME/.virtualenvs"
#     to your .bashrc.
#  3. Add a line like "source /path/to/this/file/virtualenvwrapper.sh"
#     to your .bashrc.
#  4. Run: source ~/.bashrc
#  5. Run: workon
#  6. A list of environments, empty, is printed.
#  7. Run: mkvirtualenv temp
#  8. Run: workon
#  9. This time, the "temp" environment is included.
# 10. Run: workon temp
# 11. The virtual environment is activated.

#Create virtualenviroment

mkvirtualenv enviro100
mkvirtualenv enviro200

user1@localhost ~ $ workon
enviro100
enviro200

#To use enviroment named enviro200

workon enviro200