python开发接口

3 篇文章 1 订阅
2 篇文章 0 订阅

目录:第一部分flask简介,第二部分简单开发get和post接口例子

一、flask开发接口简介

flask是一个python编写的轻量级框架,可以使用它实现一个网站或者web服务。此外,python 运用Django 开发后台接口。本文就用flask来开发一个接口。

flask需要先安装再引用。pip install flask

用flask开发接口的流程为:

1.1、定义一个server

server=flask.Flask(__name__) #__name__代表当前的python文件。把当前的python文件当做一个服务启动

1.2、然后定义接口函数,一般函数和接口函数的区别在于,定义为接口的函数上方要特别加上:

@server.route('/index',methods=['get','post']) #第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get

@server.route('/index',methods=['get','post'])#第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get
def index():
    res={'msg':'这是我开发的第一个借口','msg_code':0}
    return json.dumps(res,ensure_ascii=False)

1.3、让server执行起来

server.run(port=5001,debug=True,host='0.0.0.0')

#port可自定义填写,默认是5000。不要与机器上已占用的port冲突。
#debug=True,在代码进行修改后,程序会自动重新加载,不用再次运行。也就是运行一次即可,即使改动代码,也不需要重启服务
#host本地ip地址,写0.0.0.0,可以让其他人直接访问本机的ip。
#最终这个接口的访问地址就是  http://127.0.0.1/index  ,get方法或者post方法都可。返回数据是json格式res内容

二、闲话少说,下面就给出例子和测试结果


2.1、编写server_new.py,代码如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import subprocess
import flask,json
'''
CREATE TABLE IF NOT EXISTS `my_user`(
   `auto_id` INT UNSIGNED AUTO_INCREMENT,
   `username` VARCHAR(50) NOT NULL,
   `passwd` VARCHAR(40) NOT NULL,
   `is_admin` INT,
   PRIMARY KEY ( `auto_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
'''
server=flask.Flask(__name__) #__name__代表当前的python文件,把当前这个python文件,当成一个服务
def excute_command(username,pwd):
    if username=='yyz':
        return "excute_command username=yyz pwd=%s" % pwd
    else:
        return "excute_command username=%s pwd=%s" % (username,pwd)
def my_db(sql):
    import pymysql
    coon = pymysql.connect(host='127.0.0.1',user='root',passwd='y44444444',port=3306,db='test_db',charset='utf8')
    cur = coon.cursor()
    cur.execute(sql)
    if sql.strip()[:6].upper() == 'SELECT': #判断sql语句是否select开头
        res = cur.fetchall()  #获取到sql语句所有的返回结果
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res

@server.route('/index',methods=['get'])  #装饰器  ip:5000/index?xxx
def index():
    res={'msg':'这个是我开发的第一个接口','msg_code':0} #这个是字典,接口返回的是json,所以需要引入json,并且返回进行json.dumps
    return json.dumps(res,ensure_ascii=False) #返回结果是unicode,需要增加ensure_ascii=False
@server.route('/reg',methods=['post'])
def reg():
    try:
        date = flask.request.values.get('date')
        print "date-date",date
        course_id = int(flask.request.values.get('course_id'))
        chapter_id = int(flask.request.values.get('chapter_id'))
        subprocess.Popen("bash ./main.sh '" + str(date) + "'", shell=True)
        res = {'msg': str(date) + '执行shell成功!', 'msg_code': 0}
    except:
        res = {'msg':'参数非法,请检查接口文档!','msg_code':1001}

    return json.dumps(res,ensure_ascii=False)
if __name__ == '__main__':
    server.run(port=5001,debug=True, host='0.0.0.0')   #端口号要是不指定,默认为5000.debug=True,改了代码之后不用重启,会自动重启一次。后面增加host='0.0.0.0',别人可以访问

接口访问中,经常会需要输入参数。那么如果要接受传入的参数,则可用以下方法:

  username=flask.request.values.get('username')

2.2、编写main.sh脚本,这里面可以进行任何种类的开发:

#!/usr/bin/bash

PYTHON="/usr/bin/python"

 

function handle_function()
{
    $PYTHON ./new_mysql.py $1
    if [ $? -ne 0 ]; then
        return 0
    fi

    return 1
}

 

function main()
{
    #检查参数
    if [ $# -eq 0 ]; then
        local start_date=`date -d last-day +%Y-%m-%d`
        local end_date=`date -d "$start_date +1 day" +%Y-%m-%d`
        #local end_date=$start_date
    elif [ $# -eq 1 ]; then
        local start_date=$1
        local end_date=`date -d "$start_date +1 day" +%Y-%m-%d`
        #local end_date=$start_date
    elif [ $# -eq 2 ]; then
        local start_date=$1
        local end_date=$2
    else
        echo "Usage: bash ./main.sh 2017-05-02 2017-05-03"
        exit
    fi
    echo "success--yyz-- start_date ${start_date}"
    echo "success--yyz-- end_date ${end_date}"

    for((i=0;;i++)); do
        date_str=`date -d "$start_date +$i day" +%Y-%m-%d`
        date_str_s=`date -d "${date_str}" +%s`
        end_date_s=`date -d "${end_date}" +%s`

        echo "success--yyz-- date_str ${date_str}"
        echo "success--yyz-- end_date_s ${end_date_s}"

       if handle_function $date_str
        then
            echo "handle success"
        else
            echo "handle failed"
        fi

        if [ $date_str_s -ge $end_date_s ]; then
                break
        fi
        done

    return 0
}
main $@

2.3、运行和测试:

之后需要在本地配置绑定host,这样便于记忆,

     vi /etc/hosts

   xxx.xxx.xxx.168 yyz.edu.com # flask interface test

运行接口服务器:
 $python server_new.py

 * Serving Flask app "server_new" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5001/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 264-088-175


测试一:在浏览器输入以下命令     http://yyz.edu.com:5001/index   ,可以看到如下界面:

 

测试二、由于浏览器无法模拟post请求,所以才有postman等模拟工具
http://yyz.edu.com:5001/reg?date=2018-12-28&course_id=123456&chapter_id=99999

 

此外,curl命令是一个利用URL规则在命令行下工作的文件传输工具。它支持文件的上传和下载。curl支持包括HTTP、HTTPS、ftp等众多协议,还支持POST、cookies、认证、从指定偏移处下载部分文件、用户代理字符串、限速、文件大小、进度条等特征。

在进行web后台程序开发测试过程中,常常会需要发送url进行测试,使用curl可以方便地模拟出符合需求的url命令

测试三、使用curl命令行测试get请求

$ curl http://yyz.edu.com:5001/index
{"msg": "这个是我开发的第一个接口", "msg_code": 0}

测试四、使用curl发送POST请求:

$ curl -d 'date=2018-12-28&course_id=123456&chapter_id=99999' http://yyz.edu.com:5001/reg
{"msg": "2018-12-28执行shell成功!", "msg_code": 0}

这种方法是参数直接在header里面的,如需将输出指定到文件可以通过重定向进行操作.
curl -H "Content-Type:application/json" -X POST -d 'json data' URL

参考:

python简单开发接口:https://www.cnblogs.com/xiaojing2017/p/9041115.html

python:接口开发 https://www.cnblogs.com/bendouyao/p/9019955.html

curl 模拟 GET\POST 请求: https://blog.csdn.net/fungleo/article/details/80703365

安装setuptools和pip过程 :https://blog.csdn.net/xingxingboke/article/details/78275757

Linux源码安装步骤:https://www.cnblogs.com/benwu/articles/8436209.html

Python框架 Flask 项目实战教程https://www.cnblogs.com/jsben/p/4909964.html

  • 7
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值