MyException - 我的异常网
当前位置:我的异常网» Perl/Python » Python Lover(一)Python and Django Introduction

Python Lover(一)Python and Django Introduction

www.MyException.Cn  网友分享于:2014-09-21  浏览:0次
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

文章评论

鲜为人知的编程真相
鲜为人知的编程真相
总结2014中国互联网十大段子
总结2014中国互联网十大段子
 程序员的样子
程序员的样子
旅行,写作,编程
旅行,写作,编程
2013年中国软件开发者薪资调查报告
2013年中国软件开发者薪资调查报告
漫画:程序员的工作
漫画:程序员的工作
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
Google伦敦新总部 犹如星级庄园
Google伦敦新总部 犹如星级庄园
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
程序员和编码员之间的区别
程序员和编码员之间的区别
为什么程序员都是夜猫子
为什么程序员都是夜猫子
如何成为一名黑客
如何成为一名黑客
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
代码女神横空出世
代码女神横空出世
我是如何打败拖延症的
我是如何打败拖延症的
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
程序员都该阅读的书
程序员都该阅读的书
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
编程语言是女人
编程语言是女人
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
每天工作4小时的程序员
每天工作4小时的程序员
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
看13位CEO、创始人和高管如何提高工作效率
看13位CEO、创始人和高管如何提高工作效率
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
2013年美国开发者薪资调查报告
2013年美国开发者薪资调查报告
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
程序员的鄙视链
程序员的鄙视链
程序员应该关注的一些事儿
程序员应该关注的一些事儿
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
那些性感的让人尖叫的程序员
那些性感的让人尖叫的程序员
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
程序员周末都喜欢做什么?
程序员周末都喜欢做什么?
Java程序员必看电影
Java程序员必看电影
10个调试和排错的小建议
10个调试和排错的小建议
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
一个程序员的时间管理
一个程序员的时间管理
程序员必看的十大电影
程序员必看的十大电影
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有