django框架
1、框架介绍
根据第一部分内容介绍,我们可以总结出一个web框架应该包含如下三部分:a.sockect服务、b.根据不同的url调用不同函数(包含逻辑)、c.返回内容(模板渲染)。常见的python WEB框架有tornado(包含如上3部分, Django(上述a部分为第三方的),flask(上述a和c为第三方的)。
2、Django安装
一、命令行方式
命令行创建django项目(首先将cd到django项目欲放置的位置):
使用方法
进到要存放的文件夹目录
启动Django项目: 命令行方式: python manage.py runserver 127.0.0.1:8888 python manage.py runserver 8888
目录介绍
配置文件
模板文件配置:在python中创建一个django项目后,在项目文件夹下会多一个templates文件夹,主要用于存放html模板文件,若要准确找到引用的html文件,需要在setting文件中对此文件夹路径进行配置。如下:(利用pycharm创建django项目,pycharm会自动帮你创建)
静态文件配置:在使用html模板文件时,其通常会有使用js或css等文件,这些文件称为静态文件,为了使其正常生效,我们也需要在setting文件进行相关配置,如下:
html文件中引用静态文件的方式如下:
django入门必学三招
HttpResponse
:用于向服务器返回字符串(如启动服务后,在浏览器请求:127.0.0.1:8000/index/后,浏览器显示hello world字符内容)
from django.conf.urls import urlfrom django.contrib import admin from django.shortcuts import HttpResponse,render,redirect def index(request): # 所有跟请求相关的数据,都保存在request return HttpResponse("hello world
") urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^index/', index), ]
(2)render
:用于渲染html文件,如启动服务后,在浏览器请求:127.0.0.1:8000/login/后,浏览器会显示login.html文件应被渲染出的结果
urls.py
此过程中的错误点:
redirect(具体要跳转的URl)
用django连接数据库,密码登录网站
def login(request): # return HttpResponse("Hello World") # 判断request是否是POST方法 error_msg = ' ' if request.method == "POST": # 定义两个变量接收浏览器POST的数据 name = request.POST.get("username") pwd = request.POST.get("password") # 与数据库建立连接 # conn = pymysql.connect(host="localhost", database="day60", user="root", password="123456", charset="utf8") conn = pymysql.connect(**config) cursor = conn.cursor() # 查询语句,进行密码以及账号的认证 sql = "SELECT * FROM userinfo WHERE NAME = %s AND pwd = %s;" try: ret = cursor.execute(sql, [name, pwd]) if ret: return redirect("http://www.cnblogs.com/jassin-du/p/8270462.html") else: error_msg = "用户名密码错误" except Exception as e: print(e) return render(request, "login.html", { "key": error_msg})urlpatterns = [ url(r'^login/', login), url(r'^admin/', admin.site.urls), # url(r'^$', login),]
登录
"""Django settings for jgo项目 project.Generated by 'django-admin startproject' using Django 1.11.8.For more information on this file, seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/1.11/ref/settings/"""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 = '7(_h_umn&5&k2u60h@_=-*k2@28d+!g)#pab2vqr*6v+gt0bha'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = True#ALLOWED_HOSTS = []# Application definition# 安装的appINSTALLED_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',]# url 路由的某些配置ROOT_URLCONF = 'jgo项目.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服务器网关WSGI_APPLICATION = 'jgo项目.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 = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/1.11/howto/static-files/# 静态文件(css 文件和 js文件) 存放的实际位置STATIC_URL = '/static/'# 静态文件(css文件和js文件) 存放的实际位置STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"), # os.path.join(BASE_DIR,"css"),]