為什麼要用djangorestframework做server端?
我個人是因為簡單,以及需要寫的程式很少
如果是單純的資料存取,差不多就是定義table及json樣式
另外就是自帶api管理介面,帳號管理(這篇還不會用到帳號)
以下程式看步驟看起來很多,其實都是打打指令產生程式而以
如果你還更懶,可以直接用最下面的github clone下來用修改的,秒完工
以下指指執行於ubuntu 14.04 + python 2.7,其它系統可自行微調,差別應該不大
1.安裝所需的lib
4.新增檔案 myRest/api/serializers.py 設定json樣式
最後目錄結構
也可以測試,點api連結,下面的form打上資料就可以新增一筆資料
當然也可以修改刪除資料,方式就是api網址後加上資料的id
http://localhost:8000/api/records/1/
我個人是因為簡單,以及需要寫的程式很少
如果是單純的資料存取,差不多就是定義table及json樣式
另外就是自帶api管理介面,帳號管理(這篇還不會用到帳號)
以下程式看步驟看起來很多,其實都是打打指令產生程式而以
如果你還更懶,可以直接用最下面的github clone下來用修改的,秒完工
以下指指執行於ubuntu 14.04 + python 2.7,其它系統可自行微調,差別應該不大
1.安裝所需的lib
sudo pip install django sudo pip install djangorestframework2.建立專案
$ 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 files3.修改檔案 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 = RecordSerializer6.新增檔案 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 files10.執行專案,如訊息所示,要停掉按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
3.修改檔案 myRest/record/models.py
回覆刪除date = models.DateTimeField(auto_now=True, auto_now_add=True)
-> date = models.DateTimeField(auto_now=True)
auto_now, auto_now_add 好像只能選一個