DIY a Web framework

I. Introduction

Second, the implementation process and the frame structure

Third, the summary

 

I. Introduction

  When we learned about the Web and Web application framework, as well as the principle of HTTP protocol, we can do it yourself DIY a simple WEB framework to deepen their understanding of Web frameworks, and test the waters for the upcoming learning Django road.

 

Second, the implementation process and the frame structure

  SUMMARY 1. The frame structure shown below

  Our DIY Web framework in the order of the boot, so roughly divided into several parts, which are models.py, manage.py, urls.py, views.py, templates (html file) five sections, here we are carried out to achieve these five sections, finally, running usability testing, validation frame.

  2. implementation process

  (1) models.py - database-related, before we started the project, using the table structure models.py created in the database, note that only run once.

#!/usr/bin/env python3
#!-*- coding:utf-8-*-
# write by cc

import pymysql

# 1 establishes a connection 
Conn = pymysql.connect (
    host = 'localhost',
    port = 3306,
    user = 'cc1',
    password = 'cc111',
    db = 'db1',
    charset = 'utf8'
)

# 2. Get the cursor 
Cursor = conn.cursor ()
 # Cursor = conn.cursor (pymysql.cursor.DictCursor) # cursor type is provided dictionaries

# 3 execute sql statement 
sql = " Create Table Users (int ID, User char (12 is), char pwd (12 is)) " 
rows = the cursor.execute (sql)
 Print (rows) # prints the number of records affected

# 4. Submit (must be submitted in order to achieve operation) 
conn.commit ()

# 5. Close the cursor and connected 
cursor.close ()
conn.close()

  (2) manage.py - the project's startup files

from wsgiref.simple_server import make_server

from urls import url_list

def application(environ,start_response):
    path = environ.get("PATH_INFO")
    print(path)
    start_response("200 OK",[('Content-Type','text/html')])

    func = None
    for item in url_list:
        if path == item[0]:
            func = item[1]
            break
    if func:
        return [func(environ)]
    else:
        return [b'404 Not found']

if __name__ == '__main__':
    httpd = make_server("",8080,application) # 指定端口
    print('Serving HTTP on port 8080...')
    httpd.serve_forever () # open listening

  (. 3) the urls.py - mapping relationship url controller, and view function reflect the path

from app01.views import *

url_list = [
    ('/favcion.ico',fav),
    ('/index',index),
    ('/login',login),
    ('/reg',reg),
    ( ' / H ' , h),
    ('/auth',auth)
]

  (. 4) the views.py - a view function, in the form of a fixed reception parameters: environ

from urllib.parse import parse_qs
def fav(environ):
    with open('templates/favcion.ico','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 login(environ):
    with open('templates/login.html','rb') as f:
        data = f.read()
    return data

def reg(environ):
    with open('templates/reg.html','rb') as f:
        data = f.read()
    return data

def timer(environ):
    import datetime
    now = datetime.datetime.now().strftime("%y-%m-%d %X")
    return now.encode('utf-8')

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)

    # Parse the user input user name and password 
    User data.get = (B ' User ' ) [0] .decode ( ' UTF8 ' )
    pwd = data.get(b'pwd')[0].decode('utf8')


    # Connect to database 
    Import pymysql
    conn = pymysql.connect(host='localhost',port=3306,user='cc1',password='cc111',db='db1',charset='utf8')

    # Create a cursor 
    the Cursor = conn.cursor ()

    # Perform data query, insert and other operations 
    SQL = ' SELECT * WHERE Users from User pwd =% =% S and S '
    cursor.execute(sql,(user,pwd))

    # Verify whether the relevant record taken 
    IF cursor.fetchone ():
         Print (cursor.fetchone ())
        f = open('templates/backend.html','rb')
        data = f.read()
        data = data.decode('utf8')
        return data
    else:
        return b'user or password is wrong'

  (. 5) Templates - html file storage, when the path input by the user when the presence of the correct url controller, the user display the specified page.

  favcion.ico is a thumbnail, you can specify freely.

  index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>Hello world!</h1>
    <h2>Boys and girls!</h2>
    <h3><a href="https://www.cnblogs.com/schut"/>This is my web</a></h3>
    <img src="https://pic.cnblogs.com/avatar/1209144/20170813234607.png">
</body>
</html>

  login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <h1>Hello world!</h1>
    <h2>Boys and girls!</h2>
    <form action="http://127.0.0.1:8080/auth" method="post">
        姓名<input type="text" name="user">
        密码<input type="password" name="pwd">
        <input type="submit">
    </form>
</body>
</html>

  reg.html

<! DOCTYPE HTML > 
< HTML lang = "EN" > 
< head > 
    < Meta charset = "UTF-8" > 
    < title > Registration Page </ title > 
</ head > 
< body > 
    < h3 > Welcome to the registration page </ h3 > 
    < form Action = "" Method, = "POST" > 
        user name: < the INPUT of the type = "text" name="username"><br/>
        密 码:<input type="password" name="pwd"><br/>
        再次输入密码:<input type="password" name="pwd2"><br/>
        <input type="submit">
        <input type="reset">
    </form>
</body>
</html>

  backend.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h2>欢迎登录</h2>
</body>
</html>

 

Third, the summary

  Simple frame DIY above can be roughly divided into five parts, each assume different roles, are indispensable.

manage.py - startup file, package socket

1 urls.py - mapping between the path and the view function controller ------------- url
2 views.py - a view function, in the form of a fixed reception parameters: environ ------- view function
3 templates folder - html template file -------
4 models -, create a table structure in the database before the start of the project related database -----

 

  

 

Guess you like

Origin www.cnblogs.com/schut/p/11015577.html