Python-利用flask模块创建web接口

一、创建一个实现登录的接口

import flask
from flask import request  #获取参数
# import json #post请求传入json对象时,通过json获取参数

def conn_mysql(sql):
    import pymysql
    conn = pymysql.connect(host='127.0.0.1 ', user='jessica', password='123456', db='sql_python', charset='utf8')
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cur.execute(sql)
    res = cur.fetchone()
    print(res)
    conn.commit()
    cur.close()
    conn.close()
    return res

server = flask.Flask(__name__) #创建一个flask对象


@server.route('/login', methods=['get','post'])
def login():
    username = request.values.get('username') #获取参数
    password = request.values.get('password')
    # username = request.json.get('username') #入参为json类型时,必须用.json方式获取
    # password = request.json.get('password')
    if username and password:
        sql = 'select * from user where username="%s"'%username
        data = conn_mysql(sql)
        if data['password'] == password:
            return '{"msg":"登录成功"}'
        else:
            return '{"msg":"账号密码错误"}'
    else:
        return '{"msg":"请输入用户名密码"}'

server.run(port=8000,debug=True) #debug设置为True,修改接口信息后直接刷新接口即可;添加参数host='0.0.0.0'允许同一局域网内访问

 

二、在浏览器输入:http://127.0.0.1:8000/login?username=xxx&password=123456,查看结果

posted on 2017-11-17 23:23  乔~惜  阅读(4667)  评论(0编辑  收藏  举报