django,flask接口初试
Posted 不爱贞子爱爽子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django,flask接口初试相关的知识,希望对你有一定的参考价值。
-------------django
1、需要安装的环境 pip install django pip install djangorestframework ## restful组件 pip install markdown ## 将文本渲染成html pip install django-filter ## 查询插件 2、创建项目 ## django-admin startproject api ## cd api ## python manage.py startapp app 3、配置settings.py文件 ## INSTALLED_APPS INSTALLED_APPS = [ \'django.contrib.admin\', \'django.contrib.auth\', \'django.contrib.contenttypes\', \'django.contrib.sessions\', \'django.contrib.messages\', \'django.contrib.staticfiles\', \'django_api.apps.DjangoApiConfig\', \'app\', ##引入app \'rest_framework\' ## 引restful组件 ] ## 配置数据库 mysql DATABASES = { \'default\': { \'ENGINE\': \'django.db.backends.mysql\', \'NAME\': \'api\', \'USER\': \'root\', \'PASSWORD\': \'root\', \'HOST\': \'127.0.0.1\' } } 4、建表models.py /app/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models class Type(models.Model): \'\'\'type\'\'\' ###设置名称,去除前缀 class Meta: db_table = "type" type_name = models.CharField(max_length=50) pub_date = models.DateField() def __str__(self): return \'%s\' % self.type_name class Autor(models.Model): \'\'\'作者\'\'\' GENDER_CHOICES = ( (u\'M\', u\'Male\'), (u\'F\', u\'Female\'), ) class Meta: db_table = "autor" name = models.CharField(max_length=100) gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default=\'M\') def __str__(self): return \'%s\' % self.name class Book(models.Model): \'\'\'book\'\'\' class Meta: db_table = "book" type = models.ForeignKey(Type) name = models.CharField(max_length=200) description = models.TextField() autor = models.ForeignKey(Autor) src = models.CharField(max_length=200) pub_date =models.DateField() def __str__(self): return \'%s\' % self.name class Music(models.Model): \'\'\'music\'\'\' class Meta: db_table = \'music\' type = models.ForeignKey(Type) name =models.CharField(max_length=200) src = models.CharField(max_length=200) pub_date = models.DateField() def __str__(self): return \'%s\' % self.name 建立了四张表type,autor,book,music 5、新建序列化文件serializer.py /app/serializer.py from app.models import Type,Autor,Book,Music from rest_framework import serializers class TypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Type fields = (\'type_name\', \'pub_date\') class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Book fields = (\'type\',\'name\',\'description\',\'autor\',\'src\',\'pub_date\') class MusicSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Music fields = (\'type\',\'name\',\'src\',\'pub_date\') class AutorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Autor fields = (\'name\',\'gender\') 6、修改视图文件views.py /app/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User, Group from app.models import Type,Book,Autor,Music from rest_framework import viewsets from app.serializers import TypeSerializer,BookSerializer,MusicSerializer,AutorSerializer class TypeViewSet(viewsets.ModelViewSet): queryset = Type.objects.all() serializer_class = TypeSerializer class AutorViewSet(viewsets.ModelViewSet): queryset = Autor.objects.all() serializer_class = AutorSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class MusicViewSet(viewsets.ModelViewSet): queryset = Music.objects.all() serializer_class = MusicSerializer 7、生成路由 a、 urls.py /api/urls.py from django.conf.urls import url,include from django.contrib import admin from app import rest_urls urlpatterns = [ url(r\'^admin/\', admin.site.urls), url(r\'^api/\', include(rest_urls)), ] b.在app下新建rest_urls.py /app/rest_urls.py # -*- coding:utf-8 -*- from django.conf.urls import url, include from rest_framework import routers from app import views router = routers.DefaultRouter() router.register(r\'users\', views.UserViewSet) router.register(r\'groups\', views.GroupViewSet) router.register(r\'types\', views.TypeViewSet) router.register(r\'autors\', views.AutorViewSet) router.register(r\'books\', views.BookViewSet) router.register(r\'musics\', views.MusicViewSet) urlpatterns = [ url(r\'^\', include(router.urls)), url(r\'^api-auth/\', include(\'rest_framework.urls\', namespace=\'rest_framework\')) ]\\ 8、运行python manage.py runserver
以types为例
http://127.0.0.1:8000/api/types/ 显示type表所有数据
post http://127.0.0.1:8000/api/types/ 为type表新增数据
http://127.0.0.1:8000/api/types/1/ 显示type表id=1的数据
put http://127.0.0.1:8000/api/types/1/ 更新type表id=1的字段数据
delete http://127.0.0.1:8000/api/types/1/ 删除type表id=1的数据
-------------flask 1、安装flask和搭建web环境 pip install flask 。。。 以前的博客已经写过了。 2、创建项目 3、创建模型 modles.py # -*- coding: utf-8 -*- from app import db ## 类型表 class Type(db.Model): __tablename__ = \'type\' id = db.Column(db.Integer, primary_key=True) type_name = db.Column(db.String(50)) pub_date = db.Column(db.Date) def __repr__(self): return \'<Type %r>\' % self.type_name def get_info(self): obj = db.session.execute(\'select * from type\').fetchall() return obj ## autor class Autor(db.Model): M = \'m\' F = \'F\' __tablename__ = \'autor\' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) gender = db.Column(db.String, default= M) src = db.Column(db.String(200)) pub_date = db.Column(db.Date) class Book(db.Model): __tablename__ = \'book\' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(200)) description = db.Column(db.Text) type_id = db.Column(db.Integer,db.ForeignKey(\'type.id\')) autor_id = db.Column(db.Integer, db.ForeignKey(\'autor.id\')) src = db.Column(db.String(200)) pub_date = db.Column(db.Date) class Music(db.Model): __tablename__ = \'music\' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(200)) type_id = db.Column(db.Integer,db.ForeignKey(\'type.id\')) src = db.Column(db.String(200)) pub_date = db.Column(db.Date) 4、序列化文件serializers.py # -*- coding: utf-8 -*- from marshmallow import Schema, fields ###admin表 class TypeSchema(Schema): id = fields.Int() type_name = fields.Str() pub_date = fields.Str() 5、视图文件 main/views.py # -*- coding: utf-8 -*- from flask import jsonify,abort,request,redirect from .. import db from ..models import Type from . import main from ..serializers import TypeSchema import datetime ###定义login表单 @main.route(\'/api/v1.0/types/\', methods=[\'GET\',\'POST\']) def get_types(): if request.method==\'GET\': types = Type.query.all() ## -----way 1 # list = [] # dict = {} # for v in types: # a = { # \'id\': v.id, # \'type_name\': v.type_name, # \'pub_date\': v.pub_date # } # list.append(a) # dict[\'types\'] = list # return jsonify(dict) ## way 2 schema = TypeSchema(many = True) list = schema.dump(types) return jsonify(list) else: if request.values.get(\'pub_date\'): pub_date = request.values.get(\'pub_date\') else: pub_date =datetime.date() if request.values.get(\'type_name\'): type_name = request.values.get(\'type_name\') else: type_name =\'\' type = Type(type_name = type_name,pub_date = pub_date) db.session.add(type) db.session.commit() redirect(\'/api/v1.0/types/\') @main.route(\'/api/v1.0/types/<int:id>\', methods=[\'GET\',\'PUT\',\'DELETE\']) def get_type(id): if request.method ==\'GET\': type = Type.query.filter_by(id=id).first() if type == \'\': abort(404) schema = TypeSchema() type = schema.dump(type) return jsonify({\'type\': type}) elif request.method ==\'PUT\': try: id = request.values.get(\'id\') except: abort(404) if request.values.get(\'type_name\'): type_name = request.values.get(\'type_name\') else: pass if request.values.get(\'pub_date\'): pub_date = request.values.get(\'pub_date\') else: pass else: ## 删除 pass
----基本是这样,flask-restful这个库还没有使用过,可以尝试下。
----资料来源于网络,flask官方文档。
以上是关于django,flask接口初试的主要内容,如果未能解决你的问题,请参考以下文章