Python[7] :Python制作json格式和shell格式的API

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 MongoDB,通用型 2核4GB
简介:

api(应用程序编程接口) 

API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。


继承前几篇文章,围绕资产管理搜集的信息,进行这篇文章的api

一、sqlite数据库的基本使用

资产管理的后台数据库用的是sqlite,这个是轻量级的数据库,大家可能对这个数据库很陌生。那么我们就简单的来看看这个数据库是如何使用的?

1、登陆sqlite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@localhost ~] # cd Simplecmdb
[root@localhost Simplecmdb] # ls
Boot_django.sh        curl_post_test_v2.sh  db.sqlite3  manage.py         Simplecmdb
curl_post_test_v1.sh  curl_post_test_v3.py  hostinfo    post_hostinfo.py
[root@localhost Simplecmdb] # python manage.py shell
/usr/lib/python2 .6 /site-packages/django/db/backends/sqlite3/base .py:58: RuntimeWarning: SQLite received a naive datetime (2015-03-03 16:18:21.229988)  while  time  zone support is active.
   RuntimeWarning)
Python 2.6.6 (r266:84292, Feb 22 2013, 00:00:18) 
Type  "copyright" "credits"  or  "license"  for  more  information.
 
IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about  'object' , use  'object??'  for  extra details.
 
In [1]:

2、查看models.py

文件中有Host和HostGroup两个类,每个类中都定义了字段名和数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@localhost Simplecmdb] # cat hostinfo/models.py
from django.db  import  models
 
# Create your models here.
class Host(models.Model):
     hostname  = models.CharField(max_length=50)
     ip = models.IPAddressField()
     osversion = models.CharField(max_length=50)
     memory = models.CharField(max_length=50)
     disk = models.CharField(max_length=50)
     vendor_id = models.CharField(max_length=50)
     model_name = models.CharField(max_length=50)
     cpu_core = models.CharField(max_length=50)
     product = models.CharField(max_length=50)
     Manufacturer = models.CharField(max_length=50)
     sn = models.CharField(max_length=50)
 
     def __str__(self):
     return  self. hostname
 
class HostGroup(models.Model):
     groupname = models.CharField(max_length=50)
     members = models.ManyToManyField(Host)

3、将资产管理数据结构导入到当前的环境中并使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
In [1]: from hostinfo.models  import  *
 
In [3]: HostGroup.     #有很多方法可以使用
HostGroup.DoesNotExist             HostGroup.delete                   HostGroup.save
HostGroup.MultipleObjectsReturned  HostGroup.full_clean               HostGroup.save_base
HostGroup.add_to_class             HostGroup.members                  HostGroup.serializable_value
HostGroup.clean                    HostGroup.mro                      HostGroup.unique_error_message
HostGroup.clean_fields             HostGroup.objects                  HostGroup.validate_unique
HostGroup.copy_managers            HostGroup.pk                       
HostGroup.date_error_message       HostGroup.prepare_database_save  
 
In [3]: HostGroup.objects.all()     #查看类中所有的对象(5个),返回值为列表
Out[3]: [<HostGroup: HostGroup object>, <HostGroup: HostGroup object>, <HostGroup: HostGroup object>, <HostGroup: HostGroup object>, <HostGroup: HostGroup object>]
 
In [5]: hg = HostGroup.objects.all()[0]     #取第一个对象并赋值为hg
 
In [6]: hg.     #hg中的方法
hg.DoesNotExist             hg.delete                   hg.objects                  hg.serializable_value
hg.MultipleObjectsReturned  hg.full_clean               hg.pk                       hg.unique_error_message
hg.clean                    hg.groupname                hg.prepare_database_save    hg.validate_unique
hg.clean_fields             hg. id                        hg.save                     
hg.date_error_message       hg.members                  hg.save_base                
 
In [6]: hg.groupname     #查看对应的组的名字
Out[6]: u 'nginx'
 
In [7]: hg.members     #查看成员,返回值是一个对象,是对象就有方法和属性
Out[7]: <django.db.models.fields.related.ManyRelatedManager at 0x2156f10>
 
In [8]: hg.members.all()     #查看所有成员
Out[8]: [<Host: nginx_master.com>, <Host: nginx_slave.com>]
 
In [10]: h = hg.members.all()[0]
 
In [12]: h.
h.DoesNotExist             h.delete                   h.memory                   h.save
h.Manufacturer             h.disk                     h.model_name               h.save_base
h.MultipleObjectsReturned  h.full_clean               h.objects                  h.serializable_value
h.clean                    h.hostgroup_set            h.osversion                h.sn
h.clean_fields             h. hostname                  h.pk                       h.unique_error_message
h.cpu_core                 h. id                        h.prepare_database_save    h.validate_unique
h.date_error_message       h.ip                       h.product                  h.vendor_id
 
In [12]: h. hostname
Out[12]: u 'nginx_master.com'
 
In [13]: h.ip
Out[13]: u '192.168.1.200'
 
In [14]: h.ip =  '192.168.1.234'     #修改记录
 
In [15]: h.ip
Out[15]:  '192.168.1.234'
 
In [16]: h.save()     #保存到数据库中,会在后台admin页面中看到


二、api(json)

1、实现json格式api的草图

wKiom1T1ceryZA3XAAGIRi796SY810.jpg

2、在命令行中实现上述效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[root@localhost Simplecmdb] # python manage.py shell
/usr/lib/python2 .6 /site-packages/django/db/backends/sqlite3/base .py:58: RuntimeWarning: SQLite received a naive datetime (2015-03-03 16:36:45.158750)  while  time  zone support is active.
   RuntimeWarning)
Python 2.6.6 (r266:84292, Feb 22 2013, 00:00:18) 
Type  "copyright" "credits"  or  "license"  for  more  information.
 
IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about  'object' , use  'object??'  for  extra details.
 
In [1]: from hostinfo.models  import  *
 
In [2]: d = []
 
In [3]: hg = HostGroup.objects.all()
 
In [4]:  for  in  hg:
    ...:         ret = { 'groupname' :g.groupname, 'members' :[]}
    ...:          for  in  g.members.all():
    ...:                 ret_h = { 'hostname' :h. hostname , 'ip' :h.ip}
    ...:                 ret[ 'members' ].append(ret_h)
    ...:         d.append(ret)
    ...:         
 
In [5]: print d
[{ 'groupname' : u 'nginx' 'members' : [{ 'ip' : u '192.168.1.234' 'hostname' : u 'nginx_master.com' }, { 'ip' : u '192.168.1.201' 'hostname' : u 'nginx_slave.com' }]}, { 'groupname' : u 'mongodb' 'members' : [{ 'ip' : u '192.168.1.121' 'hostname' : u 'mongodb.com' }]}, { 'groupname' : u 'db' 'members' : [{ 'ip' : u '192.168.1.105' 'hostname' : u 'mysql_master.com' }, { 'ip' : u '192.168.1.106' 'hostname' : u 'mysql_slave.com' }]}, { 'groupname' : u 'tomcat' 'members' : [{ 'ip' : u '192.168.1.109' 'hostname' : u 'tomcat_node1.com' }, { 'ip' : u '192.168.1.110' 'hostname' : u 'tomcat_node2.com' }, { 'ip' : u '192.168.1.111' 'hostname' : u 'tomcat_node3.com' }, { 'ip' : u '192.168.1.112' 'hostname' : u 'tomcat_node4.com' }]}, { 'groupname' : u 'memcached' 'members' : [{ 'ip' : u '192.168.1.120' 'hostname' : u 'memory.com' }]}]
 
对上述列表遍历能看的更清楚
In [6]:  for  in  d:
    ...:     print i
    ...:     
{ 'groupname' : u 'nginx' 'members' : [{ 'ip' : u '192.168.1.234' 'hostname' : u 'nginx_master.com' }, { 'ip' : u '192.168.1.201' 'hostname' : u 'nginx_slave.com' }]}
{ 'groupname' : u 'mongodb' 'members' : [{ 'ip' : u '192.168.1.121' 'hostname' : u 'mongodb.com' }]}
{ 'groupname' : u 'db' 'members' : [{ 'ip' : u '192.168.1.105' 'hostname' : u 'mysql_master.com' }, { 'ip' : u '192.168.1.106' 'hostname' : u 'mysql_slave.com' }]}
{ 'groupname' : u 'tomcat' 'members' : [{ 'ip' : u '192.168.1.109' 'hostname' : u 'tomcat_node1.com' }, { 'ip' : u '192.168.1.110' 'hostname' : u 'tomcat_node2.com' }, { 'ip' : u '192.168.1.111' 'hostname' : u 'tomcat_node3.com' }, { 'ip' : u '192.168.1.112' 'hostname' : u 'tomcat_node4.com' }]}
{ 'groupname' : u 'memcached' 'members' : [{ 'ip' : u '192.168.1.120' 'hostname' : u 'memory.com' }]}

3、api(json)

 3.1、添加访问的api的url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@localhost Simplecmdb] # vim Simplecmdb/urls.py
 
from django.conf.urls  import  patterns, include, url
 
from django.contrib  import  admin
admin.autodiscover()
 
urlpatterns = patterns( '' ,
     # Examples:
     # url(r'^$', 'Simplecmdb.views.home', name='home'),
     # url(r'^blog/', include('blog.urls')),
 
     url(r '^admin/' , include(admin.site.urls)),
     url(r '^hostinfo$' , 'hostinfo.views.index' ),
     url(r '^hostinfo/getjson$' , 'hostinfo.views.getjson' ),
)

  3.2、定义响应请求的视图文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
[root@localhost Simplecmdb] # vim hostinfo/views.py
 
from django.shortcuts  import  render
from django.http  import  HttpResponse
from hostinfo.models  import  Host
from hostinfo.models  import  HostGroup
import  pickle
import  json
 
# Create your views here.
def index(req):
     if  req.method ==  'POST' :
         pick_obj = json.loads(req.body)
         hostname  = pick_obj[ 'hostname' ]
         ip = pick_obj[ 'ip' ]
         osversion = pick_obj[ 'osversion' ]
         memory = pick_obj[ 'memory' ]
         disk = pick_obj[ 'disk' ]
         vendor_id = pick_obj[ 'vendor_id' ]
         model_name = pick_obj[ 'model_name' ]
         cpu_core = pick_obj[ 'cpu_core' ]
         product = pick_obj[ 'product' ]
         Manufacturer = pick_obj[ 'Manufacturer' ]
         sn = pick_obj[ 'sn' ]
 
         try:
             host = Host.objects.get( hostname = hostname )
         except:
             host = Host()
         host. hostname  hostname
         host.ip = ip
         host.osversion = osversion
         host.memory = memory
         host.disk = disk
         host.vendor_id = vendor_id
         host.model_name = model_name
         host.cpu_core = cpu_core
         host.product = product
         host.Manufacturer = Manufacturer
         host.sn = sn
         host.save()
         return  HttpResponse( 'ok' )
     else :
         return  HttpResponse( 'no data' )
 
#添加如下行
def getjson(req):
     hg = HostGroup.objects.all()
     d = []
     for  in  hg:
         ret = { 'groupname' :g.groupname, 'members' :[]}
         for  in  g.members.all():
             ret_h = { 'hostname' :h. hostname , 'ip' :h.ip}
             ret[ 'members' ].append(ret_h)
         d.append(ret)
     return  HttpResponse(json.dumps(d))

 3.3、浏览器访问(需要注意,必须启动JSONView才能如下显示)

wKiom1T1dDKAtFxuAAKWTNNAZ4Y749.jpg

wKioL1T1dRDxglJ0AAHj_eNw-I8874.jpg



三、api(shell)

1、实现json格式api的草图

1
2
3
4
5
API
-----shell格式-----
web  node1 192.168.1.10
web  node2 192.168.1.11
db   node3 192.168.1.11


2.2、定义响应请求的视图文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
[root@localhost Simplecmdb] # vim hostinfo/views.py
 
from django.shortcuts  import  render
from django.http  import  HttpResponse
from hostinfo.models  import  Host
from hostinfo.models  import  HostGroup
import  pickle
import  json
 
# Create your views here.
def index(req):
     if  req.method ==  'POST' :
         pick_obj = json.loads(req.body)
         hostname  = pick_obj[ 'hostname' ]
         ip = pick_obj[ 'ip' ]
         osversion = pick_obj[ 'osversion' ]
         memory = pick_obj[ 'memory' ]
         disk = pick_obj[ 'disk' ]
         vendor_id = pick_obj[ 'vendor_id' ]
         model_name = pick_obj[ 'model_name' ]
         cpu_core = pick_obj[ 'cpu_core' ]
         product = pick_obj[ 'product' ]
         Manufacturer = pick_obj[ 'Manufacturer' ]
         sn = pick_obj[ 'sn' ]
 
         try:
             host = Host.objects.get( hostname = hostname )
         except:
             host = Host()
         host. hostname  hostname
         host.ip = ip
         host.osversion = osversion
         host.memory = memory
         host.disk = disk
         host.vendor_id = vendor_id
         host.model_name = model_name
         host.cpu_core = cpu_core
         host.product = product
         host.Manufacturer = Manufacturer
         host.sn = sn
         host.save()
         return  HttpResponse( 'ok' )
     else :
         return  HttpResponse( 'no data' )
 
 
def getjson(req):
     hg = HostGroup.objects.all()
     d = []
     for  in  hg:
         ret = { 'groupname' :g.groupname, 'members' :[]}
         for  in  g.members.all():
             ret_h = { 'hostname' :h. hostname , 'ip' :h.ip}
             ret[ 'members' ].append(ret_h)
         d.append(ret)
     return  HttpResponse(json.dumps(d))
 
#添加如下行
def gettxt(req):
     str =  ''
     hg = HostGroup.objects.all()
     for  in  hg:
         for  in  g.members.all():
             str += g.groupname + h. hostname  ' '  + h.ip +  ' '  '\n'
     return  HttpResponse(str)

2.3 浏览器访问

wKiom1T1dYrwvv9iAAGeTnWCGbU386.jpg

2.4 命令行访问

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~] # curl http://192.168.1.210/hostinfo/gettxt
nginxnginx_master.com 192.168.1.234 
nginxnginx_slave.com 192.168.1.201 
mongodbmongodb.com 192.168.1.121 
dbmysql_master.com 192.168.1.105 
dbmysql_slave.com 192.168.1.106 
tomcattomcat_node1.com 192.168.1.109 
tomcattomcat_node2.com 192.168.1.110 
tomcattomcat_node3.com 192.168.1.111 
tomcattomcat_node4.com 192.168.1.112 
memcachedmemory.com 192.168.1.120






     本文转自zys467754239 51CTO博客,原文链接:http://blog.51cto.com/467754239/1616904,如需转载请自行联系原作者


相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
1月前
|
数据采集 JSON API
如何实现高效率超简洁的实时数据采集?——Python实战电商数据采集API接口
你是否曾为获取重要数据而感到困扰?是否因为数据封锁而无法获取所需信息?是否因为数据格式混乱而头疼?现在,所有这些问题都可以迎刃而解。让我为大家介绍一款强大的数据采集API接口。
|
1月前
|
JSON API 数据库
解释如何在 Python 中实现 Web 服务(RESTful API)。
解释如何在 Python 中实现 Web 服务(RESTful API)。
26 0
|
8天前
|
JSON API 数据格式
python的request库如何拿到json的返回值
python的request库如何拿到json的返回值
10 0
|
10天前
|
存储 JSON NoSQL
MongoDB的文档存储格式BSON和JSON的区别
MongoDB的文档存储格式BSON和JSON的区别
|
12天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
28 0
|
16天前
|
存储 JSON 数据挖掘
python逐行读取txt文本中的json数据,并进行处理
Python代码示例演示了如何读取txt文件中的JSON数据并处理。首先,逐行打开文件,然后使用`json.loads()`解析每一行。接着,处理JSON数据,如打印特定字段`name`。异常处理包括捕获`JSONDecodeError`和`KeyError`,确保数据有效性和字段完整性。将`data.txt`替换为实际文件路径运行示例。
14 2
|
21天前
|
XML JSON JavaScript
使用JSON和XML:数据交换格式在Java Web开发中的应用
【4月更文挑战第3天】本文比较了JSON和XML在Java Web开发中的应用。JSON是一种轻量级、易读的数据交换格式,适合快速解析和节省空间,常用于API和Web服务。XML则提供更强的灵活性和数据描述能力,适合复杂数据结构。Java有Jackson和Gson等库处理JSON,JAXB和DOM/SAX处理XML。选择格式需根据应用场景和需求。
|
1月前
|
JSON API 数据格式
Python中使用API(四)
Python中使用API(四)
20 0
|
1月前
|
JSON API 数据格式
Python中使用API(三)
Python中使用API(三)
18 0
|
1月前
|
JSON API 数据格式
Python中使用API(二)
Python中使用API(二)
18 0