2014-12-25

Published on 2014-12-25


MySQL in Python

Install MySQL

# apt-get install mysql-client  # for some programs connect to mysql
# apt-get install mysql-server  # for mysql service
# apt-get install libmysqlclient-dev  # for MySQL-python

Install python-dev

Python-dev is used when build MySQL-python.

# apt-get install python-dev

Install MySQL-python

Download MySQL-python (MySQLdb)

Find path of mysql_config with

$ whereis mysql_config

Edit site.cfg of MySQL-python, set the correct path of mysql_config, then save.

$ python setup.py build
# python setup.py install

Django Core

Install

You can install Django with pip

# pip install Django==1.7.1

Or you can download source of Django, Decompression it. Then use

# python setup.py install

Start Projects

To start a project

$ django-admin.py startproject mysite

To start an app

$ ./manage.py startapp <appname>

Then install this app in settings.py

INSTALLED_APPS = (
    # other installed apps
    '<appname>',
)

To run a project

$ ./manage.py runserver [<host>:<port>]

For example, you can run your site on 127.0.0.1:8000 by default, or on localhost by (note that run on port 80 need super user)

# ./manage.py runserver 0.0.0.0:80

To open a shell for testing

$ ./manage.py shell

Settings

Then configure you site by modifying the file settings.py.

Modify ALLOWED_HOSTS to allow all users from all over the world to visit your site

ALLOWED_HOSTS = [*]

By default, the debug mode and template debug mode is open, but in fact they should only open on your developing environment. You could play a trick which makes them automatically open or closed.

import socket

if socket.gethostname() in ['developer-Thinkpad', 'username-PC', ] :
    DEBUG = True
    TEMPLATE_DEBUG = True
else:
    DEBUG = False
    TEMPLATE_DEBUG = False

Models

Models are ORM framework of Django. They are always defined as

from django.db import models
from django.contrib.auth.models import User

class Message(models.Model):
    time = models.DateTimeField(auto_now = True)
    title = models.CharField(max_length = 40)
    content = models.TextField()
    is_new = models.BooleanField(default = True, verbose_name = 'Is New')
    sender = models.ForeignKey(User, null = True, related_name = 'sender_set')
    receiver = models.ForeignKey(User, related_name = 'receiver_set')
    related_url = models.URLField(null = True, verbose_name = 'Related Links')

    class Meta:
        ordering = ['-time', 'id']

    def __unicode__(self):
        return self.receiver.username + u'\'s messageļ¼š ' + self.title

The ordering attribute in class 'Meta' denotes that result of queries about Message will be sorted in time and id.

More information about filed types see here.

The Django command syncdb has been replaced by migrate. Commonly the first migration could be done with

$ ./manage.py makemigrateions
$ ./manage.py migrate