Roshan Book

My Tech Notebook

Tag Archives: python

How to install MySQLdb in a virtualenv on Ubuntu Karmic

Source : http://www.saltycrane.com/blog/2010/02/install-mysqldb-virtualenv-ubuntu-karmic/

Install dependencies
sudo apt-get build-dep python-mysqldb
Install MySQLdb with pip/virtualenv
cd ~/lib/python-environments
virtualenv –distribute –no-site-packages default
pip install -E default/ MySQL-python

Advertisements

Setting up rancho in django

Follow instructions listed in here http://www.getrancho.com/media/files/README.pdf

Installing psycopg2 : http://www.saltycrane.com/blog/2009/07/using-psycopg2-virtualenv-ubuntu-jaunty/

Installing mysqldb –https://roshanbook.wordpress.com/2011/12/20/how-to-install-mysqldb-in-a-virtualenv-on-ubuntu-karmic/

to install dependencies inside virtual env:

install virtuaev -pip install virtualenv
install python image library-
pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL
install mysqldb- pip install MySQL-python
install pytz - pip install pytz
install pisa - pip install pisa
 
 

Go to wikiboard view change ho.pisa module to xhtml2pdf.pisa

add ’django.middleware.csrf.CsrfResponseMiddleware’, to settings

add mysql only as database setting

install all rancho needed module via sudo easy_install modulename

When you implement the project you get an error where you are unable to upload and message under any project. To solve this refer

http://code.google.com/p/django-tagging/issues/detail?id=233

Patch is at http://code.google.com/p/django-tagging/issues/attachmentText?id=233&aid=-8130674876521494184&name=patch_prealpha_fix.diff&token=jHsKmdEwdlE38gHO-m86Q6BH3MY%3A1324220044756

 

To resolve tinymce>>widget.py error – cannot import smart_unicode

see patch http://code.google.com/p/django-tinymce/issues/attachmentText?id=63&aid=-4089731018218914032&name=tinymce-django12alpha.diff&token=giMV8_cMwqMy7s8gzL2Rv19uKic%3A1324448267646

Setting up heroku with django and python

Django deployment on linux machine

Using Django with Apache and mod_python

Apache with mod_python currently is the most robust setup for using Django on a production server.

mod_python (http://www.djangoproject.com/r/mod_python/) is an Apache plug-in that embeds Python within Apache and loads Python code into memory when the server starts. Code stays in memory throughout the life of an Apache process, which leads to significant performance gains over other server arrangements.

Django requires Apache 2.x and mod_python 3.x, and we prefer Apache’s prefork MPM, as opposed to the worker MPM.4

Note

Configuring Apache is well beyond the scope of this book, so we’ll simply mention details as needed. Luckily, a number of great resources are available if you need to learn more about Apache. A few of them we like are as follows:
The free online Apache documentation, available via http://www.djangoproject.com/r/apache/docs/
Pro Apache, Third Edition (Apress, 2004) by Peter Wainwright, available via http://www.djangoproject.com/r/books/pro-apache/
Apache: The Definitive Guide, Third Edition (O’Reilly, 2002) by Ben Laurie and Peter Laurie, available via http://www.djangoproject.com/r/books/apache-pra/
2
Basic Configuration

To configure Django with mod_python, first make sure you have Apache installed with the mod_python module activated. This usually means having a LoadModule directive in your Apache configuration file. It will look something like this:3
LoadModule python_module /usr/lib/apache2/modules/mod_python.so

Then, edit your Apache configuration file and add the following:

SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On

Make sure to replace mysite.settings with the appropriate DJANGO_SETTINGS_MODULE for your site.2

This tells Apache, “Use mod_python for any URL at or under ‘/’, using the Django mod_python handler.” It passes the value of DJANGO_SETTINGS_MODULE so mod_python knows which settings to use.

Note that we’re using thedirective, not thedirective. The latter is used for pointing at places on your filesystem, whereaspoints at places in the URL structure of a Web site.would be meaningless here.2

Apache likely runs as a different user than your normal login and may have a different path and sys.path. You may need to tell mod_python how to find your project and Django itself.4
PythonPath “[‘/path/to/project’, ‘/path/to/django’] + sys.path”

You can also add directives such as PythonAutoReload Off for performance. See the mod_python documentation for a full list of options.

Note that you should set PythonDebug Off on a production server. If you leave PythonDebug On, your users will see ugly (and revealing) Python tracebacks if something goes wrong within mod_python.

Restart Apache, and any request to your site (or virtual host if you’ve put this directive inside ablock) will be served by Django.

Note

If you deploy Django at a subdirectory — that is, somewhere deeper than “/” — Django won’t trim the URL prefix off of your URLpatterns. So if your Apache config looks like this:

SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On

then all your URL patterns will need to start with “/mysite/”. For this reason we usually recommend deploying Django at the root of your domain or virtual host. Alternatively, you can simply shift your URL configuration down one level by using a shim URLconf:
urlpatterns = patterns(”,
(r’^mysite/’, include(‘normal.root.urls’)),
)
2
Running Multiple Django Installations on the Same Apache Instance

It’s entirely possible to run multiple Django installations on the same Apache instance. You might want to do this if you’re an independent Web developer with multiple clients but only a single server.

To accomplish this, just use VirtualHost like so:1
NameVirtualHost *
ServerName http://www.example.com
# …
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
ServerName www2.example.com
# …
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings

If you need to put two Django installations within the same VirtualHost, you’ll need to take a special precaution to ensure mod_python’s code cache doesn’t mess things up. Use the PythonInterpreter directive to give different directives separate interpreters:

ServerName http://www.example.com
# …

SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonInterpreter mysite
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
PythonInterpreter mysite_other
The values of PythonInterpreter don’t really matter, as long as they’re different between the two Location blocks.
Running a Development Server with mod_python

Because mod_python caches loaded Python code, when deploying Django sites on mod_python you’ll need to restart Apache each time you make changes to your code. This can be a hassle, so here’s a quick trick to avoid it: just add MaxRequestsPerChild 1 to your config file to force Apache to reload everything for each request. But don’t do that on a production server, or we’ll revoke your Django privileges.1

If you’re the type of programmer who debugs using scattered print statements (we are), note that print statements have no effect in mod_python; they don’t appear in the Apache log, as you might expect. If you have the need to print debugging information in a mod_python setup, you’ll probably want to use Python’s standard logging package. More information is available at http://docs.python.org/lib/module-logging.html. Alternatively, you can or add the debugging information to the template of your page.2
Serving Django and Media Files from the Same Apache Instance

Django should not be used to serve media files itself; leave that job to whichever Web server you choose. We recommend using a separate Web server (i.e., one that’s not also running Django) for serving media. For more information, see the “Scaling” section.1

If, however, you have no option but to serve media files on the same Apache VirtualHost as Django, here’s how you can turn off mod_python for a particular part of the site:

SetHandler None

Change Location to the root URL of your media files.

You can also use to match a regular expression. For example, this sets up Django at the site root but explicitly disables Django for the media subdirectory and any URL that ends with .jpg, .gif, or .png:

SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
SetHandler None
SetHandler None

In all of these cases, you’ll need to set the DocumentRoot directive so Apache knows where to find your static files.

Python tutorial 18- Using python in netbeans

 

  • Start NetBeans 7
  • Click on Tools > Plugins
  • When the Plugins window opens click the Settings Tab
  • In the Settings tab click the Add button
  • Type whatever Name you want for this, I used ‘Developer Updates’
  • Under URL put http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastStableBuild/artifact/nbbuild/nbms/updates.xml.gz and click OK
  • The plugin list should refersh and may take a moment, when it does click on the ‘Available Plugins’ tab.
  • In the search box there type ‘python’ to find the python plugin, check the box for that plugin and click Install.

Python tutorial 0–Resources

Python tutorial 17.2 Working with modules

Opening and encoding a webpage

def main():
    import urllib.request
    page=urllib.request.urlopen(‘http://bw.org/’)
    for line in page: print(str(line, encoding =’utf_8′), end=”)

if __name__ == “__main__”: main()

 

 

Module resource : http://docs.python.org/py3k/index.html

Python tutorial 17–Objects in database

import sqlite3

class database:
    def __init__(self, **kwargs):
        self.filename = kwargs.get(‘filename’)
        self.table = kwargs.get(‘table’, ‘test’)
   
    def sql_do(self, sql, *params):
        self._db.execute(sql, params)
        self._db.commit()
   
    def insert(self, row):
        self._db.execute(‘insert into {} (t1, i1) values (?, ?)’.format(self._table), (row[‘t1’], row[‘i1’]))
        self._db.commit()
   
    def retrieve(self, key):
        cursor = self._db.execute(‘select * from {} where t1 = ?’.format(self._table), (key,))
        return dict(cursor.fetchone())
   
    def update(self, row):
        self._db.execute(
            ‘update {} set i1 = ? where t1 = ?’.format(self._table),
            (row[‘i1’], row[‘t1’]))
        self._db.commit()
   
    def delete(self, key):
        self._db.execute(‘delete from {} where t1 = ?’.format(self._table), (key,))
        self._db.commit()

    def disp_rows(self):
        cursor = self._db.execute(‘select * from {} order by t1’.format(self._table))
        for row in cursor:
            print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

    def __iter__(self):
        cursor = self._db.execute(‘select * from {} order by t1’.format(self._table))
        for row in cursor:
            yield dict(row)

    @property
    def filename(self): return self._filename

    @filename.setter
    def filename(self, fn):
        self._filename = fn
        self._db = sqlite3.connect(fn)
        self._db.row_factory = sqlite3.Row

    @filename.deleter
    def filename(self): self.close()

    @property
    def table(self): return self._table
    @table.setter
    def table(self, t): self._table = t
    @table.deleter
    def table(self): self._table = ‘test’

    def close(self):
            self._db.close()
            del self._filename

def main():
    db = database(filename = ‘test.db’, table = ‘test’)

    print(‘Create table test’)
    db.sql_do(‘drop table if exists test’)
    db.sql_do(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    db.insert(dict(t1 = ‘one’, i1 = 1))
    db.insert(dict(t1 = ‘two’, i1 = 2))
    db.insert(dict(t1 = ‘three’, i1 = 3))
    db.insert(dict(t1 = ‘four’, i1 = 4))
    for row in db: print(row)

    print(‘Retrieve rows’)
    print(db.retrieve(‘one’), db.retrieve(‘two’))

    print(‘Update rows’)
    db.update(dict(t1 = ‘one’, i1 = 101))
    db.update(dict(t1 = ‘three’, i1 = 103))
    for row in db: print(row)

    print(‘Delete rows’)
    db.delete(‘one’)
    db.delete(‘three’)
    for row in db: print(row)

if __name__ == “__main__”: main()

Python tutorial 16–CRUD application

import sqlite3

def insert(db, row):
    db.execute(‘insert into test (t1, i1) values (?, ?)’, (row[‘t1’], row[‘i1’]))
    db.commit()

def retrieve(db, t1):
    cursor = db.execute(‘select * from test where t1 = ?’, (t1,))
    return cursor.fetchone()

def update(db, row):
    db.execute(‘update test set i1 = ? where t1 = ?’, (row[‘i1’], row[‘t1’]))
    db.commit()

def delete(db, t1):
    db.execute(‘delete from test where t1 = ?’, (t1,))
    db.commit()

def disp_rows(db):
    cursor = db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

def main():
    db = sqlite3.connect(‘test.db’)
    db.row_factory = sqlite3.Row
    print(‘Create table test’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    insert(db, dict(t1 = ‘one’, i1 = 1))
    insert(db, dict(t1 = ‘two’, i1 = 2))
    insert(db, dict(t1 = ‘three’, i1 = 3))
    insert(db, dict(t1 = ‘four’, i1 = 4))
    disp_rows(db)

    print(‘Retrieve rows’)
    print(dict(retrieve(db, ‘one’)), dict(retrieve(db, ‘two’)))

    print(‘Update rows’)
    update(db, dict(t1 = ‘one’, i1 = 101))
    update(db, dict(t1 = ‘three’, i1 = 103))
    disp_rows(db)

    print(‘Delete rows’)
    delete(db, ‘one’)
    delete(db, ‘three’)
    disp_rows(db)

if __name__ == “__main__”: main()

Python tutorial 16–CRUD application

import sqlite3

def insert(db, row):
    db.execute(‘insert into test (t1, i1) values (?, ?)’, (row[‘t1’], row[‘i1’]))
    db.commit()

def retrieve(db, t1):
    cursor = db.execute(‘select * from test where t1 = ?’, (t1,))
    return cursor.fetchone()

def update(db, row):
    db.execute(‘update test set i1 = ? where t1 = ?’, (row[‘i1’], row[‘t1’]))
    db.commit()

def delete(db, t1):
    db.execute(‘delete from test where t1 = ?’, (t1,))
    db.commit()

def disp_rows(db):
    cursor = db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

def main():
    db = sqlite3.connect(‘test.db’)
    db.row_factory = sqlite3.Row
    print(‘Create table test’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    insert(db, dict(t1 = ‘one’, i1 = 1))
    insert(db, dict(t1 = ‘two’, i1 = 2))
    insert(db, dict(t1 = ‘three’, i1 = 3))
    insert(db, dict(t1 = ‘four’, i1 = 4))
    disp_rows(db)

    print(‘Retrieve rows’)
    print(dict(retrieve(db, ‘one’)), dict(retrieve(db, ‘two’)))

    print(‘Update rows’)
    update(db, dict(t1 = ‘one’, i1 = 101))
    update(db, dict(t1 = ‘three’, i1 = 103))
    disp_rows(db)

    print(‘Delete rows’)
    delete(db, ‘one’)
    delete(db, ‘three’)
    disp_rows(db)

if __name__ == “__main__”: main()

%d bloggers like this: