码迷,mamicode.com
首页 > 其他好文 > 详细

重修课程day57(Django的开始)

时间:2017-11-26 19:39:14      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:session   ocs   ida   set   sim   pre   one   display   pass   

一 浏览器相关知识

 http:只有依赖一回,属于短链接,不会报错客户端的信息。

 浏览器相当于一个客户端,客户端的链接

 服务端:socket服务端,起服务监听客户端的请求。

技术分享图片
import socket
sk=socket.socket()
sk.bind((‘192.168.11.38‘,8888))
sk.listen(5)

def index():
    with open(‘轮播网页.html‘,encoding=‘utf-8‘)as f:
        ret=f.read()
        return ret
def login():
    with open(‘login.html‘,encoding=‘utf-8‘)as f:
        ret=f.read()
    import pymysql
    conn=pymysql.connect(
        host=‘127.0.0.1‘,
        port=3306,
        user=‘root‘,
        passwd=‘0410‘,
        db=‘day46‘
    )
    cursor=conn.cursor()
    cursor.execute(‘select * from user‘)
    user_list=cursor.fetchall()
    cursor.close()
    conn.close()
    res=‘‘
    for i in user_list:
        res += ‘‘‘
        <tr>
            <td>{}</td>
            <td>{}</td>
            <td>{}</td>
        </tr>
        ‘‘‘.format(i[0], i[1], i[2])
    tables= ret.replace(‘@@xx@@‘,res)
    return tables




def info():
    return "这是个人信息"

info_index=[
    (‘/login/‘,login),
    (‘/index/‘,index),
    (‘/info/‘,info)
]
while True:
    conn,addr=sk.accept()
    print(addr)
    data=conn.recv(8096)
    data3=str(data,encoding=‘utf-8‘)
    data1=data3.split(‘\r\n\r\n‘)[0]
    print(‘*‘*50)
    print(data1)
    data2=data1.split(‘\r\n‘)[0].split(‘ ‘)[1]
    print(data2)
    ingo_name=None
    for i in info_index:
        if data2==i[0]:
            ingo_name=i[1]
            break
    if ingo_name:
        response=ingo_name()
    else:
        response=‘404‘

    conn.send(b‘HTTP/1.1 200 0k\r\nContent-Type:text/html;charset=utf-8\r\n\r\n‘)
    conn.send(response.encode(‘utf-8‘))
    conn.close()
View Code

二 框架的介绍

 tornado:模版都是人家写好的,我们只管拿来使用。

 Django:服务端可以自己写,其他的模版都是别人写好的。

 flask:服务端和模版渲染都是自己写的,函数的功能都是别人写好了的。

 所有的web框架叫做web应用服务器。

三 django的安装和使用

 安装:pip install django。

 创建项目:django-admin startproject 项目名

 手动创建:

技术分享图片技术分享图片

 查看参数:django-admin。

 开启项目:python manage.py runserver

 响应格式:

  {

  "接收到的想要":回复

。。。。。

  }

四 使用

 request:代表所有请求的内容

  request.method

  request.POST.get(‘***‘)

 新手三件套:

  导入:from django.import import

   HttpResponse:http的响应

   render:渲染

    render(request, ‘html文件‘)

    render(request,"html文件",{"替换的内容":值})

   redirect:跳转页面

技术分享图片
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import render,redirect



def mysql():
    import pymysql
    user_dic = {}
    conn=pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="0410", db="day43", charset="utf8")
    cursor=conn.cursor()
    cursor.execute(‘select name,password from user‘)
    user_list = cursor.fetchall()
    cursor.close()
    conn.close()
    for user in user_list:
        user_dic[user[0]]=user[1]
    return user_dic


def login(request):
    if request.method==‘GET‘:
        return render(request,‘登陆界面.html‘)
    else:
        user_dic=mysql()
        for user in user_dic:
            if request.POST.get(‘user‘)==user and request.POST.get(‘passwd‘)==user_dic[user] and request.POST.get(‘pwd‘)==user_dic[user]:
                return redirect(‘http://www.xiaohuar.com/hua/‘)
            elif request.POST.get(‘user‘)==user and request.POST.get(‘passwd‘)==user_dic[user] and request.POST.get(‘pwd‘)!=user_dic[user]:
                return render(request, ‘登陆界面.html‘, {‘error_msg‘: ‘密码输入不一致‘})
        else:
            return render(request,‘登陆界面.html‘,{‘error_msg‘:‘用户名和密码错误‘})

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^login/‘,login)
]
View Code

 模版语言:

  格式1:

   {% for i in **%}

    {{x}}

   {% endfor %}

  格式2:

   {{ 变量名 }}

技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            width: 100%;
            height: 50px;
            background-color:#DDDDDD;
            opacity: 0.3;
        }

        .c4{
            width:80%;
            height:50px;
            background-color:#DDDDDD;
            margin-left: 10%;
        }

        .c7{
            width: 100px;
            height: 50px;
            float:left;
        }

        .c8{
            width: 80px;
            height: 50px;
            float:right;
        }

        .c9{
            width: 120px;
            height: 50px;
            float:right;
        }

        .c10{
            width: 80px;
            height: 50px;
            float:right;
        }

        .c11{
            width: 80px;
            height: 50px;
            float:right;
        }

         .c12{
             width: 50px;
             height: 50px;
             float:right;
        }

        .s1{
            line-height:50px;
            text-align: center;
            color:#1F1E1E;
        }

        .c2{
            width:100%;
            height: 60px;
            background-color: #ffffff;
            margin-top: 20px;
        }

        .c5{
            width: 80%;
            height: 60px;
            background-color: #FFFFFF;
            margin-left: 10%;
        }
        .c3{
            width:100%;
            height:auto;

        }

        .c6{
            width: 80%;
            height: auto;
            margin-left: 10%;
        }

        .d1{
            width: 500px;
            height: 400px;
            float: left;
            margin-top: 50px;
        }

        .d3{
            width: 500px;
            height: 50px;
            margin-top:60px;
        }

        .s2{
            font-weight:600;
            font-size:30px;
            color: #2e2e2e;
            line-height:50px;
            margin-left: 70px;

        }

        .p1{
            margin-left: 120px;
        }

        .p2{
            margin-left: 104px;
        }


        .i2{
            margin-left: 15px;
        }

        .s3{
            color:red;
        }

        .p4{
            margin-left: 150px;
        }

        .s4{
            color:#0000CC;
        }

        .i3{
            font-size: 14px;
        }


        .p5{
            margin-left: 200px;
        }

        .i5{
            font-size: 10px;
             background-color:red;
        }

        .d2{
            width: 314px;
            height:400px;
            float: right;
            margin-top: 50px;
        }

        .p6{
            margin-left:30px;
        }


        .p7{
            margin-top: 50px;
        }

    </style>
</head>
<body>

<div class="c1">
    <div class="c4">
        <div class="c7"><span class="s1">*收藏网址</span></div>
        <div class="c8"><span class="s1">客户服务</span></div>
        <div class="c9"><span class="s1">VIP会员俱乐部</span></div>
        <div class="c10"><span class="s1">我的订单</span></div>
        <div class="c11"><span class="s1">免费注册</span></div>
        <div class="c12"><span class="s1">登陆</span></div>
    </div>
</div>
<div class="c2">
    <div class="c5"><img src="111.png" alt="悟空"></div>
</div>
<div class="c3">
    <div class="c6">
        <div class="d1">
            <div class="d3"><span class="s2">注册新用户</span></div>
            <form action="/login/" method="post">
                <p class="p1"><span class="s3">*</span>用户名:<input type="text" name="user" class="i2"></p>
                <p class="p1"><span class="s3">*</span>手机号:<input type="text" name="phone" class="i2"></p>
                <p class="p2"><span class="s3">*</span>登陆密码:<input type="password" name="passwd" class="i2"></p>
                <p class="p2"><span class="s3">*</span>确认密码:<input type="password" name="pwd" class="i2"></p>
                <p class="p4"><input type="checkbox" name="ppp"><span class="i3">我已阅读并同意</span><span class="s4 i3">《用户注册协议》</span> </p>
                <p class="p5"><input type="submit" value="开始登录" class="i5"></p>
                {{ error_msg }}
            </form>
        </div>
        <div class="d2">
            <p class="p6 p7"><img src="222.png" alt="悟天" width=‘250px‘ height="200px"></p>
        </div>
    </div>
</div>
</body>
</html>
View Code

 setting文件的配置:

  添加路径:

			TEMPLATES = [
				{
					‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
					‘DIRS‘: [],   # 在这里进行设置
					‘APP_DIRS‘: True,
					‘OPTIONS‘: {
						‘context_processors‘: [
							‘django.template.context_processors.debug‘,
							‘django.template.context_processors.request‘,
							‘django.contrib.auth.context_processors.auth‘,
							‘django.contrib.messages.context_processors.messages‘,
						],
					},
				},
			]
			

   注释内容:

			2. 中间件需要注释一个
			MIDDLEWARE = [
			‘django.middleware.security.SecurityMiddleware‘,
			‘django.contrib.sessions.middleware.SessionMiddleware‘,
			‘django.middleware.common.CommonMiddleware‘,
			# ‘django.middleware.csrf.CsrfViewMiddleware‘,
			‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
			‘django.contrib.messages.middleware.MessageMiddleware‘,
			‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
		]

   静态文件设置:

			STATIC_URL = ‘/static/‘
			STATICFILES_DIRS = (
				os.path.join(BASE_DIR, "ss"),  # 静态文件存放位置
				
			)
技术分享图片
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘#vofy$6d=w^aoa0kk#8jhtc3mno9o)eil^8-a^u=)cana=9zq^‘

# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
]

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    # ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]

ROOT_URLCONF = ‘bigJob.urls‘

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)]
        ,
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]

WSGI_APPLICATION = ‘bigJob.wsgi.application‘


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
        ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.MinimumLengthValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.CommonPasswordValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.NumericPasswordValidator‘,
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = ‘en-us‘

TIME_ZONE = ‘UTC‘

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = ‘/static/‘
STATICFILES_DIRS=(os.path.join(BASE_DIR,‘css‘),)
IEMPLATE_DIRS=(os.path.join(BASE_DIR,‘templates‘),)
View Code

 

   

 

重修课程day57(Django的开始)

标签:session   ocs   ida   set   sim   pre   one   display   pass   

原文地址:http://www.cnblogs.com/fangjie0410/p/7896589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!