-------------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接口初试的更多相关文章

  1. Django&Flask区别

    Flask Flask 本身只有一个内核,几乎所有的功能都需要用第三方的扩展来实现. Flask 没有默认使用的数据库,默认依赖两个外部库:Jinja2 模板引擎和 WSGI 工具箱(采用的时 Wer ...

  2. 在 Django/Flask 开发服务器上使用 HTTPS

    使用 Django 或 Flask 这种框架开发 web app 的时候一般都会用内建服务器开发和调试程序,等程序完成后再移交到生产环境部署.问题是这些内建服务器通常都不支持 HTTPS,我们想在开发 ...

  3. nginx + uwsgi + django/flask Nginx + php-fpm + PHP

    后端服务器设置nginx + uwsgi + django/flask需要注意的问题 - ACE开发者 https://acejoy.com/2018/09/09/547/ 后端开发应用中,除了Ngi ...

  4. Django&,Flask&pyrthon原生sql语句 基本操作

    Django框架 ,Flask框架 ORM 以及pyrthon原生sql语句操作数据库 WHAT IS ORM? ORM( Object Relational Mapping) 对象关系映射 , 即通 ...

  5. windows下apache + mod_wsgi + python部署flask接口服务

    windows下apache + mod_wsgi + python部署flask接口服务 用python3安装虚拟环境 为啥要装虚拟环境? 原因1:安装虚拟环境是为了使项目的环境和全局环境隔离开,在 ...

  6. jmeter测试 flask 接口请求

    jmeter测试 flask 接口请求 flask的代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flas ...

  7. python三大web框架Django,Flask,Flask,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Python几种主流框架 从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python We ...

  8. Django,Flask,Tornado三大框架对比,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Django 与 Tornado 各自的优缺点Django优点: 大和全(重量级框架)自带orm,template,view 需要的功能也可以去找第三方的app注重高效开发全自动化的管理后台(只需要使 ...

  9. tornado django flask 跨域解决办法(cors)

    XMLHttpRequest cannot load http://www.baidu.com. No 'Access-Control-Allow-Origin' header is present ...

随机推荐

  1. react-hot-loader 3.0于1.3的区别

    现在react-hot-loader 3.0版本应该还是beta版本,不过没关系,还是可以正常使用,我在项目中用的是react-hot-loader 3.0.0-beta.7 版本,并没用发现任何问题 ...

  2. 使用kolla安装的openstack mariadb为集群所有节点无法启动

    当在做测试时,把所有的openstack节点都关机,再开启做测试时,发现mariadb galera集群启不来,相当于所有的mariadb集群都停止了(跟所有节点断电情况相似),这时候怎么办呢,重新建 ...

  3. JS replace()用法实现replaceAll

    由于js没有提供replaceAll,则使用正则表达式实现全局替换. javascript中replace() 方法如果直接用str.replace("-","!&quo ...

  4. 在Ubuntu上使用noip动态域名的方法(ddns)

    首先,注册一个noip.com的帐号. 注册的步骤见这篇教程:http://www.cnblogs.com/infopi/p/3991407.html 建立目录 第1行进入当前用户的home目录 第2 ...

  5. 一些常用的排序算法(C版)

    1. 直接插入排序(稳定排序) 简单的说就是将序列分为有序序列和无序序列.每一趟排序都是将无序序列的第一个元素插入有序序列中.R[1… i-1] <- R[i…n] , 每次取R[i]插入到R[ ...

  6. WyBox用usb口驱动4G模块EC20

    按照: http://wiki.openwrt.org/doc/howtobuild/wireless-router-with-a-3g-dongle 然后: 进入linux-3.10.49/driv ...

  7. OpenWrt路由器通过LuCI界面实现Guest SSID功能

    转自: http://blog.ltns.info/linux/guest_ssid_over_openwrt_router/ 之前尝试过 Tomato路由器设置VLAN实现Guest SSID功能, ...

  8. 坑人的 Javascript 模块化编程 require.js

    坑人的 Javascript 模块化编程 require.js

  9. C/C++中字符串和数字互转小结

    一. 数字 转 char*型 1.sprintf函数(适合C和C++) 示例: char str[50]; int num = 345; sprintf(str,"%d",num) ...

  10. Flex组件参考 代码参考汇总

    1:tourdeflex快速熟悉各种组件用法的参考http://www.adobe.com/devnet/flex/tourdeflex.html在线:http://www.adobe.com/dev ...