Python Lover(一)Python and Django Introduction

Python Lover(1)Python and Django Introduction

Python Lover(1)Python and Django Introduction

Recently I notice that python is popular in some companies. And I use django and python in year 2010, that is long time ago, I am missing that days.
So I will try to pick my python and django knowledge again.

1. Python
Go to Python website and download the latest package https://www.python.org/ftp/python/3.4.1/python-3.4.1-macosx10.6.dmg
>python3 -V
Python 3.4.1

>python -V
Python 2.7.5

2. Django
https://www.djangoproject.com/download/

Get the latest version https://www.djangoproject.com/m/releases/1.7/Django-1.7.tar.gz
Unzip and link this directory to my working place.
>cd /opt/django
>sudo pythonsetup.pyinstall

Proof the installation
>python3
>import django
>print(django.get_version())
1.7

3. Try to Pick up my Old 2010 django and python knowledge
Some documents from Here
https://docs.djangoproject.com/en/1.7/

Verify the Installation
>python -c "import django;print(django.get_version())"
1.7

Build a poll application
Create the Project 
>django-admin.py startproject easypoll

__init__.py means that this directory is Python package.

WSGI is the Web Server Gateway Interface

database configuration is in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

default django apps
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages’,   — messaging framework
    'django.contrib.staticfiles’,    —— static files
)

Prepare the DB
>python manage.py migrate
Operations to perform:  Apply all migrations: admin, auth, sessions, contenttypes Running migrations:  Applying contenttypes.0001_initial... OK  Applying auth.0001_initial... OK  Applying admin.0001_initial... OK  Applying sessions.0001_initial... OK

Start the Server
This is a lightweight Web Server written purely in Python.

Or start the server with IP and Port
>python manage.py runserver 0.0.0.0:9000
Performing system checks... System check identified no issues (0 silenced). September 13, 2014 - 05:26:37 Django version 1.7, using settings 'easypoll.settings' Starting development server at http://0.0.0.0:9000/

The development Server automatically reloads Python code for each request as needed.
Creating Models
>python manage.py startapp polls

We then have the polls module there. with models.py, tests.py, views.py and admin.py

Choose the IDE http://www.jetbrains.com/pycharm/

The ORM layer is fast and clean to me.
from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Once this is defined, Django will create a database schema, create a Python database-access API for accessing Question and Choice objects.

Edit the easypoll/settings.py file to install the app polls.
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls'
)

>python manage.py makemigrations polls
Migrations for 'polls':  0001_initial.py:    - Create model Choice    - Create model Question    - Add field question to choice

Check the SQL
>python manage.py sqlmigrate polls 0001
BEGIN; CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL); CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL); CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id")); INSERT INTO "polls_choice__new" ("votes", "choice_text", "id") SELECT "votes", "choice_text", "id" FROM "polls_choice"; DROP TABLE "polls_choice"; ALTER TABLE "polls_choice__new" RENAME TO "polls_choice"; CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

From the SQL, we saw it backup the data for choice and do the fore key.

Check the issues
>python manage.py check
System check identified no issues (0 silenced).

Migrate the changes into DB
>python manage.py migrate
Operations to perform:  Apply all migrations: admin, sessions, polls, auth, contenttypes Running migrations:  Applying polls.0001_initial... OK

Play with the ORM API
>python manage.py shell
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Commands on the API
>>> from polls.models import Question, Choice >>> Question.objects.all() [] >>> from django.utils import timezone >>> q = Question(question_text="what's new?",pub_date=timezone.now()) >>> q.save() >>> q.id 1 >>> q.question_text "what's new?" >>> q.pub_date datetime.datetime(2014, 9, 15, 17, 25, 50, 477263, tzinfo=<UTC>) >>> q.question_text = "what's up?" >>> q.save() >>> Question.objects.all() [<Question: Question object>]

After I change the __str__ method as follow:
    def __str__(self):
        return '%s %s' % (self.question_text, self.pub_date)

help>
>>> quit() macbook-master:easypoll carl$ python manage.py shell>>> from polls.models import Question, Choice >>> Question.objects.all() [<Question: what's up? 2014-09-15 17:25:50.477263+00:00>]

Very impressive Search on the API
>>> Question.objects.all()
[<Question: what's up? 2014-09-15 17:25:50.477263+00:00>] >>> >>> Question.objects.filter(id=1) [<Question: what's up? 2014-09-15 17:25:50.477263+00:00>] >>> >>> Question.objects.filter(question_text__startswith='What') [<Question: what's up? 2014-09-15 17:25:50.477263+00:00>] >>> >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: what's up? 2014-09-15 17:25:50.477263+00:00>

Customized Method
>>> from polls.models import Question, Choice >>> >>> >>> q = Question.objects.get(id=1) >>> q.was_published_recently()

Display and Search the Related Objects
>>> q.choice_set.all() [] >>> q.choice_set.create(choice_text='Not Much', votes=1) <Choice: Not Much 1> >>> q.choice_set.create(choice_text='The Sky', votes=2) <Choice: The Sky 2> >>> c = q.choice_set.create(choice_text='The Ground', votes=3) >>> c.question <Question: what's up? 2014-09-15 17:25:50.477263+00:00> >>> q.choice_set.all() [<Choice: Not Much 1>, <Choice: The Sky 2>, <Choice: The Ground 3>] >>> q.choice_set.count() 3 >>> >>> c = q.choice_set.filter(choice_text__startswith='The') >>> c [<Choice: The Sky 2>, <Choice: The Ground 3>]

Really impressive on Django from 2010 to 2014, it improve a lot.

Tip 
Upgrade and Install from Sources
Both 1&2 are old from my understanding.

I download the source file from here https://www.python.org/ftp/python/3.4.0/Python-3.4.0.tar.xz

Unzip and try to build on my local machine.
>./configure --prefix=/Users/carl/tool/python-3.4.0
>make
>make altinstall

Soft link this directory to the working place
Edit the .profile File
export PATH=/opt/python/bin:$PATH

>. ~/.profile
>python -V
Python 3.4.0

I do not plan to do source installation.


References:
django 1~8
http://sillycat.iteye.com/blog/573279  Installation and hello world
http://sillycat.iteye.com/blog/573370  CRUD, html template
http://sillycat.iteye.com/blog/575687   session and wiki
http://sillycat.iteye.com/blog/576192   db, import and export
http://sillycat.iteye.com/blog/576864   page and UI
http://sillycat.iteye.com/blog/582074    nginx + fastcgi
http://sillycat.iteye.com/blog/582603    ajax and json
http://sillycat.iteye.com/blog/583993   Tag

https://docs.djangoproject.com/en/1.7/

https://www.djangoproject.com/download/

http://www.swoole.com/Twisted.html
http://blog.sina.com.cn/s/blog_704b6af70100py9n.html
http://twistedmatrix.com/trac/wiki

相关内容推荐