django+mysql实现网页查询

django+mysql实现网页查询

实现网页查询并返回结果,将查询关键字保存至数据库

环境:

  • vscode 编辑器
  • python3.8.2
  • djangoVersion: 2.0
  • pip list
Package           Version
----------------- -------
astroid           2.4.2
colorama          0.4.3
Django            2.0
isort             4.3.21
lazy-object-proxy 1.4.3
mccabe            0.6.1
pip               20.1.1
pylint            2.5.3
PyMySQL           0.9.3
pytz              2020.1
setuptools        41.2.0
six               1.15.0
toml              0.10.1
wrapt             1.12.1

1、创建视图,添加映射

mkdir projects
cd projects
python -m venv .venv_mysql
cd .venv_mysql/scripts
activate ## 激活虚拟环境
pip install django==2.0## 高版本不支持pymysql,如果能安装上mysqlclient也可以使用高版本的
django-admin startproject  pro_mysql
cd pro_mysql
python manage.py startapp app_mysql

## 1、创建两个视图app_mysql/views.py
from django.shortcuts import render
# Create your views here.
def search(request):
    return render(request,"app_mysql/search.html",{})
def handle(request):
    return render(request,"app_mysql/resp.html",{})

## 2、修改pro/setting.py
INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘app_mysql‘,
]

# 3、添加映射
## 3.1 子路由app/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = ‘app_mysql‘  ## 命名空间
urlpatterns = [
    path(‘‘, views.search,name=‘search‘),
    path(‘handle/‘, views.handle,name=‘handle‘),
]
## 3.2 总路由pro/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘‘, include(‘app_mysql.urls‘)),
]

2、添加页面框架并测试django

# 1、app_mysql/templates/app_mysql/search.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <h1>hello world</h1>
    
</body>
</html>
# 2、app_mysql/templates/app_mysql/resp.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    
</body>
</html>

  • 命令行检查django是否安装成功

    python manage.py runserver

3、数据库mysql安装

  • https://www.cnblogs.com/winton-nfs/p/11524007.html

  • 下载mysql安装包,解压到安装目录,注意目录不要包含中文

  • ①下转到mysql的bin目录下:cmd命令行:cd mysql..\bin

  • ②安装mysql的服务:mysqld --install 或者mysqld –remove ,mysqld remove MySQL,删除data文件夹

  • ③初始化mysql,在这里,初始化会产生一个随机密码,记住这个密码,后面会用到(mysqld --initialize --console)

    • mysqld --initialize --console
    • -Knhlwhhj1wV
  • ④开启mysql的服务(net start mysql)、停服务net stop mysql

  • ⑤登录验证,mysql是否安装成功!

    • mysql -u root -p 密码提示输入:root110
  • 修改密码:alter user ‘root‘@‘localhost‘ identified by ‘root110‘;

    • exit
    • mysql -u root -p 密码提示输入:root110
  • 设置系统的全局变量:

    • ①点击"我的电脑"-->"属性"-->‘‘高级系统设置‘‘-->‘‘环境变量‘‘

4、navicat 连接数据库

  • 创建连接
    • mysql
    • app_mysql
    • localhost
    • 3306
    • root
    • root110
  • 创建数据库
    • 数据库名:mysql-demo1
    • 字符集:utf8mb4
    • 排序规则:空着
  • 创建表shop,text
    • shop表 和 text表可使用语法生成

5、vscode设置数据库连接

## 设置pro_mysql/__init__.py
## 命令行先安装pymysql
pip install pymysql
# import pymysql  # 导入第三方模块,用来操作mysql数据库
import pymysql
pymysql.install_as_MySQLdb()

## 设置pro_mysql/settings.py
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘mysql-demo1‘,
        ‘HOST‘: ‘127.0.0.1‘,
        ‘PORT‘: 3306,
        ‘USER‘:‘root‘,
        ‘PASSWORD‘:‘root110‘
    }
}


## 命令行查看数据库细节
python manage.py inspectdb

## 生成models.py文件
python manage.py inspectdb > models.py

## 将models.py移动到app下
## 修改models.py为可写
    class Meta:
        managed = True  ## True为可写
        db_table = ‘text‘

6、搜索网页内容编写

## 1、编写app/template/name1/search.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <form action="{% url ‘app_mysql:handle‘ %}" method="POST">    <!--命名空间app_name的值:对应函数-->
        {% csrf_token %}                                          <!--django防范跨越攻击的作用-->
        <div>       <!--搜索框-->
            <input type="text" name="搜索内容">   ## 注意属性之间没有逗号
            <input type="submit" value="搜索">
        </div>
    </form>
</body>
</html>

7、接收数据,返回数据

## 1、app_mysql/views.py中编写接收数据函数,将数据保存到数据库
from . import service
def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库
## app_mysql/service.py 新建文件,存储到数据库功能的文件
from .models import Text
def addText(text):
    text1 = Text(text=text)
    text1.save()

## 2、返回数据函数
def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库
    db = Shop.objects.all()          ## 将数据库的每条数据内容变为可操作的对象
    po_list=[]                        ## 创建列表
    for i in db:
        if text in i.title:
            po_list.append(i.content)       ## 若传入的text值在shop.title中,将shop.content加入列表

    return render(request,"app_mysql/resp.html",{"resp":po_list})  ## 将列表值返回给resp.html,使用resp接收

8、搜索结果返回网页编写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    {% for i  in resp %}
    <h1>{{ i }}</h1>
    {% endfor%}
</body>
</html>

9、测试结果

  • python manage.py runserver
  • 网页打开http://127.0.0.1:8000/
  • 输入表单内容,并提交
  • 跳转到http://127.0.0.1:8000/handle并有数据返回
  • 查看Navicat数据库中text表中是否保存有关键字

10、相关问题

  • 提示需要安装更高版本的mysqlclient时,可考虑降低django版本,原因可baidu

  • 提示vscode会提示出现Class “xxx” has no ‘objects’ member错误:

    • 不影响使用
    • pip install pylint-django
  • settings.json中增加以下语句

    {
        "python.pythonPath": ".venv\\Scripts\\python.exe",
        "python.linting.pylintArgs": ["--generate-members"]
    }
    

完整代码

app_mysql

  • views.py
from django.shortcuts import render
from . import service
from app_mysql.models import Shop

# Create your views here.
from django.shortcuts import render
# Create your views here.
def search(request):
    return render(request,"app_mysql/search.html",{})

def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库

    db = Shop.objects.all()          ## 将数据库的每条数据内容变为可操作的对象
    po_list=[]                        ## 创建列表
    for i in db:
        if text in i.title:
            po_list.append(i.content)       ## 若传入的text值在shop.title中,将shop.content加入列表

    return render(request,"app_mysql/resp.html",{"resp":po_list})  ## 将列表值返回给resp.html,使用resp接收
  • urls.py
from django.contrib import admin
from django.urls import path
from . import views

app_name = ‘app_mysql‘  ## 命名空间
urlpatterns = [
    path(‘‘, views.search,name=‘search‘),
    path(‘handle/‘, views.handle,name=‘handle‘),
]
  • modles.py
# This is an auto-generated Django model module.
# You‘ll have to do the following manually to clean this up:
#   * Rearrange models‘ order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don‘t rename db_table values or field names.
from django.db import models


class Shop(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=255, blank=True, null=True)
    content = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = True
        db_table = ‘shop‘


class Text(models.Model):
    id = models.IntegerField(primary_key=True)
    text = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = ‘text‘

  • service.py
from .models import Text

## 存储到数据库功能的文件
def addText(text):
    text1 = Text(text=text)
    text1.save()
  • seach.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <form action="{% url ‘app_mysql:handle‘ %}" method="POST">    <!--命名空间app_name的值:对应函数-->
        {% csrf_token %}                                          <!--django防范跨越攻击的作用-->
        <div>       <!--搜索框-->
            <input type="text" name="搜索内容">
            <input type="submit" value="搜索">
        </div>
    </form>
</body>
</html>
  • resp.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    {% for i  in resp %}
    <h1>{{ i }}</h1>
    {% endfor%}
</body>
</html>

django+mysql实现网页查询

上一篇:MongoDB安装和入门


下一篇:mysql 临时表的好处