Python Django 实现简单注册功能过程详解
人气:0项目创建略,可参考Python Django Vue 项目创建。
目录结构如下
编辑views.py
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render from common.DBHandle import DataBaseHandle import time def djangoHello(request): return HttpResponse('Hello Django!') def index(request): return render(request,'index.html') def login(request): print('login_func') usn = request.POST['username'] pwd = request.POST['password'] host = '127.0.0.1' username = 'username' password = 'password' database = 'dbname' port = 3306 # 实例化 数据库 连接 DbHandle = DataBaseHandle(host, username, password, database, port) localTime = time.localtime(time.time()) create_time = time.strftime("%Y-%m-%d %H:%M:%S", localTime) sql = "insert into user(username,password,create_time) values ('%s','%s','%s')" % (usn, pwd, create_time) DbHandle.insertDB(sql) DbHandle.closeDb() return render(request,'login.html')
接下来编辑urls.py
"""FirstWeb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from fistWeb import views urlpatterns = [ path('admin/', admin.site.urls), path('hello/',views.djangoHello), path('index/',views.index), path('login/',views.login), ]
在应用下创建templates 文件夹
并创建html文件 index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>FirstWeb</title> </head> <body> <h1>信息注册</h1> <!-- action="/login/" 这里是 提交后访问的路径,因此 要在 urls 添加改路径 --> <form action="/login/" method="post"> {% csrf_token %} 用户名:<input type="text" name="username" id="usn"><br> 密 码:<input type="password" name="password" id="pwd"><br> <input type="submit" value="注册"> </form> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>FirstWeb-登录</title> </head> <body> <h1>您好,您已注册成功!</h1> </body> </html>
介绍一下添加的common文件
添加一个数据库封装的类。
# FileName : DBHandle.py # Author : Adil # DateTime : 2018/11/29 2:03 PM # SoftWare : PyCharm import pymysql # username : adil # password : helloyyj class DataBaseHandle(object): ''' 定义一个 MySQL 操作类''' def __init__(self,host,username,password,database,port): '''初始化数据库信息并创建数据库连接''' # 下面的赋值其实可以省略,connect 时 直接使用形参即可 self.host = host self.username = username self.password = password self.database = database self.port = port self.db = pymysql.connect(self.host,self.username,self.password,self.database,self.port,charset='utf8') # 这里 注释连接的方法,是为了 实例化对象时,就创建连接。不许要单独处理连接了。 # # def connDataBase(self): # ''' 数据库连接 ''' # # self.db = pymysql.connect(self.host,self.username,self.password,self.port,self.database) # # # self.cursor = self.db.cursor() # # return self.db def insertDB(self,sql): ''' 插入数据库操作 ''' self.cursor = self.db.cursor() try: # 执行sql self.cursor.execute(sql) # tt = self.cursor.execute(sql) # 返回 插入数据 条数 可以根据 返回值 判定处理结果 # print(tt) self.db.commit() print('执行成功') except: # 发生错误时回滚 self.db.rollback() print('执行失败') finally: self.cursor.close() def deleteDB(self,sql): ''' 操作数据库数据删除 ''' self.cursor = self.db.cursor() try: # 执行sql self.cursor.execute(sql) # tt = self.cursor.execute(sql) # 返回 删除数据 条数 可以根据 返回值 判定处理结果 # print(tt) self.db.commit() except: # 发生错误时回滚 self.db.rollback() finally: self.cursor.close() def updateDb(self,sql): ''' 更新数据库操作 ''' self.cursor = self.db.cursor() try: # 执行sql self.cursor.execute(sql) # tt = self.cursor.execute(sql) # 返回 更新数据 条数 可以根据 返回值 判定处理结果 # print(tt) self.db.commit() except: # 发生错误时回滚 self.db.rollback() finally: self.cursor.close() def selectDb(self,sql): ''' 数据库查询 ''' self.cursor = self.db.cursor() try: self.cursor.execute(sql) # 返回 查询数据 条数 可以根据 返回值 判定处理结果 data = self.cursor.fetchall() # 返回所有记录列表 print(data) # 结果遍历 for row in data: sid = row[0] name = row[1] # 遍历打印结果 print('sid = %s, name = %s'%(sid,name)) except: print('Error: unable to fecth data') finally: self.cursor.close() def closeDb(self): ''' 数据库连接关闭 ''' self.db.close() if __name__ == '__main__': DbHandle = DataBaseHandle('127.0.0.1','username','password','dbname',3306) sql = "insert into JdwSpider(image_name,image_url,Spider_time) values ('%s','%s','%s')" % ( '1', '2', '2018-12-04 15:25:21') DbHandle.insertDB(sql) # DbHandle.insertDB('insert into test(name) values ("%s")'%('FuHongXue')) # DbHandle.insertDB('insert into test(name) values ("%s")'%('FuHongXue')) # DbHandle.selectDb('select * from test') # DbHandle.updateDb('update test set name = "%s" where sid = "%d"' %('YeKai',22)) # DbHandle.selectDb('select * from test') # DbHandle.insertDB('insert into test(name) values ("%s")'%('LiXunHuan')) # DbHandle.deleteDB('delete from test where sid > "%d"' %(25)) # DbHandle.selectDb('select * from test') DbHandle.closeDb()
以上代码实现了一个简单的注册页面,并将注册信息存放到数据库表中。
启动项目演示
打开浏览器输入url:http://127.0.0.1:8000/index/
点击注册提交按钮,页面跳转如下
查看数据库表,可以看到新增的用户信息。
您可能感兴趣的文章:
加载全部内容