设为首页 收藏本站
查看: 242|回复: 0

[经验分享] Python Lover(1)Python and Django Introduction

[复制链接]

尚未签到

发表于 2017-4-21 11:31:24 | 显示全部楼层 |阅读模式
  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

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-367348-1-1.html 上篇帖子: Python 应用领域 下篇帖子: 关于Python的一些资源
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表