day51_9_15_Django

One. pycharm accept the principle of pages of information.

  How to achieve acceptance in the back-end data browser, and parse out the useful information it?

  Use socket write-Fi, and then access ip + port number through a browser.

import socket


def index():
    with open('D:\pythontext\9_15\index.html','r') as f:
        date = f.read()
    return date

def dee():
    return 'dee'

dict1 = {'/index':index,'/dee':dee}
server = socket.socket()
server.bind(('127.0.0.1',8080))
server.listen(5)

while True:
    conn,addr = server.accept()
    date = conn.recv(1024)
    print(date)
    date = date.decode()
    date = date.split(' ')
    print(date)
    if date[1] in dict1:
        send2 = dict1.get(date[1])()
    else:
        send2 = '_'
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    conn.send(send2.encode())

  Print code can return information see:

b'GET /index HTTP/1.1\r\n
Host: 127.0.0.1:8080\r\n
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36\r\n
Sec-Fetch-Mode: navigate\r\n
Sec-Fetch-User: ?1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\r\n
Sec-Fetch-Site: none\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n\r\n
'

· Obtain the route to get back by the cutting method, and then executed by the statement to determine the appropriate return function, the return value is binary.

supplement:

  And the conversion between binary characters, in addition to using the function:

  encode()

  decode  ()

  , You can also use the following form:

data = str(data,encoding='utf-8')

data = bytes(data,encoding='utf-8')

two. Use wsgiref module.

  wsgiref incoming page speaking socket module encapsulation process, send and receive the package, so long as the programmer to write a view corresponding relationship between routing and data, to perform the corresponding function.

  

 

 

   Wherein the correspondence relationship is stored urls routing and views, and is stored in wsgiref1 run the code. views view function is stored.

  wsgiref start function:

if __name__ == '__main__':
    server = make_server('127.0.0.1',8080,run)
    server.serve_forever()

  Wherein the make_server ip + host to accept, then run run function.

  run will be two arguments: env and response.

  env including some important information web page which includes routing: PATH_INFO, storage use is the dictionary.

  run from the dictionary can be written to parse the PATH_INFO urls, perform the corresponding function.

  Method response function:

response('200 OK',[])

  Total code:

from wsgiref.simple_server import make_server

def run(env,response):
    print(env)
    response('200 OK',[])
    curruct_path = env.get('PATH_INFO')
    func = None
    for url in urls:
        if url[0] == curruct_path:
            func = url[1]
            break
    if func:
        res = func(env)
    else:
        res = error(env)
    return [res.encode()]

  The env kv key:

{'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\xin\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-V7OFSTO', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\xin', 'LOCALAPPDATA': 'C:\\Users\\xin\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-V7OFSTO', 'NUMBER_OF_PROCESSORS': '4', 'ONEDRIVE': 'C:\\Users\\xin\\OneDrive', 'ONEDRIVECONSUMER': 'C:\\Users\\xin\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'D:\\python3.6\\Scripts\\;D:\\python3.6\\Scripts;D:\\python3.6\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;F:\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;D:\\python2.7\\Scripts;D:\\python2.7\\;D:\\mysql\\mysql-5.6.45-winx64\\bin;C:\\Users\\xin\\AppData\\Local\\Microsoft\\WindowsApps;', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 61 Stepping 4, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '3d04', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_PORT': '51431', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\python编译器\\PyCharm 2018.1.4\\helpers\\pycharm_matplotlib_backend;D:\\pythontext\\9_15', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\Windows', 'TEMP': 'C:\\Users\\xin\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\xin\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-V7OFSTO', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-V7OFSTO', 'USERNAME': 'xin', 'USERPROFILE': 'C:\\Users\\xin', 'WINDIR': 'C:\\Windows', 'SERVER_NAME': 'DESKTOP-V7OFSTO', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8080', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/index', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'text/plain', 'HTTP_HOST': '127.0.0.1:8080', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'HTTP_SEC_FETCH_SITE': 'none', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9,en;q=0.8', 'wsgi.input': <_io.BufferedReader name=844>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>}
kv

three. Static and dynamic pages

  Static pages:

    Data on the page is written dead, the same years

  dynamic webpages:

    Data on the page is retrieved from the back-end dynamic

    For example, the back end to get the current time

    Back-end database to obtain the data is then passed to the front page.

  Therefore, the simulation of dynamic pages, you need to write a page, use $$ time character occupying time, and then replace the characters by the time function.

  (Page pass == "page rendering)

  Add functionality. How to dynamically add the dictionary to the page loop, and use the point value method.

four. jinja2 use

  Download jinja2: pip3 install jinja2

  flask is dependent on jinja2, so download the flask can download jinja2.

  jinja2 can be back-end data template (html page) is processed, the dictionary has become a point method and data dictionary value method, the syntax is as follows:

from jinja2 import Template
def get_user(env):
    user_dic = {'name':'lzx','pwd':'123'}
    with open(r'D:\pythontext\9_15\template\user.html','r') as f:
        date = f.read()
    temp = Template(date)
    res = temp.render(date = user_dic)
    return res

  The page displays the following

{{date}}}
{{date.name}}
{{date['name']}}
{{date.get('name')}}

  jinja2 dynamic display database:

import pymysql
def get_db(env):
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        charset='utf8',
        user='root',
        password='123456',
        database='test',
        autocommit=True
    )
    cursor = conn.cursor(
        pymysql.cursors.DictCursor
    )
    sql = 'select * from user'
    with open(r'D:\pythontext\9_15\template\get_db.html','r') as f:
        date1 = f.read()
    date2 = cursor.execute(sql)
    date = cursor.fetchall()
    temp = Template(date1)
    res = temp.render(user_list=date)
    return res

  template:

{% for user_dict in user_list%}
                        <tr>
                            <td>{{user_dict.id}}</td>
                            <td>{{user_dict.name}}</td>
                            <td>{{user_dict.pwd}}</td>
                        </tr>
                    {%endfor%}

  So web draw a flow chart:

 

 

 

 Fives. web framework.

  There are three major python web framework

    Django: large and comes with a lot of functional modules, similar to the aircraft carrier (Cons: a little bulky)

    Flask: dapper, built-in function modules are extremely rare, most of them are dependent on third-party modules (small and light)

      Flask made particularly to third frame assembly, may be worth a combined django

    Tornado: asynchronous non-blocking treatment is mainly used in the case of high-io multiplexing can write game backend

 

      high speed.

A: Socket
B: routing and view function
c: rendering template

Django:
A use of someone else's wsgiref
b write their own
c himself wrote
the Flask:
A use of someone else's Werkzeug
b write their own
c with someone else's jinja2
Tornado:
A, b, c are to write their own

six. Django framework:

  Caution:

    1. The name of the computer can not have Chinese

    2. A pycharm window is a project, not multiple projects in a window inside

    3. Project name can not be played Chinese

  About Version:

    Recommended 1.11.11

  

Django project to create a way to
Mode 1 (command line to create):
Create a project django
django-admin startproject project name
to create app application
python3 manage.py startapp app01
start django project
python3 manage.py the runserver
PS: django create the command line does not automatically default create templates folder
you need to manually create yourself (note change whether the folder path is added in the configuration file)



mode 2 (pycharm created)
fILE >>> new new Project select the second django note can not have a Chinese name, select the local interpretation , a background check management
create App
PyCharm command line to create
python3 manage.py startapp app01
Tools the following functions run manage task bar
to start a small green arrow

stressed:
1. django must ensure that only a running state Remember Remember! ! ! ! ! ! !
2. must remember clear browser cache

 

Guess you like

Origin www.cnblogs.com/LZXlzmmddtm/p/11525229.html