标签:run 获取 json 客户 rip sele str debug pymysql
import flask,pymysql
import hashlib
import json
server = flask.Flask(__name__) #把当前这个python文件当做一个服务
def my_db(sql,port=3306,charset=‘utf8‘):
ip, user, passwd, db = ‘10.24.31.40‘,‘jz‘,‘123456‘,‘jxz‘
coon = pymysql.connect(host=ip,user=user,
password=passwd,db=db,
port=port,charset=charset,autocommit=True)
cur = coon.cursor()
sql=sql.strip()
cur.execute(sql)
sql_start = sql[:6].lower()#取sql的开头,转成小写
if sql_start.startswith(‘select‘) or sql_start.startswith(‘show‘):
data = cur.fetchall()
else:
data = ‘ok‘
cur.close()
coon.close()
return data
def my_md5(s):
m = hashlib.md5(s.encode())
return m.hexdigest()
@server.route(‘/login‘,methods=[‘get‘,‘post‘])
def taotao():
username = flask.request.values.get(‘username‘) #是从客户端发过来的数据
pwd = flask.request.values.get(‘password‘)
flask.request.cookies.get(‘xxx‘) #获取cookie
flask.request.headers.get(‘xxxx‘) #获取headers
json_data = flask.request.json.get(‘username‘) #这个获取入参是json类型的
if username==‘nhy‘ and pwd==‘123456‘:
res = {‘code‘:1000,‘msg‘:‘登录成功‘,‘sign‘:‘sdfsdf23vsrqsdf‘}
else:
res = {‘code‘:2000,‘msg‘:‘账号/密码错误‘}
return json.dumps(res,ensure_ascii=False)
@server.route(‘/register‘,methods=[‘post‘])
def reg():
username = flask.request.values.get("username")
passwd = flask.request.values.get("passwd")
cpasswd = flask.request.values.get("cpasswd")
if username and passwd and cpasswd:
sql1 = ‘select * from nhy where name="%s";‘%username
sql_res = my_db(sql1)
if sql_res:
res = {‘code‘:2001,‘msg‘:‘该用户已经被注册‘}
else:
if passwd==cpasswd:#
md5_pwd = my_md5(passwd)
sql2 = ‘insert into nhy (name,pwd) value ("%s","%s");‘%(username,md5_pwd)
my_db(sql2)
res = {‘code‘:1000,‘msg‘:‘注册成功‘}
else:
res = {‘code‘:2003,‘msg‘:‘两次输入的密码不一致‘}
else:
res = {‘code‘:2002,‘msg‘:‘必填参数未填,请查看接口文档!‘}
return json.dumps(res,ensure_ascii=False)
server.run(port=8989,debug=True) #启动服务
接下来,通过postman去测试所开发的接口。
标签:run 获取 json 客户 rip sele str debug pymysql
原文地址:https://www.cnblogs.com/URNOTBENBEN/p/9343965.html