1 昨日回顧
a socket
b 路由關係
c 模板字符串替換(模板語言)
主流web框架總結:
django a用別人的 b本身寫的 c本身寫的
flask a用別人的 b本身寫的 c用別人的(jinja2)
tornado a本身寫的 b本身寫的 c本身寫的
另外一個維度:
djaogo
其餘
建立Django
1 模塊安裝(三種方法)
1 ---
2 --
3--
2 django-admin startproject mysite
3 manage.py 管理個人django項目
4 (1)啓動django--python3
-manage.py runserver 127.0.0.1:8002
-manage.py runserver 8002
-manage.py runserver
(2)pycharm啓動:1 跟上面同樣
2 點綠色的箭頭
不是點右鍵運行
5 中止 ctrl+c
6 目錄介紹
settings--django全局配置文件
urls---路由關係
app:
命令:python3 manage.py startapp app01
目錄:
migrations:數據庫遷移的文件
admin:後臺管理相關
apps:app配置相關
models:模型,數據庫相關,寫一些類
tests:測試相關
views:視圖函數
settings:
DEBUG
INSTALLED_APPS---》放app的名字
MIDDLEWARE--》中間件
TEMPLATES---》指定模板文件放的路徑
DATABASES---》指定鏈接的數據庫
靜態文件配置:(名字必定不能錯)
STATICFILES_DIRS=[
os.path.join(BASE_DIR, 'static'),
]
三件套:
# render 模板渲染
# HttpResponse 返回字符串
# redirect 重定向
orm:對象關係映射
python代碼------》sql
前端:
$("#app")------>document.getEmlementById(‘app’)
優勢:
1 sql掌握通常,也可開發程序
2 開發效率高
3 易用,學習曲線短
缺點:
1 sql大神,執行效率高,可能orm 執行效率低
2 有的sql寫不出來
做業:
1 上課講的代碼敲完
2 寫個註冊,登陸
3 看一下orm(有餘力)
項目的基本配置 settings文件
1 """
2 Django settings for mySecond project. 3
4 Generated by 'django-admin startproject' using Django 1.11. 5
6 For more information on this file, see 7 https://docs.djangoproject.com/en/1.11/topics/settings/ 8
9 For the full list of settings and their values, see 10 https://docs.djangoproject.com/en/1.11/ref/settings/ 11 """
12
13 import os 14
15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 # 根路徑 mySecond
17 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18
19
20 # Quick-start development settings - unsuitable for production
21 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
22
23 # SECURITY WARNING: keep the secret key used in production secret!
24 SECRET_KEY = 'uzz2#7dq+qruh2e6&cklrwj49(oe0&@hwaqqtkmb0z2xmhe03*'
25
26 # SECURITY WARNING: don't run with debug turned on in production!
27 DEBUG = True 28
29 ALLOWED_HOSTS = [] 30
31
32 # Application definition
33
34 # 放app的名字
35 INSTALLED_APPS = [ 36 'django.contrib.admin', 37 'django.contrib.auth', 38 'django.contrib.contenttypes', 39 'django.contrib.sessions', 40 'django.contrib.messages', 41 'django.contrib.staticfiles', 42 # 新建的功能項目須要添加到INSTALLED_APPS
43 # app01下面的apps裏面的App01Config
44 'app01.apps.App01Config', 45 ] 46
47 MIDDLEWARE = [ 48 'django.middleware.security.SecurityMiddleware', 49 'django.contrib.sessions.middleware.SessionMiddleware', 50 'django.middleware.common.CommonMiddleware', 51 # 'django.middleware.csrf.CsrfViewMiddleware', 中間件 跨站攻擊防禦的先註釋掉,之後再加上
52 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 'django.contrib.messages.middleware.MessageMiddleware', 54 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 ] 56
57 ROOT_URLCONF = 'mySecond.urls'
58
59 TEMPLATES = [ 60 { 61 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 # 把模板路徑放到裏面
63 'DIRS': [os.path.join(BASE_DIR, 'templates')] # 若是建立項目的時候括號裏沒有內容須要手動加上
64 , 65 'APP_DIRS': True, 66 'OPTIONS': { 67 'context_processors': [ 68 'django.template.context_processors.debug', 69 'django.template.context_processors.request', 70 'django.contrib.auth.context_processors.auth', 71 'django.contrib.messages.context_processors.messages', 72 ], 73 }, 74 }, 75 ] 76
77 WSGI_APPLICATION = 'mySecond.wsgi.application'
78
79
80 # Database
81 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
82
83 # DATABASES---》指定鏈接的數據庫
84 DATABASES = { 85 'default': { 86 'ENGINE': 'django.db.backends.sqlite3', 87 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 88 } 89 } 90
91
92 # Password validation
93 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
94
95 AUTH_PASSWORD_VALIDATORS = [ 96 { 97 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 98 }, 99 { 100 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 101 }, 102 { 103 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 104 }, 105 { 106 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 107 }, 108 ] 109
110
111 # Internationalization
112 # https://docs.djangoproject.com/en/1.11/topics/i18n/
113
114 LANGUAGE_CODE = 'en-us'
115
116 TIME_ZONE = 'UTC'
117
118 USE_I18N = True 119
120 USE_L10N = True 121
122 USE_TZ = True 123
124
125 # Static files (CSS, JavaScript, Images)
126 # https://docs.djangoproject.com/en/1.11/howto/static-files/
127
128 # 靜態文件配置:(名字必定不能錯)
129 # STATICFILES_DIRS=[
130 # os.path.join(BASE_DIR, 'static'),
131 # ]
132 STATIC_URL = '/static/' # 這步至關於作了個接口,經過接口來訪問STATICFILES_DIRS
133 # 若是不寫static_url這個接口,外面能夠直接調用裏面的文件
134 STATICFILES_DIRS=[ 135 os.path.join(BASE_DIR, 'static'), 136 ]
管理django項目的manage文件css
1 #!/usr/bin/env python
2 import os 3 import sys 4
5 if __name__ == "__main__": 6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mySecond.settings") 7 try: 8 from django.core.management import execute_from_command_line 9 except ImportError: 10 # The above import may fail for some other reason. Ensure that the
11 # issue is really that Django is missing to avoid masking other
12 # exceptions on Python 2.
13 try: 14 import django 15 except ImportError: 16 raise ImportError( 17 "Couldn't import Django. Are you sure it's installed and "
18 "available on your PYTHONPATH environment variable? Did you "
19 "forget to activate a virtual environment?"
20 ) 21 raise
22 execute_from_command_line(sys.argv)
urls 存放請求地址和函數關係的路由html
1 """mySecond URL Configuration 2
3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/1.11/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.conf.urls import url, include 14 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 """
16 from django.conf.urls import url 17 from django.contrib import admin 18 from app01 import views 19 urlpatterns = [ 20 url(r'^admin/', admin.site.urls), 21 url(r'^index/', views.index), 22 url(r'^login/', views.login), 23 url(r'^login_submit/', views.login_submit), 24 ]
views 視圖函數的存放點前端
1 from django.shortcuts import render,HttpResponse,redirect 2 # 三件套 render 模板渲染
3 # HttpResponse 返回字符串
4 # redirect 重定向
5 import pymysql 6
7
8 # redirect 重定向
9 # Create your views here.
10
11
12 def index(request): 13 # with open('templates/index','r') as f:
14 # data=f.read()
15 print(request.method) 16
17 # return HttpResponse('<h1>Hellw</h1>')
18 return render(request, 'index.html') 19
20
21 def login111(request): 22 # GET 必定要大寫
23 if request.method == 'GET': 24 return render(request, 'login.html') 25 elif request.method == 'POST': 26 name = request.POST['name'] 27 # 推薦用這種
28 # request.POST 請求體的內容都在裏面,字典形式
29 # <QueryDict: {'name': ['123'], 'password': ['444']}>
30 password = request.POST.get('password', None) 31 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306) 32
33 cursor = conn.cursor(pymysql.cursors.DictCursor) 34 cursor.execute('select * from user where name=%s and password=%s', [name, password]) 35 user = cursor.fetchone() 36 if user: 37 return HttpResponse('登陸成功') 38 # if name == 'lqz' and password == '123':
39 # # return HttpResponse('登陸成功')
40 # return redirect('www.baidu.com')
41 # # return redirect('http://127.0.0.1:8000/index/')
42 else: 43 error = '用戶名或密碼錯誤'
44 return render(request, 'login.html', {'error': error}) 45
46
47 def login(request): 48 error = ''
49 if request.method == 'POST': 50 name = request.POST['name'] 51 password = request.POST.get('password', None) 52 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306) 53 cursor = conn.cursor(pymysql.cursors.DictCursor) 54 cursor.execute('select * from user where name=%s and password=%s', [name, password]) 55 user = cursor.fetchone() 56 if user: 57 return HttpResponse('登陸成功') 58 else: 59 error = '用戶名或密碼錯誤'
60 return render(request, 'login.html', {'error': error}) 61
62
63 def login_submit(request): 64 # print(request.get_full_path())
65 # print(request.method)
66 print(request.POST) 67 name = request.POST.get('name',None) 68 # 推薦用這種
69 # request.POST 請求體的內容都在裏面,字典形式
70 # <QueryDict: {'name': ['123'], 'password': ['444']}>
71 password = request.POST.get('password', None) 72 if name == 'lqz' and password == '123': 73 # return HttpResponse('登陸成功')
74 return redirect('/index/') 75
76 return redirect('/login/')
注意:html結尾的這些文件一般都放在templates下,稱做模板python
index.htmlmysql
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 <link rel="stylesheet" href="/static/css/mycss.css">
7 </head>
8 <body>
9 <h1>Hello</h1>
10 </body>
11 </html>
login.htmlweb
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>登陸</title>
6 <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.min.css">
7 </head>
8 <body>
9 <div class="container">
10
11 <div class="row">
12
13 <div class="col-md-6 col-md-offset-3">
14
15 <form action="" method="post">
16
17 <p>用戶名:<input type="text" name="name" class="form-control" ></p>
18 <p>密碼:<input type="password" name="password" class="form-control"></p>
19 <p><input type="submit" value="登陸" class="form-control"></p>
20 <p class="text-danger text-center">{{ error }}</p>
21
22
23 </form>
24 </div>
25 </div>
26
27 </div>
28
29
30
31 </body>
32 </html>
static文件:下面存放着css,js,img,bootstrap等。。sql
最後,附上本身的做業:數據庫
1 from django.shortcuts import render,HttpResponse,redirect 2
3 # Create your views here.
4 # 視圖層函數裏面就是一個個須要經過路由來調用並訪問的函數
5 # 調用函數的目的是爲了去訪問模板層。
6 import pymysql 7
8
9 def index(request): 10 with open('templates/index','r') as f: 11 print(f.read()) 12 return render(request,'index.html') 13 # return HttpResponse('<h1>hellowword</h1>')
14
15
16
17
18 def register(request): 19 if request.method == 'GET': 20 return render(request,'register.html') 21 elif request.method == 'POST': 22 name = request.POST.get('name',None) 23 password = request.POST.get('password',None) 24 re_password = request.POST.get('re_password',None) 25 if password != re_password: 26 return HttpResponse('password is not similar') 27 else: 28 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306) 29
30 cursor = conn.cursor(pymysql.cursors.DictCursor) 31 cursor.execute('select * from user where name=%s and password = %s', [name, password]) 32 user = cursor.fetchone() 33 if user: 34 return HttpResponse('having the similar user please change the user or password') 35 else: 36 # 數據庫建表的時候要遞增
37 cursor.execute('insert into user(name,password) values(%s,%s) ', [name, password]) 38 print(request.POST.get('name',None)) 39 # 必需要提交,不然不會寫到數據庫裏
40 conn.commit() 41 # 必需要有返回值
42 return HttpResponse('sn') 43
44 def login(request): 45 if request.method == 'GET': 46 return render(request,'login.html') 47 elif request.method == 'POST': 48 name = request.POST.get('name',None) 49 password = request.POST.get('password',None) 50 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306) 51
52 cursor = conn.cursor(pymysql.cursors.DictCursor) 53 cursor.execute('select * from user where name=%s and password=%s', [name, password]) 54 user = cursor.fetchone() 55 if user: 56 return HttpResponse('login success') 57 else: 58 error = "logging fail,relog again"
59 return render(request,'login.html',{'error':error})
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>register</title>
6 <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
7 </head>
8 <body>
9 <div class = 'row'>
10 <div class = 'col-md-6 col-md-offset-3'>
11 <form action="" method = 'post'>
12 <p>user:<input type="text" name="name" class="form-control" ></p>
13 <p>pwd:<input type="password" name="password" class="form-control"></p>
14 <p>re_pwd:<input type="password" name="re_password" class="form-control"></p>
15 <p><input type="submit" value="register" class="form-control"></p>
16 <p class="text-danger text-center">{{ error }}</p>
17 </form>
18 </div>
19 </div>
20
21 </body>
22 </html>