code

2016年5月23日 星期一

djangorestframework 權限控制


直接下載上次寫的rest,你有其它rest專案也可以直接拿來用
$git clone https://github.com/montanoh/python-djangorestframework-example.git securityRest
$cd securityRest/
$./manage.py syncdb
$./manage.py runserver
此時 http://127.0.0.1:8000/api/, http://127.0.0.1:8000/api/records/ 應該可以正常使用
編輯 myRest/settings.py

因為輸入了中文註解所以在開頭加上 # -*- encoding: utf-8 -*-

在 MIDDLEWARE_CLASSES = ( ... ) 後加上下面這一段,要加上權限管理真正做的事其實只有這一段
REST_FRAMEWORK = {
    # 加上這一段 rest api 都會變成唯讀
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'],
    # 加上下面這段,則需要帳號密碼才能存取rest api
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAdminUser',],
    # 其它一般設定
    'PAGE_SIZE': 10
}

此時頁面上的api己經不能使用,會出現錯誤訊息,如需存取需用curl,並且需要加上帳號密碼
securityRest$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://12.0.0.1:8000/api/records/
[
    {

        "id": 1,
        "date": "2016-05-12T07:10:07.954Z",
        "gid": "aaa",
        "tag": "tag1",
        "note": "test",
        "money": 100.0
    }
]

django 內建管理帳號網址 http://127.0.0.1:8000/admin/ 可以增刪管理帳號



使用指令 manage.py createsuperuser 也可以建立帳號
securityRest$ ./manage.py createsuperuser
Username (leave blank to use 'mon'): test
Email address: test@test.com
Password: 
Password (again): 
Superuser created successfully.

2016年5月17日 星期二

專案指令清單

總是會有人問這些問題,「怎麼打包」、「怎麼deploy」、[怎麼跑測試]
簡單的建立一個指令清單解決所有問題


以下指指執行於ubuntu 14.04 + python 2.7,其它系統可自行微調,差別應該不大
$touch run.py
$chmod +x run.py


修改 run.py 內容
#!/usr/bin/python
#coding=utf-8

import os

cmd = [[
"cd project; mvn clean install ",
"cd project; mvn clean install -Dmaven.test.skip=true",
"cd ~/tomcat/bin;./tomcat.sh", ],
["註解1","打包跳過測試ooxx","desc3"]]

for idx, x in enumerate(cmd[0]): 
 print('\033[9{3}m {0}:{1:55}   {0}\033[0m#{2}').format(idx, x[:55], cmd[1][idx], idx % 7)

userInput = raw_input("run: ")

try:
 print "run:", cmd[0][int(userInput)]
 os.system(cmd[0][int(userInput)])
except Exception, e:
 print "incorrect input"


修改自行需要的指令及註解就行,指令及註解需要成對
程式中{1:55}中的55是顯示指令的寬度,也可以自行調整
色碼變化是依指令數量改變的,有研究bbs色碼的高手可自行修改
也可以拿掉所有 \033[...m  去掉顏色
執行結果如下,輸入數字就可以執行想執行的指令


2016年5月12日 星期四

django-rest-framework 十分鐘架一個簡單的 restful api

為什麼要用djangorestframework做server端?
我個人是因為簡單,以及需要寫的程式很少
如果是單純的資料存取,差不多就是定義table及json樣式
另外就是自帶api管理介面,帳號管理(這篇還不會用到帳號)
以下程式看步驟看起來很多,其實都是打打指令產生程式而以
如果你還更懶,可以直接用最下面的github clone下來用修改的,秒完工

以下指指執行於ubuntu 14.04 + python 2.7,其它系統可自行微調,差別應該不大

1.安裝所需的lib
sudo pip install django
sudo pip install djangorestframework
2.建立專案
$ django-admin.py startproject myRest
$ cd myRest/
/myRest$ django-admin.py startapp api
/myRest$ django-admin.py startapp record
目前目錄狀況
.
├── api
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── myRest
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── record
    ├── admin.py
    ├── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py
3 directories, 15 files
3.修改檔案 myRest/record/models.py 資料要長怎樣在這邊設定
from django.db import models


class Record(models.Model):
    id = models.AutoField(primary_key=True)
    date = models.DateTimeField(auto_now=True, auto_now_add=True)
    gid = models.CharField(max_length=100)
    tag = models.CharField(max_length=100)
    note = models.CharField(max_length=100)
    money = models.FloatField()

4.新增檔案 myRest/api/serializers.py 設定json樣式
from rest_framework import serializers
from record.models import Record


class RecordSerializer(serializers.ModelSerializer):
    """
    Serializer to parse Record data
    """

    class Meta:
        model = Record
        fields = ('id', 'date', 'gid', 'tag', 'note', 'money')
5.修改檔案 myRest/api/views.py api 存取介面
from rest_framework import viewsets
from record.models import Record
from api.serializers import RecordSerializer

ng
class Record(viewsets.ModelViewSet):
    queryset = Record.objects.all()
    serializer_class = RecordSerializer
6.新增檔案 myRest/api/urls.py  設定api url
from django.conf.urls import patterns, include, url
from api.views import Record
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'records', Record)

urlpatterns = patterns('',
                       url(r'^', include(router.urls)),
                       )
7.修改檔案 myRest/myRest/urls.py 設定專案url所有頁面都要設在設裡才會work
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url( r'^api/', include( 'api.urls' ) ),
)
8.修改檔案myRest/myRest/settings.py 專案設定檔,看起來很長其實只加了三行,下方也可以找到資料庫的設定,預設是sqlite,有需要可以改掉
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b287(m-v%d3au!qf(0m%3*ha3jf3)2dluq13yfp10n6kc$4)c3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'record',
    'api',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'myRest.urls'

WSGI_APPLICATION = 'myRest.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

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

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
9.回到專案目錄,執行myRest$ ./manage.py syncdb 同步資料庫
myRest$ ./manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table record_record

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes (建立管理者帳號)
Username (leave blank to use 'mon'): admin
Email address: xxx@gmail.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

最後目錄結構
.
├── api
│   ├── admin.py
│   ├── admin.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── serializers.py
│   ├── serializers.pyc
│   ├── tests.py
│   ├── urls.py
│   ├── urls.pyc
│   ├── views.py
│   └── views.pyc
├── db.sqlite3
├── manage.py
├── myRest
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
└── record
    ├── admin.py
    ├── admin.pyc
    ├── __init__.py
    ├── __init__.pyc
    ├── models.py
    ├── models.pyc
    ├── tests.py
    └── views.py

3 directories, 31 files
10.執行專案,如訊息所示,要停掉按ctrl+c就行
myRest$ ./manage.py runserver
Validating models...

0 errors found
May 12, 2016 - 07:38:27
Django version 1.6.1, using settings 'myRest.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
11.api 測試
myRest/myRest$ curl http://127.0.0.1:8000/api/records/
[{"id": 1, "date": "2016-05-12T07:10:07.954Z", "gid": "aaa", "tag": "tag1", "note": "test", "money": 100.0}]myRest/myRest$

myRest/myRest$ curl -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/api/records/
[
    {
        "id": 1,
        "date": "2016-05-12T07:10:07.954Z",
        "gid": "aaa",
        "tag": "tag1",
        "note": "test",
        "money": 100.0
    }
]
browser上可以看到管理頁面,網址就是啟動時顯示的 http://127.0.0.1:8000/ 加上程式中設定的 api 也就是 http://127.0.0.1:8000/api/ 畫面下方就是 api的清單

也可以測試,點api連結,下面的form打上資料就可以新增一筆資料

 當然也可以修改刪除資料,方式就是api網址後加上資料的id
http://localhost:8000/api/records/1/


django的基本管理頁面在 http://localhost:8000/admin/  這就不多做介紹

如果程式不想用打的,我在git hub 放了一份
https://github.com/montanoh/python-djangorestframework-example