• 04 DIYweb框架


    编辑本博客

    wsgiref模块

    按http请求协议解析数据

    按http响应协议封装数据

    方案一:直接用if...else...判断

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    #@Time     : 2018/6/26 14:48
    #@Author   :HuangYa
    #@Email    :huangmingya66@163.com
    #@File     :wsgi_server
    #@Software :PyCharm
    
    from wsgiref.simple_server import make_server
    def application(environ,start_response):
        #environ:按http协议解析数据
        # start_response:按http协议组装数据
        start_response("200 OK",[])
        #当前请求路径
        path=environ.get("PATH_INFO")
        # 根据请求路径来确定返回的内容
        print("PATH:",path)
        if path=="/index":
            with open("index.html","rb") as f:
                data=f.read()
            return [data]
        # 浏览器图标显示
        if path=="/favicon.ico":
            with open("favicon.ico","rb") as f:
                data=f.read()
            return [data]
        elif path=="/login":
            with open("login.html","rb") as f:
                data=f.read()
            return [data]
        else:
            return ["<h1>Hi,WSGIref</hq>".encode("utf8")]
    httped=make_server("",8091,application)
    httped.serve_forever()
    View Code

    方案二:路由分发实现解耦

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    #@Time     : 2018/6/26 14:48
    #@Author   :HuangYa
    #@Email    :huangmingya66@163.com
    #@File     :wsgi_server
    #@Software :PyCharm
    
    from wsgiref.simple_server import make_server
    def login(environ):
        with open("login.html", "rb") as f:
            data=f.read()
        return data
    def index(environ):
        with open("index.html", "rb") as f:
            data=f.read()
        return data
    def favi(environ):
        with open("favicon.ico", "rb") as f:
            data=f.read()
        return data
    def register(environ):
        return "register page!".encode("utf8")
    url_patterns=[("/login",login),
                  ("/index",index),
                  ("/register",register),
                  ("/favicon.ico",favi)
                  ]
    def application(environ,start_response):
        # 当前请求路径
        start_response("200 OK",[])
        path=environ.get("PATH_INFO")
        print(path)
        func=None
        for item in url_patterns:
            if path==item[0]:
                func=item[1]
        if not func:
            return ["<h1>error</h1>".encode("utf8")]
        else:
            return [func(environ)]
    httped=make_server("",8091,application)
    httped.serve_forever()
    View Code

    方案三:将html,urls,views单独用独立文件

    框架之数据库操作

    main.py:启动文件,封装socket

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    #@Time     : 2018/6/26 14:48
    #@Author   :HuangYa
    #@Email    :huangmingya66@163.com
    #@File     :wsgi_server
    #@Software :PyCharm
    
    from wsgiref.simple_server import make_server
    from urls import url_patterns
    def application(environ,start_response):
        # 当前请求路径
        start_response("200 OK",[])
        path=environ.get("PATH_INFO")
        print(path)
        func=None
        for item in url_patterns:
            if path==item[0]:
                func=item[1]
        if not func:
            return ["<h1>error</h1>".encode("utf8")]
        else:
            return [func(environ)]
    httped=make_server("",8091,application)
    httped.serve_forever()
    View Code

    views.py:函数视图,固定一个形式参数,即视图函数

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    #@Time     : 2018/6/26 15:59
    #@Author   :HuangYa
    #@Email    :huangmingya66@163.com
    #@File     :views
    #@Software :PyCharm
    # from wsgiref.simple_server import parse_qs
    import pymysql
    def login(environ):
        print(environ)
        with open("templates/login.html", "rb") as f:
            data=f.read()
        return data
    def index(environ):
        with open("templates/index.html", "rb") as f:
            data=f.read()
        return data
    def favi(environ):
        with open("templates/favicon.ico", "rb") as f:
            data=f.read()
        return data
    def register(environ):
        return "register page!".encode("utf8")
    def auth(environ):
        try:
            request_body_size=int(environ.get("CONTENT_LENGTH",0))
        except (ValueError):
            request_body_size=0
        request_body=environ["wsgi.input"].read(request_body_size)
        data=parse_qs(request_body)
        user=data.get(b"username")[0].decode("utf8")
        pwd = data.get(b"pwd")[0].decode("utf8")
        conn = pymysql.connect("127.0.0.1", port=3306, user="root", passwd="123.com", db="web", charset="utf8")
        cursor=conn.cursor()
        sql="select * from userinfo where name='%s' and password='%s'"
        cursor.execute(sql,(user,pwd))
        if cursor.fetchall():
            return "login success.".encode("utf8")
        else:
            return "user or pwd is wrong.".encode("utf8")
    def timer(environ):
        import datetime
        now=datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")
        return now.encode("utf8")
    View Code

    urls.py:视图与函数映射关系,即url控制器

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    #@Time     : 2018/6/26 15:59
    #@Author   :HuangYa
    #@Email    :huangmingya66@163.com
    #@File     :urls
    #@Software :PyCharm
    from views import *
    url_patterns=[("/login",login),
                  ("/index",index),
                  ("/register",register),
                  ("/favicon.ico",favi),
                  ("/timer",timer),
                  ("/auth",auth),
                  ]
    View Code

    templates文件夹,存放html文件,即模板

    models.py:项目启动前,在数据库中创建表结构,即与数据库相关

    import pymysql
    conn=pymysql.connect("127.0.0.1",port=3306,user="root",passwd="123.com",db="web",charset="utf8")
    cur=conn.cursor()
    sql="""
    create table userinfo(
    id int PRIMARY KEY auto_increment,
    name VARCHAR(32),
    password VARCHAR(32))
    """
    cur.execute(sql)
    conn.commit()
    cur.close()
    conn.close()
    View Code
  • 相关阅读:
    Redis使用cmd进入执行命令界面
    Mime 类型列表
    BootstrapBlazor 智能生成神器(一)AutoGenerateColumnAttribute 特性介绍
    BootstrapBlazorValidateForm 表单验证组件
    RabbitMQ Windows 安装、默认设置及命令
    .Net Core 可为Null的类型
    BootstrapBlazor EditorForm 表单组件(一)
    docker 命令实录2
    win 10家庭版没有docker如何操作
    docker 记录
  • 原文地址:https://www.cnblogs.com/yaya625202/p/9228946.html
Copyright © 2020-2023  润新知