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 url
from django.contrib import admin from django.shortcuts import HttpResponse,render,redirect def index(request): # 所有跟请求相关的数据,都保存在request return HttpResponse("<h1>hello world</h1>") urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^index/', index), ]
(2)render
:用于渲染html文件,如启动服务后,在浏览器请求:127.0.0.1:8000/login/后,浏览器会显示login.html文件应被渲染出的结果
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
此过程中的错误点:
redirect(具体要跳转的URl)
用django连接数据库,密码登录网站
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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), ]
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录</title> <link rel="stylesheet" href="../static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <link rel="stylesheet" href="/templates/login.html"> <style> body { background-color: #eeeeee; } #login-form { margin-top: 100px; } </style> </head> <body> <div class="container"> <div class="row"> <form id="login-form" class="form-horizontal col-md-4 col-md-offset-4" action="login.html" method="post"> <h3 class="text-center">请登录</h3> <div class="form-group"> <label for="username" class="col-sm-2 control-label">账号</label> <div class="col-sm-10"> <input type="text" class="form-control" id="username" placeholder="账号" name="username"> </div> </div> <div class="form-group"> <label for="inputPassword" class="col-sm-2 control-label">密码</label> <div class="col-sm-10"> <input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox">记住我 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary btn-block">登录</button> <p style="color: red">{{key}}</p> </div> </div> </form> </div> </div> <script src="../static/jquery-3.2.1.min.js"></script> </body> </html>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
""" Django settings for jgo项目 project. Generated by 'django-admin startproject' using Django 1.11.8. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://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 # 安装的app 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', ] # 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 = True USE_L10N = True USE_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"), ]