• 自动化学习-Day10


    Flask

    #index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>我的网站</title>
    </head>
    <body>
    <div><input type = 'text' placeholder="请输入你的账号" name="username"></div>
    <div><input type = 'text' placeholder="请输入你的密码" name="password"></div>
    <input type="button" value="提交">
    <div style="  90px;height: 100px; background-color: blue">
    
    </div>
    <a href="www.baidu.com">百度</a>
    </body>
    </html>
    import flask
    import json
    import tools
    
    server = flask.Flask(__name__)
    import datetime
    
    @server.route('/api/get_time')
    def get_time():
        now = str(datetime.datetime.now())
        return "现在的时间是:%s"%now
    
    @server.route('/api/say_hello')
    def say_hell():
        return 'hello'
    
    @server.route('/index')
    def my_page():
        f = open('index.html',encoding='utf-8')
        res = f.read()
        f.close()
        return res
    
    @server.route('/login',methods=['post','get'])
    def login():
        #username
        #password
        username =flask.request.values.get('username')
        password = flask.request.values.get('password')
        if username and password:
            sql = "select username,passowrd from app_myuser where username = '%s' and password = '%s';" %(username,password)
            result = tools.my_db(sql) #执行sql
            if result:
                res =  {'error_code':1000,'msg':'登陆成功'}
            #return json.dumps(res,ensure_ascii=False,indent=4)
            #sql=''
            else:
                res = {"error_code":3001,"msg":'账号/密码错误'}
        else:
            res = {'error_code':3000,"msg":"必填参数未填,请查看接口文档"}
            #return json.dumps(res,ensure_ascii=False,indent=4)
        return json.dumps(res, ensure_ascii=False, indent=4)
    
    @server.route('/add_student',methods=['post'])
    def add_student():
        params = flask.request.json #入参是字典的时候用它
        if params:
            name = params.get('name')
            sex = params.get('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
            #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 gold.isdigit() and not tools.check_float():
                    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, "meg": "必填参数未填"}
            return json.dumps(res,ensure_ascii=False)
        else:
            res = {"error_code":3302,'msg':'入参必须是json'}
        return json.dumps(res,ensure_ascii=False)
    
    @server.route('/upload',methods=['post'])
    def file_upload():
        f = flask.request.files.get('wj',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(port=8888,debug=True)
    #host写成0.0.0.0的话,那么在一个局域网里面的人都可以访问了
    #debug=True 加上它 就不需要重启了,改完代码他会自动重启

    #start.py
    import os,sys
    res = os.path.abspath(__file__) #取当前这个文件绝对路径
    base_path = os.path.dirname(os.path.dirname(res)) #取两次父目录
    sys.path.insert(0,base_path) #加入环境变量,跨平台中,可以将包放到随便一个目录就能运行
    #import sys
    #sys.path.insert(0,r'C:Users
    ongpPycharmProjectsjnzDay10my_api')
    
    from lib.service import server
    from lib import get_time,main
    from conf.setting import server_info #需要将运行的文件先导入并运行,不然会报错
    server.run(**server) #启动服务
    #setting.py
    #mysql 配置信息
    my_info = {
        'host':'118.24.3.20',
        'port':'3306',
        'user':'jxz',
        'password':'123456',
        'charset':'utf08',
        'autocommit':True
    }
    
    server_info = {
        'HOST':'0.0.0.0',
        'PORT':5000,
        'debug':True
    }
    #get_table_data.py
    from lib.service import  server
    from lib.tools import my_db
    import flask
    import json
    def get_table_data():
        #获取某个表中的数据
        table_name = flask.request.values.get('table_name')
        sql = 'select * from %s;'%table_name
        res = my_db(sql)
        return json.dumps(res,ensure_ascii=False)
    #get_time.py
    from lib.service import server
    import datetime
    
    @server.route('/get_time')
    def get_time():
        now = str(datetime.datetime.now())
        return "现在的时间是:%s"%now
    #index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>我的网站</title>
    </head>
    <body>
    <div><input type = 'text' placeholder="请输入你的账号" name="username"></div>
    <div><input type = 'text' placeholder="请输入你的密码" name="password"></div>
    <input type="button" value="提交">
    <div style="  90px;height: 100px; background-color: blue">
    
    </div>
    <a href="www.baidu.com">百度</a>
    </body>
    </html>
    #main.py
    import flask
    import json
    from lib import tools
    import datetime
    from lib.service import server
    
    
    
    @server.route('/say_hello')
    def say_hell():
        return 'hello'
    
    @server.route('/index')
    def my_page():
        f = open('index.html',encoding='utf-8')
        res = f.read()
        f.close()
        return res
    @server.route('/login',methods=['post','get'])
    def login():
        #username
        #password
        username =flask.request.values.get('username')
        password = flask.request.values.get('password')
        if username and password:
            sql = "select username,passowrd from app_myuser where username = '%s' and password = '%s';" %(username,password)
            result = tools.my_db(sql) #执行sql
            if result:
                res =  {'error_code':1000,'msg':'登陆成功'}
            #return json.dumps(res,ensure_ascii=False,indent=4)
            #sql=''
            else:
                res = {"error_code":3001,"msg":'账号/密码错误'}
        else:
            res = {'error_code':3000,"msg":"必填参数未填,请查看接口文档"}
            #return json.dumps(res,ensure_ascii=False,indent=4)
        return json.dumps(res, ensure_ascii=False, indent=4)
    
    @server.route('/add_student',methods=['post'])
    def add_student():
        params = flask.request.json #入参是字典的时候用它
        if params:
            name = params.get('name')
            sex = params.get('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
            #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 gold.isdigit() and not tools.check_float():
                    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, "meg": "必填参数未填"}
            return json.dumps(res,ensure_ascii=False)
        else:
            res = {"error_code":3302,'msg':'入参必须是json'}
        return json.dumps(res,ensure_ascii=False)
    
    @server.route('/upload',methods=['post'])
    def file_upload():
        f = flask.request.files.get('wj',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)
    #service.py
    import flask
    server = flask.Flask(__name__) #把当前这个python文件当作一个服务
    #tools.py
    import pymysql
    from conf.setting import my_info
    def my_db(sql):
        conn = pymysql.connect(**my_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

    网络请求

    from urllib.request import urlopen
    from urllib.parse import urlencode
    url = "http://www.baidu.com"
    
    res = urlopen(url).read() #get请求
    f = open('a.html','w',encoding='utf-8')
    f.write(res.decode())
    from urllib.request import urlopen
    from urllib.parse import urlencode
    
    url = 'http://api.nnzhp.cn/api/user/login'
    data = {"username":'wrp123',"passwd":'Wrp123'}
    data = urlencode(data) #通过urlencode变成username=wrp123&passwd=Wrp123
    res = urlopen(url,data.encode()).read() #将data变成byte类型
    
    print(res.decode()) #转为字符串类型
    
    import json
    d = json.loads(res.decode())
    print(d.get('login_info').get('sign'))

    使用requests模块

    #GET请求
    import
    requests import json url = "http://www.baidu.com" res = requests.get(url,params={"K":"V","K1":"V1"}, cookies={"a":"b"},headers={"a":"b"}) #如果cookies中信息多,不需要cookies参数,将cookies变成字符串,headers={"cookies":str} print(res.text) #返回字符串
    #POST请求
    import
    requests import json url = 'http://api.nnzhp.cn/api/user/login' res1 = requests.post(url,data = {"username":'wrp123',"passwd":'Wrp123'}) print(res1.json()) #返回的是一个字典 print(res1.text) #json
    #下载二进制内容
    import
    requests import json mp3_url ='http://upuwmp3.changba.com/userdata/userwork/943/1205649943.mp3' res = requests.get(mp3_url) mp3 = res.content #返回二进制的内容 f = open('g.mp3','wb') f.write(mp3) f.close()
    #上传
    import requests
    import json
    
    url = 'http://api.nnzhp.cn/api/file/file_upload'
    res = requests.post(url,files={'file':open('g.mp3','rb')}) #上传文件
    print(res.json())
    #BODY为JSON
    import requests
    import json
    
    url = 'http://api.nnzhp.cn/api/user/add_stu'
    
    data = {"phone":"13266565555","grade":"三年级","name":"小李"}
    res = requests.post(url,json=data)
    print(res.json())
  • 相关阅读:
    java 异常java.lang.UnsupportedOperationException
    转载RabbitMQ入门(6)--远程调用
    转载RabbitMQ入门(5)--主题
    转载RabbitMQ入门(4)--路由
    转载RabbitMQ入门(3)--发布和订阅
    转载RabbitMQ入门(2)--工作队列
    转载RabbitMQ入门(1)--介绍
    转载:浅析Java中的final关键字
    Java NIO Channel通道
    Java NIO Buffer缓冲区
  • 原文地址:https://www.cnblogs.com/rongpeng/p/12050754.html
Copyright © 2020-2023  润新知