脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - 利用python写api接口实战指南

利用python写api接口实战指南

2022-12-28 14:52说笑谈古松 Python

api接口在我们开发中的重要性相信大家都这篇文章主要给大家介绍了关于利用python写api接口实战的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

一、操作步骤

  1. 导入:import flask,json
  2. 实例化:api = flask.Flask(name)
  3. 定义接口访问路径及访问方式:@api.route(’/index’,methods=[‘get/post/PUT/DELETE’])
  4. 定义函数,注意需与路径的名称一致,设置返回类型并支持中文:def index(): return json.dumps(ren,ensure_ascii=False)
  5. 三种格式入参访问接口:
    5.1 url格式入参:flask.request.args.get(‘id’)
    5.2 form-data格式入参:pwd = flask.request.values.get(‘pwd’)
    5.3 josn格式入参:pwd = flask.request.json.get(‘pwd’)
  6. 启动服务:api.run(port=8888,debug=True,host=‘127.0.0.1’),开启服务之后,就可以通过ip+端口+路径+入参访问接口

二、源码举例

?
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
#!/usr/bin/python3
# encoding:utf-8
import flask,json
# 实例化api,把当前这个python文件当作一个服务,__name__代表当前这个python文件
api = flask.Flask(__name__)
 
# 'index'是接口路径,methods不写,默认get请求    
@api.route('/index',methods=['get'])
# get方式访问
def index():
  ren = {'msg':'成功访问首页','msg_code':200}
  #json.dumps 序列化时对中文默认使用的ascii编码.想输出中文需要指定ensure_ascii=False
  return json.dumps(ren,ensure_ascii=False)
 
#post入参访问方式一:url格式参数
@api.route('/article',methods=['post'])
def article():
  #url格式参数?id=12589&name='lishi'
  id = flask.request.args.get('id')
   
  if id:
    if id == '12589':
      ren = {'msg':'成功访问文章','msg_code':200}
    else:
      ren = {'msg':'找不到文章','msg_code':400}
  else:
    ren = {'msg':'请输入文章id参数','msg_code':-1}
  return json.dumps(ren,ensure_ascii=False)
 
#post入参访问方式二:from-data(k-v)格式参数
@api.route('/login',methods=['post'])
def login():
  #from-data格式参数
  usrname = flask.request.values.get('usrname')
  pwd = flask.request.values.get('pwd')
   
  if usrname and pwd:
    if usrname =='test' and pwd =='123456':
      ren = {'msg':'登录成功','msg_code':200}
    else:
      ren = {'msg':'用户名或密码错误','msg_code':-1}
  else:
    ren = {'msg':'用户名或密码为空','msg_code':1001}
  return json.dumps(ren,ensure_ascii=False)
 
#post入参访问方式二:josn格式参数 
@api.route('/loginjosn',methods=['post'])
def loginjosn():
  #from-data格式参数
  usrname = flask.request.json.get('usrname')
  pwd = flask.request.json.get('pwd')
   
  if usrname and pwd:
    if usrname =='test' and pwd =='123456':
      ren = {'msg':'登录成功','msg_code':200}
    else:
      ren = {'msg':'用户名或密码错误','msg_code':-1}
  else:
    ren = {'msg':'用户名或密码为空','msg_code':1001}
  return json.dumps(ren,ensure_ascii=False)
 
if __name__ == '__main__':
  api.run(port=8888,debug=True,host='127.0.0.1') # 启动服务
  # debug=True,改了代码后,不用重启,它会自动重启
  # 'host='127.0.0.1'别IP访问地址

运行结果:

 * Serving Flask app 'monitor' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 991-833-116
 * Running on http://127.0.0.1:8888/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Jan/2022 14:05:53] "POST /login?usrname=test&pwd=123456 HTTP/1.1" 200 -
127.0.0.1 - - [16/Jan/2022 14:08:34] "GET /index HTTP/1.1" 200 -

请求方式:

使用postman测试接口是否可行

如:

url:127.0.0.1:8888/login

参数:usrname=test;pwd=123456

利用python写api接口实战指南

获取请求参数的几种方法:

?
1
2
3
flask.request.form.get("key", type=str, default=None) 获取表单数据,
flask.request.args.get("key") 获取get请求参数,
flask.request.values.get("key") 获取所有参数。

总结

到此这篇关于利用python写api接口实战指南的文章就介绍到这了,更多相关python写api接口内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_40468470/article/details/122522758

延伸 · 阅读

精彩推荐
  • Pythonpycharm软件实现设置自动保存操作

    pycharm软件实现设置自动保存操作

    这篇文章主要介绍了pycharm软件实现设置自动保存操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    xiaofei_sun8532020-06-09
  • Pythonpython利用opencv实现颜色检测

    python利用opencv实现颜色检测

    这篇文章主要为大家详细介绍了python利用opencv实现颜色检测,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    pengyuan10112452021-09-08
  • Python使用matplotlib中scatter方法画散点图

    使用matplotlib中scatter方法画散点图

    这篇文章主要为大家详细介绍了使用matplotlib中scatter方法画散点图,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    bitcarmanlee9212021-06-07
  • Python如何利用Python和OpenCV对图像进行加水印详解

    如何利用Python和OpenCV对图像进行加水印详解

    Python使用opencv是因为觉得它足够强大,很多图像处理这块都是用的它,最近就用opencv添加个水印,这篇文章主要给大家介绍了关于如何利用Python和OpenCV对图像进...

    海拥9182022-02-14
  • Pythonpyqt5使用按钮进行界面的跳转方法

    pyqt5使用按钮进行界面的跳转方法

    今天小编就为大家分享一篇pyqt5使用按钮进行界面的跳转方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    pursuit_zhangyu14422021-07-16
  • Pythonpython 基础教程之Map使用方法

    python 基础教程之Map使用方法

    这篇文章主要介绍了python 基础教程之Map使用方法的相关资料,这里附有简单使用实例,需要的朋友可以参考下...

    Python教程网4082020-09-18
  • PythonPython使用mmap实现内存映射文件操作

    Python使用mmap实现内存映射文件操作

    内存映射通常可以提高I/O的性能,本文主要介绍了Python使用mmap实现内存映射文件操作,分享给大家,感兴趣的可以了解一下...

    一天一篇Python库10422021-11-25
  • PythonPython Flask基础到登录功能的实现代码

    Python Flask基础到登录功能的实现代码

    这篇文章主要介绍了Python Flask基础到登录功能的实现代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考...

    Scr1pt_kid8882021-10-28