MyException - 我的异常网
当前位置:我的异常网» Go » Python Monitor Water Falls(三)django restful fra

Python Monitor Water Falls(三)django restful framework

www.MyException.Cn  网友分享于:2013-03-06  浏览:0次
Python Monitor Water Falls(3)django restful framework
Python Monitor Water Falls(3)django restful framework

Sqlite browser to see the data
http://sqlitebrowser.org/

Set water record module
>django-admin.py startapp waterrecord

Set up the models.py to define a ORM layer to persist the data in sqlite
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

class WaterRecord(models.Model):
    waterName = models.CharField('water_name', max_length=50)
    released = models.BooleanField('released', default = False)
    releasedDate = models.CharField('released_date', max_length=20) #2018-01-16
    updateTime = models.DateTimeField('update_time', auto_now=True)
    createTime = models.DateTimeField('create_time', auto_now_add=True)

    def __unicode__(self):
        return self.waterName + self.releasedDate

Add this to the settings.py to enable this module
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'restful_api.waterrecord',
]

Models had some changes, so
>./manage.py makemigrations
>./manage.py migrate

Check the Database Information
>python manage.py shell
>>>from restful_api.waterrecord.models import WaterRecord
>>>WaterRecord.objects.all()
<QuerySet [<WaterRecord: MableFalls2018-01-01>, <WaterRecord: MableFalls2018-01-01>, <WaterRecord: MableFalls2018-01-02>]>

Serializer to support the JSON to Python Object and Object to JSON in serializers.py
# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import WaterRecord

class WaterRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = WaterRecord
        fields = ('id', 'waterName', 'released', 'releasedDate')

URL Mapping witch is helpful function from the framework in urls.py
# -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^waterrecords/$', views.water_record_list, name='water_record_list'),
    # url(r'^waterrecords/$', views.WaterRecordList.as_view(), name='water_record_list'),
    # url(r'^waterrecords/$', views.WaterRecordListCreate.as_view(), name='water_record_list'),
    url(r'^waterrecords/(?P<pk>[0-9]+)$', views.water_record_detail, name='water_record_detail'),
]

Following the documents, I put a lot of different ways of views.py implementation there, but we only use the last 2 methods
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics

from .models import WaterRecord
from .serializers import WaterRecordSerializer

# APIView
class WaterRecordList(APIView):
    def get(self, request, format=None):
        items = WaterRecord.objects.all()
        serializer = WaterRecordSerializer(items, many=True)
        return Response(serializer.data)
    def post(self, request, format=None):
        serializer = WaterRecordSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# ListCreateAPIView
class WaterRecordListCreate(generics.ListCreateAPIView):
    queryset = WaterRecord.objects.all()
    serializer_class = WaterRecordSerializer

# api_view
@api_view(['GET', 'POST'])
def water_record_list(request):
    '''
    List all items or create a new item
    '''
    if request.method == 'GET':
        items = WaterRecord.objects.all()
        serializer = WaterRecordSerializer(items, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = WaterRecordSerializer(data = request.data)
        if serializer.is_valid():
            item = serializer.validated_data
            result, created = WaterRecord.objects.get_or_create(
                waterName=item['waterName'],
                releasedDate=item['releasedDate'],
                defaults = item)
            serializerResult = WaterRecordSerializer(result)
            return Response(serializerResult.data, status = status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def water_record_detail(request, pk):
    try:
        item = WaterRecord.objects.get(pk=pk)
    except WaterRecord.DoesNotExist:
        return Response(status = status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = WaterRecordSerializer(item)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = WaterRecordSerializer(item, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Deployment
Directly run that
>python manage.py runserver

Install the deployment tool
>pip install gunicorn

Libraries, pick up one is fine.
>pip install eventlet
>pip install greenlet
>pip install gevent

It works
>gunicorn restful_api.wsgi

Setting file
>cat gunicorn.py.ini
import multiprocessing

bind = "0.0.0.0:8000"

workers = multiprocessing.cpu_count() * 2 + 1

Run the command
>gunicorn -c gunicorn.py.ini restful_api.wsgi

Command to curl the RESTful API about water record
>curl http://localhost:8000/api/waterrecords/

>curl -X POST http://localhost:8000/api/waterrecords/ -d "waterName=MableFalls&released=true&releasedDate=2018-01-01"

>curl -X DELETE http://localhost:8000/api/waterrecords/1

>curl -X PUT http://localhost:8000/api/waterrecords/2 -d "waterName=MableFalls&released=false&releasedDate=2018-01-01"

I really like to deploy in Docker as follow:
start.sh
#!/bin/sh -ex

#start the service
cd /share/water-monitor/restful_api
gunicorn -c gunicorn.py.ini restful_api.wsgi

Makefile to support the build and run
IMAGE=sillycat/public
TAG=water-monitor-restful-api
NAME=water-monitor-restful-api

docker-context:

build: docker-context
   docker build -t $(IMAGE):$(TAG) .

run:
   docker run -d -p 8000:8000 -v /opt/water-monitor/restful_api:/share/water-monitor/restful_api --name $(NAME) $(IMAGE):$(TAG)

debug:
   docker run -ti -p 8000:8000 -v /opt/water-monitor/restful_api:/share/water-monitor/restful_api --name $(NAME) $(IMAGE):$(TAG) /bin/bash

clean:
   docker stop ${NAME}
   docker rm ${NAME}

logs:
   docker logs ${NAME}

publish:
   docker push ${IMAGE}:${TAG}

fetch:
   docker pull ${IMAGE}:${TAG}

Dockerfile to adjust all the ENV
#Set up FTP in Docker

#Prepre the OS
FROM resin/raspberrypi3-python
MAINTAINER Carl Luo <luohuazju@gmail.com>

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get -y update
RUN apt-get -y dist-upgrade

#install the software
RUN pip install django
RUN pip install djangorestframework
RUN pip install markdown
RUN pip install django-filter
RUN pip install gunicorn

RUN pip install greenlet
RUN pip install gevent
RUN pip install eventlet

#start the application
EXPOSE  8000
RUN     mkdir -p /app/
ADD     start.sh /app/
WORKDIR /app/
CMD    [ "./start.sh" ]

References:
more example
http://www.cnblogs.com/ccorz/p/djangorestframework-shi-yong-li-zi.html

http://sillycat.iteye.com/blog/2408979

Python Lover
http://sillycat.iteye.com/blog/2116834
http://sillycat.iteye.com/blog/2116836
http://sillycat.iteye.com/blog/2117212
http://sillycat.iteye.com/blog/2117576
http://sillycat.iteye.com/blog/2188140

Python Console
http://sillycat.iteye.com/blog/2372912
http://sillycat.iteye.com/blog/2373528
http://sillycat.iteye.com/blog/2373531
http://sillycat.iteye.com/blog/2373701

http://www.django-rest-framework.org/tutorial/1-serialization/
https://github.com/encode/rest-framework-tutorial
https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework
https://github.com/BurkovBA/django-rest-framework-mongoengine-example


文章评论

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